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 |
|---|---|---|---|---|---|
In today world most of application work based on Synchronous programming in which client sent request to server and server process the task and send response back to client. The synchronous controllers work well for concept but it cannot handle long running process.
When a user sends request to server then ASP.NET will provide one of the threads from the thread pool to handle the request. If request process is taking less time to complete then it provide fast output to client but when request take more time for process then it will block the thread and this thread will not be available to other request to handle.
If such large requests are send from users and all are long running process then server will be blocked then there will be no thread to handle this request and server will fire Error message “Server too Busy”. To handle this we need to use Asynchronous Controllers in asp.net mvc.
The working of Asynchronous Controllers is when user send request to Asynchronous Controllers the asp.net will provide a thread from Thread pool to handle request. If the request is small then it will process in normal way but in case if processing is taking too long time to complete then it will return process to thread pool for handling other request and whenever the asynchronous operation is complete, it notifies ASP.NET then asp.net gets a worker thread from the thread pool (which might be a different thread from the thread that started the asynchronous operation) to process the remmaining of the request, including rendering the response.
The convention required for follow when using Asynchronous Controllers. We have 2 Methods of Asynchronous Controllers
The async method will return void and it starts the asynchronous process. The syntax of async method in asp.net mvc like as shown below
Action Name Async
This method is called when the asynchronous process is complete. The syntax of Completed method in asp.net mvc like as shown below
We will learn these methods in details with simple Example. In this example we used web service (Weatherservice) in IndexAsync method in which we created a proxy client which will take Country name as input and will Return Cities then we will store cities in TempData["ListofCities"] when process will complete then it will call IndexCompleted() Method from which we will display result on view.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcAttribute.Controllers
{
public class Default2Controller : AsyncController
{
public void IndexAsync()
{
Weatherservice.GlobalWeatherSoapClient objservice = new Weatherservice.GlobalWeatherSoapClient();
TempData["ListofCities"] = objservice.GetCitiesByCountry("India");
}
public ContentResult IndexCompleted()
{
string Result = TempData["ListofCities"].ToString();
return Content(Result);
}
}
} | https://www.tutlane.com/tutorial/aspnet-mvc/asynchronous-controller-in-asp-net-mvc-4-with-example | CC-MAIN-2020-40 | refinedweb | 449 | 56.55 |
The Question is:
I have a pc running eXcursion that gets it's ip address from a DHCP server. Is
there a way for the VMS TCPIP services to resolve the ip address of the PC to
a node name?
The Answer is :
This depends greatly on how your local network is set to resolve these
DHCP systems. Clearly, your configuration is not using DNS/BIND for
this, as the host name information would thus be available to OpenVMS.
Your current (and apparently non-OpenVMS) DHCP server is probably using
the Windows Internet Naming Service (WINS) scheme and the NetBIOS protocol
for its name services activities and not the newer DNS/BIND-based approach
found on Microsoft Windows 2000 and in later Microsoft Windows systems.
(The WINS namespace organization is flat, and has been found to not scale
particularly well in moderate to large networks.) OpenVMS provides and
accesses and expects DNS/BIND support. (DNS/BIND scales rather better.)
Alternatively, you could move to the OpenVMS DHCP server (which uses
DNS), or you could upgrade and/or potentially reconfigure the DHCP server
you have to DNS and not WINS.
The Encompasserve DEC_NETWORKING conference topic 1448 has details
of one user's experiences setting up OpenVMS DNS/BIND for use with
the Microsoft Windows 2000 Active Directory environment, information
that may be of interest here. Access (read-only) to the Encompasserve
conferences (and Encompasserve membership information) is available at: | http://h71000.www7.hp.com/wizard/wiz_7954.html | CC-MAIN-2015-40 | refinedweb | 238 | 50.57 |
NAME
netlink - Communication between kernel and userspace (AF_NETLINK)
SYNOPSIS
#include <asm/types.h> #include <sys/socket.h> #include <linux/netlink.h> netlink_socket = socket(AF; /* PID of the sending process. */ };. Standard flag bits in nlmsg_flags --------------------------------- NLM_F_REQUEST Must be set on all request messages. NLM_F_MULTI The message is part of a multipart message.
VERSIONS
The socket interface to netlink is a new feature of Linux 2.2. Linux 2.0 supported a more primitive device-based netlink interface (which is still available as a compatibility option). This obsolete interface is not described here. NETLINK_SELINUX appeared in Linux 2.6.4. NETLINK_AUDIT appeared in Linux 2.6.6. NETLINK_KOBJECT_UEVENT appeared in Linux 2.6.10. NETLINK_W1 and NETLINK_FIB_LOOKUP appeared in Linux 2.6.13. NETLINK_INET_DIAG, NETLINK_CONNECTOR and NETLINK_NETFILTER appeared in Linux 2.6.14. NETLINK_GENERIC and NETLINK_ISCSI appeared in Linux 2.6 *)[4096]; struct iovec iov = { buf, sizeof(buf) }; struct sockaddr_nl sa; struct msghdr msg; struct nlmsghdr *nh; msg = { (void *))* for information about libnetlink. for information about libnl. RFC 3549 "Linux Netlink as an IP Services Protocol"
COLOPHON
This page is part of release 3.35 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at. | http://manpages.ubuntu.com/manpages/precise/en/man7/netlink.7.html | CC-MAIN-2014-10 | refinedweb | 203 | 62.34 |
Struts 2 Hello World Annotation Example
successfully developed and tested the Hello World application using
Java...Video tutorial of creating Struts 2 Hello World Annotation Example in
Eclipse... of creating Struts 2 Hello World Annotation Example:
Let's Starts
Hello world program
Hello world program hello world program
class Hello{
public static void main(String[] args) {
System.out.println("Hello World");
}
}
For more information, visit the following link:
http
Help me please!!! - Java Beginners
Help me please!!! im badly needing the complete code for this project in java!!!
can you please help me???!!!
it is about 1-dimensional array... the answers 8Hours from now!!!
Kindly help me!!
please!!please!!!
NOTE
please help me to give code - Java Beginners
please help me to give code Write a program that prints an n-level...!");
String str = buff.readLine();
int i=1;
int j;
while(i<=4){
for(j=1;j<=i;j++)
System.out.print(str);
i=i+1;
System.out.println
please help me - Java Beginners
please help me I have some error in this programe
//write acomputer programe using java to generate following series :
//output:
//1,2,3,0...[])
{
for( int a=1;b=2 ; i++)
a=a+2;
b=b-2;
System.out.print
please help me here.. - Java Beginners
please help me here.. ..uhhmm.. im a little bit new to java and i go....");
}
}
}
----------------------------------------------------
Read for more information,...");
}
}
}
this is the program i made..it's supposed to compare the strings but it doesn't
help please - Java Beginners
help please i wrote this program
but the function newLine dosnt work with me and i dont know where is exactly the error
this is the code i...));
for(int i =0 ; i<8){
byt= s+ byt;}
System.out.println(" Byte
Hi ..I am Sakthi.. - Java Beginners
Hi ..I am Sakthi.. can u tell me Some of the packages n Sub...);
}
}
---------------------------------------------
Please visit for more information.
http... that is available in java and also starts with javax. package
HEMAL RAJYAGURU
Spring Hello World prog - Spring
Spring Hello World prog I used running the helloworld prog code... getting null pointer exception. as shown below. I added all the jars and my folder structure is similar to what showed in the website. I guess the null pointer
Beginner
Beginner Hi Friends,
I am new to ejb. I don't know how to begin with to run ejb application. I have eclipse,apache tomcat server,jdk 1.6....
Hello Friend,
Please visit the following links:
http
Develop Hello World example using Spring 3.0 Framework
Spring 3 Hello World Example
..., create new project in Eclipse IDE
and then write simple Hello World application...:\>
If you don't know how to install Java read
please help me to give code - Java Beginners
please help me to give code Write a program that reads a file named famous.txt and prints out the line with the longest length. In the case...();
}
}
}
-------------------------------
read for more information,
please help me in a java program !! - Java Beginners
please help me in a java program !! the porgram should use... , StackX, Graph , DFSApp
"DFSApp is the one from which i modify the graph and run the program"
i still need to modify the method kosaraju in the class Graph
please help me to give code - Java Beginners
please help me to give code Write a program that uses loops...; k<=4; k++){
System.out.print(k+"|");
for (int i=1; i<=4; i++){
System.out.print(i);
}
System.out.println
please help me for this program - Java Beginners
please help me for this program Write a program that asks the user...=input.nextInt();
System.out.println();
for(int i=num1;i<=num2;i++){
System.out.println(i);
}
}
}
Thanks
Hello World in Echo3 framework
Hello World in Echo3 framework
Since "Hello World" example is everyone's... with
the "Hello World" example in Echo3. We have illustrated the first
Please help me to solve these programs in Python - Java Beginners
Please help me to solve these programs in Python 1. Write a program...();
}
}
}
--------------------------------
read for more information,...,
public class PrintExamp{
public static void main(String[] args){
int i=1
urgent...pleAse help me.....please!
urgent...pleAse help me.....please! please help me urgent! how can i do dictionary with the use of array code in java, where i will type the word then the corresponding meaning for that word will appear...thanks
Core Java Hello World Example
will create here a Hello World Java program then I will explain the
terms what...Create Java Hello World Program
This tutorial explains you how to create a simple core Java "Hello World"
application. The Hello World application
Java hello world
Java hello world
..., JavaBeans, Mobile Java. Genarally, Hello world program is the first
step.../java/beginners/hello_world.shtml
plz help me - Java Beginners
give me reponse my persinal given id Hi ragni,
i am sending...plz help me Thanks deepak continue response..i face some problem
i.... if i m login then display sessionvalid .jsp not display admin page i want display
help me please
help me please how can i do dictionary with the use of array code in java, where i will type the word then the corresponding meaning for that word will appear...thanks??
Please help me?? Question_1: Using one-dimension array of primitive... and Iterator.
Step1: Create a new java file
FileName: ListDemo.java
import...?
Iterator i=myList.iterator();
System.out.println("Printing element by element
Hello World Program
Hello World Program write a java program that continuously prints HelloWorld! to the screen(once every second ) and exists when press the enter key... = new DisplayMessageContinuously("Hello World ", 1000);
th.start
Servlet Annotation Hello World Example in Eclipse
Servlet Annotation Hello World Example in Eclipse
In this tutorial you will learn how to create an annotated servlet in web
applications. In this example I...();
out.println("<h2>Hello World Servlet Annotation Example</h2
Java Hello World code example
Java Hello World code example Hi,
Here is my code of Hello World program in Java:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World
Hello world (First java program)
Hello world (First java program)
...
and running. Hello world
program is the first step of java programming language... learned how to
write and then test the Hello World! java program.
New to Java Please help
New to Java Please help Hi I need help, can some one help me with this. I am currently doing a project.
drop me an email to my email address. Thanks!
If you are new in java, then you need to learn core java
help me for doing project - Java Beginners
help me for doing project i am handling the project that "email... the email headers and how to display the port and user's information please help me thanks in advance who are going to help me bhanukiran
Nag(Beginner)
Nag(Beginner) sir i am new to java.. i want to know what topics comes under core java, adv. java and also the remaining topics... plz tell me
Java Tutorials
please help me to give code - Java Beginners
please help me to give code Write a function, sliding(word, num)that behaves as follows. It should print out each slice of the original word having length num, aligned vertically as shown below. A call to sliding(examples, 4
Am i convetrting the code right ? - Java Beginners
; sp.WriteLine("Hello World!"); sp.Close();}
Java
Enumeration pList...Am i convetrting the code right ? C#
private void button... = port.getOutputStream(); String str = "Hello World!"; byte[] b = str.getBytes
java please please help
java please please help Dear Friends plz help me to complete...[] to HashMap so that i can seperate key and value using Map.Entry.Please help me!
...[])
{
String b[]=a.split(";");
for(int i=0;i
Apache Axis2 Hello World Example
Apache Axis2 Hello World Example
Apache Axis2 Hello World Example
In this section we will develop a simple Hello World... engine and then deploy and
test the application.
About the Hello World Web
to all Experts.. please help me. im using a Jcreator. - Java Beginners
to all Experts.. please help me. im using a Jcreator. 3. Write a program that asks the user to enter a word. The program will then repeat word...=word.length();
System.out.println();
for(int i=0;i
Beginner
Beginner how to call a gui class from applet class
Hello Friend,
Please visit the following link:
Thanks
please help me.
please help me. How to read a properties file in java with a suitable example.
Please send me.
Thanks
Trinath
Please visit the following link:
Java read properties file
Help me - Java Beginners
Help me please help me in writing a program in java "A student has a name,roll no., class, home address, date of birth. First dessigne a suitable class for date, write constructor and get and set functions. Then dissign a class
Please help me.
Please help me. Hi i am trinath in below there is a url.In that url there is a code of edit a jsp page.I understand that code but only one thing i not get it i.e; What is the work of "id".and what is the data type of id?
http
Please check it and let me know - Java Beginners
Please check it and let me know Hi friends,
your las suggession... code and requirement please check it and solve again thanks
Requirements:- I... the subject c & practical type marks only.
I am sending all code.
User.jsp
java beginner
java beginner hai a i'm beginner 2 java...
i want to fetch data from database using combo box(drop down list) without using javascript...when i... that should take from db..i,e fetched from db only...
n also give me a good example
help please!!! T_T
help please!!! T_T what is wrong in this?:
import java.io.*;
class...("please enter your name:");
name1= input.readline();
System.out.println("please... {
String name1;
String name2;
System.out.println("please enter
Help me - Java Beginners
Help me I m using session in my project session is activated and admin_home.jsp page will be display but data r not displayed plz guide what is incorrect my code
help me - Java Beginners
help me i want to create a login form in java with jdbc connection... form for new user where name phoneno adress will be there plese i want this ...();
int i=st.executeUpdate("insert into login(firstname,lastname,username
Reply Me - Java Beginners
project deadline is very near
this code i am using then i got the some error "code too large for try statement" please help me its very urgent...Reply Me Hi Amardeep
I am sending database table name,code
JSF Hello World
JSF Hello World
... to print hello world in JSF application using
NetBeans IDE. NetBeans IDE provides... classes etc.
Steps to create JSF Hello World Example:
1. Go to your project
java beginner
java beginner HI
I am swetha iam confused when to use service(), doget(), dopost() method in servlets
Any request from client are handled initially by the service() method before delegating to the doXxx() methods
Reply me - Java Beginners
Reply me Hi,
this code is .java file but i am working in jsp... in the database...
if u understood my question then then please send me code oterwise...[]){
Test1 t = new Test1();
t.search();}
} Hello
Ragini
Generating Random Numbers to Fill array. Java Beginner needing help!
Generating Random Numbers to Fill array. Java Beginner needing help! Hello all!
I am new to this site, and Java programming.
My problem is: Write...() methods.
I am new to Java programming and this seems mind blowing to me :(
help - Java Beginners
help hi,i am new to java & i do not have progamming background, i just run the hello world example given, but i am not seeing the output, it just... to do or what could be the issue? plz help hello,
First complie ur
Why PriorityQueue gives such a strange behaviour?
Why PriorityQueue gives such a strange behaviour? I am using...(r2.getId());
return 0;
}
}
And also I am storing this queue... adding element I am first reading stored entries and then adding new entry and again... filed?.
Please help me
Thanks
help - Java Beginners
from the main().
Hi friend,
I am sending a link. This link will help you.
Please visit : The programming task
You are to write a Java application
Please help me to learn - WebSevices
Please help me to learn Please help me to learn Java Fast
Java Variables Help Please!
Java Variables Help Please! Hi, I just started with java and i need help with my school project, this is it so far:
import java.util.*;
public...
public static void menu() {
int choice;
do{
System.out.println("\t
t:selectOneMenu - Java Server Faces Questions
select One Menu Hi, I wanted to create a menu to select or choose from ..for my home page.Can anyone please help?Thanks in Advance. Hi friendRead for more information,
Java Help Please
Java Help Please I can't seem to figure out how to make this program, can some one help me please? It is due soon!!
4) Write a program that will take an input (Date object will contain fields for the month, day, and year -
more doubts sir. - Java Beginners
more doubts sir. Hello sir,
Sir i have executed your code... own browser.Hope you will help me out.And also sir i need the progressbar... exoplorer such as search bar and some more buttons.Sir help me out
Help please, some strange errors
Help please, some strange errors Sorry about this messy formatting. As a beginner in java i got no idea which part of the code is creating... is causing that run-time errors? Any kind of help will be helpful to me. and let
Displaying Hello World using GWT
Hello World
using GWT in java. By GWT we mean Google Web Toolkit,Google Web... Displaying Hello World using GWT
... involved in displaying the Hello World message using Net Beans
IDE 6.1
please help me to overcome this problem
please help me to overcome this problem how to make it easy to write java code. can u please give me suggestions
plz help me - Java Beginners
plz help me Deepak I can write a sessioon code plz help me admin_home.jsp page is display but data is not disply plz help me what is wrong
help me
help me Dear sir/medam
i would like to know how to use the java... the order,
Fourth button is Find length of text. and there are panels. Please help me. i want to write the code on this program. please share ur idea.
Deploying Struts and testing struts 2 hello world application
Deploying Struts and testing struts 2 hello world application
I am assuming that you have already installed ant.../
and then select "Run Struts 2 Hello World Application" from the
list.
please tell me
please tell me Actually i am working on a Project tiitle is JavaMail System,
1)How to configure java mail API and a Demo Program for Sending mail and Receiving using JSP and Servlet
Android Studio Hello World Tutorial
Android Studio Hello World Tutorial - Learn application development using Android Studio IDE
Video tutorial on developing Hello World Example using Android... the steps you should
follow to quickly develop and test the Hello World example-help - Java Beginners
java-help hello sir, please help me.....the below given is the output.java program
here in this program am using the stmts
ta. append("clustering... i want this output.java file to print in textarea.
now this output.java
Display JSP selected listbox and checkbox in xml-please help me
as selected multiple checked checkboxes.
Please help in this how to do this.....I am new to java & jsp
I need your help.
Regards...Display JSP selected listbox and checkbox in xml-please help me Hi "
Struts 2.1.8 Hello World Example
Struts 2.1.8 Hello World Example
In this section we will learn how to develop our first Hello World... to develop simple Hello World
example in Struts 2.8.1. You will also learn how
Hello world (First java program)
Hello world (First java program)
.... Hello world program is the first step of java programming
language... learned how to
write and then test the Hello World! java program
JSP Hello World
JSP Hello World
We are going to discus about JSP hello world. In this example... instances. we can print
simple "Hello World" String on web browser...;% JAVA CODE %>
Example
<%@ page language="java" contentType="
Hello World Program in JRuby
"java"
stringHello= "Hello World"
stringDate...
Hello World Program in JRuby
... HelloWorld.rb
Hello World
Date := Tue Sep 23 18:12:26 GMT+05:30 2008
i am confused here on what to write can some 1 help out here - Java Beginners
i am confused here on what to write can some 1 help out here i don't quite understand how to code it so can some one help out | http://www.roseindia.net/tutorialhelp/comment/9609 | CC-MAIN-2013-48 | refinedweb | 2,857 | 67.96 |
Use Action Filters to cut down your context.SaveChanges calls
Jon Hilton
・1 min read
If you use Entity Framework Core you will probably find yourself writing something like this over and over and over again...
context.SaveChangesAsync();
Where context refers to an instance of your Entity Framework Database Context.
This raises a few problems.
First of all it's way too easy to forget and wind up spending minutes (or even hours!) figuring out why your changes aren't being saved.
Secondly it gets everywhere and adds to the overall amount of "infrastructural" code in your code base which isn't actually part of your key business logic.
Thirdly (and perhaps most importantly) it tends to wind up being used in inconsistent ways.
So instead of saving everything logically, in one place, you can easily end up with multiple saves occurring at different times and different layers of your application.
This can make your application somewhat unpredictable and also lead to inconsistent state.
If one part of your code fails, but other code has already saved its state to the DB, you've now got a job to figure out what was saved and what wasn't.
ASP.NET Core Action Filters to the rescue
Here's an alternative.
Use an Action Filter to always make a single call to
SaveChanges when any of your MCV Action methods finish executing.
This way you can be sure that the action will either succeed (and everything will be persisted in a predictable fashion) or fail (and nothing will be persisted, leaving the user free to try again, or complain!)
public class DBSaveChangesFilter : IAsyncActionFilter { private readonly MyContext _dbContext; public DBSaveChangesFilter(MyContext dbContext) { _dbContext = dbContext; } public async Task OnActionExecutionAsync( ActionExecutingContext context, ActionExecutionDelegate next) { var result = await next(); if (result.Exception == null || result.ExceptionHandled) { await _dbContext.SaveChangesAsync(); } } }
You can register this in
startup.cs and forget all about invoking
SaveChanges() anywhere else in your code (and focus on your features instead!).
public void ConfigureServices(IServiceCollection services){ // rest of code omitted services .AddMvc(opt => opt.Filters.Add(typeof(DBSaveChangesFilter))) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
This gives you a handy "transaction per action" and helps avoid your database getting into an inconsistent state.
Want to get these articles first? Click here to have me email them to you :-)
Clean up your code with these tips!
Learning new patterns to make your code smaller, and more clear.
Detecting Sync over Async Code in ASP.NET Core
Derek Comartin -
Episode 029 - Simplifying the BFF with ProxyKit - ASP.NET Core: From 0 to overkill
João Antunes -
Introduction to ASP.NET Core Integration Testing
Kai Oswald -
Does this work because the DB context is a scoped DI service?
Assuming you had, let's say, multiple services that individually made changes via the DB context - all those changes would be saved in bulk at once?
Sounds like that would be a potential performance benefit in generic scenarios too eh?
Very interesting approach 😉
Hi James, yep you've got it.
This essentially gives you a transaction per web request, so you can be confident the operation either worked or it didn't (and you won't get into a "half n half" state where some things are persisted to the database but others aren't).
By default ASP.NET Core will commit everything in one transaction when you call SaveChanges, so every modified entity will persisted in one go :-)
Nice - did not know that! Thanks for the extra details about the transaction.
This tactic has lots of other interesting benefits 👌
I like this idea alot.
Great article! Really nice approach. What can I do in this scenario if I want to return the generated id from the insertion?
Thanks Leonardo,
As to your question. Yeah that's a little tricky.
I've tended towards using GUIDs recently for this exact reason. I don't like the idea of having to round-trip to the database to get an id for an entity.
Apart from anything it makes testing harder because the database ends up being involved in something which could otherwise be tested entirely by spinning up instances of entities in memory and exercising them without ever hitting the database.
I guess a pragmatic solution is to still call SaveChanges where absolutely necessary (to generate an id for example) but try to engineer away from it where you can :-) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/jonhilt/use-action-filters-to-cut-down-your-contextsavechanges-calls-2a17 | CC-MAIN-2019-43 | refinedweb | 725 | 55.54 |
I am aware of the existence and purpose of
collections.namedtuple, but I have noticed that, at least in IDLE (3.2.2), this factory function is also in
functools:
>>> import functools >>> functools.namedtuple <function namedtuple at 0x024B41E0>
It also exists in
collections as expected, and is the same function:
>>> import collections >>> collections.namedtuple is functools.namedtuple True
No docs I can find ever mention
namedtuple being anywhere other than collections. So: is this standard, or just an IDLE weirdness? If it’s just IDLE, is it a bug or a Why would
namedtuple be in two places – and, indeed, in whose warped mind does it make sense in
functools of all places?
Best answer
In Python 3.2.2,
functools.py contains the following import:
from collections import OrderedDict, namedtuple
It seems pretty clear that it’s just a convenience import for the module’s implementation, and is not intended to be part of its public interface. | https://pythonquestion.com/post/python-functools-namedtuple/ | CC-MAIN-2020-16 | refinedweb | 158 | 56.66 |
Blockstack Core v0.14 Release
This is the largest release of Blockstack Core since the initial release in September 2015 and is a major update. Version 0.14 is a hard fork that will activate at Bitcoin block 436363. This release removes our dependence on a distributed hash table (DHT) network, improves performance, reduces memory footprint, and adds support for multisig and a RESTful API.
Below are some notable features that are included in this release:
- Better Data Reliability. When we launched Blockstack, we included a default DHT-based network for storing additional data. The pointers for data were in the blockchain and the off-chain routing data (zone files) were stored in the DHT. DHTs are traditionally unreliable and hard to scale and we faced these challenges in our production deployment. The biggest change in v0.14 is that it replaces the Blockstack DHT with a new unstructured BitTorrent-like network called the Atlas network which is much more reliable than the previous DHT network.
- 20x RAM reduction. The earlier version of Blockstack Core used a flat JSON file for storing data, which worked at small scale but had performance issues at larger scale. More specifically, the memory footprint of using a flat JSON file became too much. Blockstack Core v0.14 stores its state in a sqlite3 database, which yields an overall 20x reduction in RAM usage (down to 150MB from 3GB), and reduces the complexity of adding support for new types of data queries.
- 6x Faster Synchronization. One of the main bottlenecks for boot up time for new nodes is the speed at which it can synchronize with the underlying blockchain. The v0.14 release of Virtualchain now fetches most of its data from Bitcoin’s peer-to-peer network, instead of via RPC. This yields a 6x performance improvement and removes the need for the multiprocess work pool used in v0.13. We had to write custom software to fetch data directly from the Bitcoin backplane, instead of the widely used RPC interface, and we hope that other projects in the ecosystem can also use our open-source code for faster block-fetching.
- Multisig Support. Security of name ownership is very important to us. The v0.14 release now supports multisig — that is, a quorum of key-pairs can pay for and manage names. This is more secure than using a single key, since now the user can divide up the set of keys across multiple devices and multiple trusted parties. Version 0.14 of the client release defaults to a 2-of-3 quorum, using pay-to-script-hash Bitcoin addresses.
- RESTful API. In order to make it simpler to use Blockstack Core, we’ve included a RESTful interface with built-in documentation in the v0.14 release, in addition to the already existing RPC interface. We’ve also merged independent servers/components like the resolver, search, and a few others into a single, easily accessible API with the v0.14 release.
- Testnet Support. We want to make it easier for developers to rapidly test their applications without worrying about spending tokens on the live network. The v0.14 release supports Bitcoin’s testnet network, which we leverage in version v0.14 in our integration test framework.
Better Data Reliability
One of the biggest milestones of this release is the addition of the Atlas network. It solves a long-standing issue of ensuring zone file data reliability. We want to ensure that zone files stay online and don’t get lost, even if Blockstack nodes come and go. This is vital for resolving Blockstack profiles, since zone files link the on-chain pointers to off-chain state in external storage.
The Problem with DHTs
Before v0.14, we had used a patched Kademlia DHT implementation for hosting zone files. Our patches ensured that (1) each key was the hash of its value, and (2) each key corresponded to an accepted name-update Blockstack transaction on Bitcoin. This prevented most classical DHT attacks — no one could overwrite a user’s key/value pairs, and no one could flood the DHT with lots of junk data.
However, DHTs are still vulnerable to routing attacks. Instead of trying to mess with the key/value pairs, an attacker can add and remove nodes in order to take control of individual hash buckets. These nodes can simply deny requests for data, censoring keys. If they take over all nodes with a copy of a key/value pair, they can simply discard it, leading to permanent zone file loss. This is a fundamental challenge to using structured overlay networks for decentralized storage (DHTs being one example). Since nodes do not store a full replica of the state, they have to route data requests to each other. Since anyone can add nodes to these networks, attackers can take control of routes to deny service and destroy data.
Atlas Network
We overcome the challenges with DHTs with a new network called the Atlas network. With the Atlas network we make use of the property that (1) zone files are small (<4KB each), and (2) the total number grows at a fixed rate. It doesn’t take a lot of disk space to have each node host a full copy of all zone files (only ~300MB today). The Atlas network solves a special case of the general problem of reliable decentralized storage — the case where (1) the data set is small in size and (2) there is a full index of data available to the network.
Atlas nodes maintain a 100% state replica, and they organize into an unstructured overlay network to stay resilient against targeted node attacks. An Atlas node works a lot like a BitTorrent node. Each node gets the set of zone file hashes from the blockchain, and they constantly try to get zone files they don’t have.
The Atlas network implements a K-regular random graph. Each node selects K other nodes at random to be its neighbors via MHRWDA, and regularly asks them for the set of zone files they have. Peers pull missing zone files in rarest-first order to maximize availability (like BitTorrent), and store them both to locally and at remote backup locations (e.g., a user chosen storage service like Dropbox or S3). When it receives a missing zone file from a client, the node pushes it to its immediate neighbors that don’t have it yet.
The Atlas network is much more reliable than the previous DHT network. Like the DHT, Atlas nodes already know the hashes of the zone files, so no one can upload invalid data. But unlike the DHT, data is replicated on O(N) nodes instead of only on a small subset of nodes.
This strategy makes unavailability attacks expensive. To censor a target zone file for a single node, an attacker must persistently eclipse all of that node’s neighbors. Censoring the entire network requires attacking O(N) nodes. By contrast, only O(log N) DHT nodes need to be taken over to censor a zone file for everyone. Even then, the victim node will detect the censorship unless the attacker also eclipses the victim’s Bitcoin node (which requires building a fraudulent blockchain fork with sufficient PoW).
We believe that the Atlas network is a major step forward towards having a reliable, hard-to-censor, and decentralized data store for zone files and we’re excited to announce that v0.14 will start using the Atlas network in production. We plan to release detailed documentation and design on the Atlas network soon.
Consensus Notes
Version 0.14 is a consensus-breaking release — once deployed, it will not be compatible with earlier releases. This is because earlier releases do not accept transactions sent from multisig outputs. As such, v0.14 is a hard fork from v0.13. Every node operator is encouraged to upgrade to v0.14 as soon as we release it, since v0.13 and v0.14 will diverge into two separate fork sets.
Version 0.14 implements phase 1 of a 2-phase improvement in how we manage names and identities. The end goal is that a user’s on-chain identity information (i.e. its zone file and public key hashes) will have a unique serial number in the .id namespace and will never expire. Names in the .id namespace will point to these identities, and must be periodically renewed. Version 0.15 will implement phase 2 of our improvement plan, and will be implemented as another hard-fork one year from now. The discussion thread and a description of the plan can be found here.
We will switch our infrastructure over from v0.13 to v0.14 at block 436363 in the Bitcoin blockchain. After this block height, v0.13 and v0.14 are expected to diverge, since this is the height at which the consensus-breaking changes in v0.14 will activate.
Node operators have about 3 weeks to upgrade. If you need help doing so, please drop us a line on our Slack channel at chat.blockstack.org.
Getting Blockstack Core
Please check out the repository on GitHub, and star it if you like it!
Please note that v0.14 will be unusable until block 436363. This is when the new features activate. However, if you want to test them in an offline deployment, see the documentation here.
Contributors
We would like to thank the following people for helping us get the 0.14 release ready. Thank you everyone for sending pull requests, helping us test the software, submitting bug reports, and being patient with us while we fix them!
- @aagorelik
- Aran Dunkley
- Burt Bielicki
- Carver Harrison
- Charles Lehner
- @cryptid11
- Daniel Buchner
- Derek Martin
- Donncha O’ Cearbhaill
- @fpischedda
- George Ty
- @Gitju
- Guy Lepage
- @JFiscella
- John Light
- Jude Nelson
- Justin Drake
- @JZA
- @koinster
- Muneeb Ali
- Larry Salibra
- Odin Hørthe Omdal
- Pandu Rao
- @ruxton
- Ryan Shea
- Sam Wood
- Samantha Atkins
- Santiago Siri
- Sebastian Pir
- Stanislas Marion
- Stephen Edgar
- Stian Ellingsen
- @syck
- Whit Jackson
- @wutengcoding
- Xiaowei Liu
- Website . blockstack.org
- Slack . chat.blockstack.org
- Reddit . r/blockstack
- Twitter . @blockstackorg
- Medium . blog.blockstack.org
- GitHub . @blockstack
- YouTube . | http://blockstack.ghost.io/blockstack-core-v0-14-release/ | CC-MAIN-2017-43 | refinedweb | 1,692 | 64.1 |
Merge sort is a sorting algorithm that follows the divide and conquers method. we use sorting techniques to rearrange a list of elements into a sorted list, either ascending or descending depending on the requirement. Java uses merge sort algorithm for array of objects. The default sorting is done in ascending order. We divide the elements into two halves, make the required steps for the two halves separately, and then we merge the two halves. The two halves are:
Divide: We divide the array into two halves and selected the middle element as out pivot element. We carry out this step till we divide the whole half array into little half arrays.
Conquer: We sort the halves of the array. We will then merge the divided arrays.
We can say merge sort is performed as merge(arr, a, m, r) that assumes arr(a,…m) and arr[m+1….r] are in the sorted form then merging two sorted set of elements into one set. For example, we have a list of elements:
23, 10, 62, 25
Step 1: we will divide the above set of 4 elements into 2. The first set becomes 23, 10 and second set becomes 62, 25
Step 2: First we check if the first half is sorted. It is not; therefore we swap both the elements. Now we get the first set as 10, 23
Step 3: Now we check if the second half is sorted or not. It is not; therefore we swap both the elements. Now we get the second set as 25, 62
When we merge both the sets using these 3 steps, we get the sorted list of elements as:
10, 23, 25, 62. It is a sorted set completely
Merge Sort Algorithm
- Find middle point to divide the array into two.
Middle m = (a+r)/2
- Call mergeSort for first half after division
Call mergeSort (arr, a, m)
- It Calls mergeSort for second half
Call mergeSort (arr, m+1, r)
- Merge the two halves sorted in step 2 and step 3.
Call mergeSort(arr, a, m, r)
Merge Sort Program in Java
package MyPackage; public class DeveloperHelps{ void merge(int arr[], int beg, int mid, int end){ int l = mid - beg + 1; int r = end - mid; int LeftArray[] = new int [l]; int RightArray[] = new int [r]; for (int i=0; i<l; ++i) LeftArray[i] = arr[beg + i]; for (int j=0; j<r; ++j) RightArray[j] = arr[mid + 1+ j]; int i = 0, j = 0; int k = beg; while (i<l&&j<r){ if (LeftArray[i] <= RightArray[j]){ arr[k] = LeftArray[i]; i++; } else{ arr[k] = RightArray[j]; j++; } k++; } while (i<l){ arr[k] = LeftArray[i]; i++; k++; } while (j<r) { arr[k] = RightArray[j]; j++; k++; } } void sort(int arr[], int beg, int end){ if (beg<end){ int mid = (beg+end)/2; sort(arr, beg, mid); sort(arr , mid+1, end); merge(arr, beg, mid, end); } } public static void main(String args[]){ int arr[] = {23,51,22,45,1,4,90,29,17,55}; DeveloperHelps ob = new DeveloperHelps(); ob.sort(arr, 0, arr.length-1); System.out.println("Sorted array suing merge sort is"); for(int i =0; i<arr.length;i++){ System.out.println(arr[i]+"");} } }
The output of the above program is:
Sorted array suing merge sort is 1 4 17 22 23 29 45 51 55 90
Merge sort time complexity
- We use it for sorting linked lists. Linked nodes may not be located adjacent in the memory in case of linked lists. We can insert extra elements in O(1) space in O(1) time. Hence we can implement the sorting technique without using that extra space in the linked lists
- We use the algorithm in the inversion count problem.
- The algorithm can also be used in external sorting.
The time complexity is O(nLogn). In case of merge sort, the average, worst and best complexities are the same. However, the space complexity in worst case scenario is O(n). | https://www.developerhelps.com/merge-sort/ | CC-MAIN-2021-31 | refinedweb | 668 | 68.2 |
2. Dataset¶
The dataset classes aim to emulate some of the functionality of NumPy’s
ndarray class. In addition, datasets can have items which contain multiple
elements - these are known as compound datasets.
2.1. Generic dataset¶
- Capabilities
- Indexing
- Slicing (now returns views)
- Boolean dataset selection
- Some advanced integer indexing
- Arithmetic operations
- Comparison and logic operations
- Mathematical and statistical functions
- Key differences
- Incomplete implementation all NumPy’s methods
- ndarray.get_elements method to get view of n-th elements of a compound array
- Implemented NumPy methods (1.10)
- Array attributes: shape, ndim, data, size, itemsize, nbytes, T, view, indices
- Array methods: copy, fill, reshape, resize, transpose, flatten, squeeze, take, put, max, min, sum, prod, all, any, argmax, argmin, cumsum, cumprod, argsort
- Array creation: array, zeros, zeros_like, ones, ones_like, empty, full, full_like, eye, identity, linspace, logspace, arange, diag, diagflat, meshgrid, indices
- Array manipulation: append, tile, repeat, concatenate, vstack, hstack, dstack, array_split, split, vsplit, hsplit, dsplit, fliplr, flipud, roll, rot90, reshape, resize, ravel, rollaxis, atleast_1d, atleast_2d, atleast_3d
- Array modification: fill, append, sort
- Array comparisons and logic operations: all, any, greater, greater_equal, less, less_equal, equal, not_equal, logical_not, logical_and, logical_or, logical_xor, allclose, nonzero, select, where, choose
- Indexing operations: unravel_index, ravel_multi_index
- Maths: add, subtract, multiply, divide, negative, power, real, imag, absolute, exp, log, log2, log10, expm1, log1p, sqrt, square, reciprocal, angle, conjugate, floor_divide, remainder, phase, signum, diff, gradient, roots, modf, fmod, interp
- Trig: sin, cos, tan, arcsin, arccos, arctan, arctan2, hypot, sinh, cosh, tanh, arcsinh, arccosh, arctanh, deg2rad, rad2deg
- Matrix: dot, vdot, inner, outer, matmul, tensordot, kron, trace
- Linear algebra: eig, eigvals, cholesky, qr, svd, norm, cond, det, solve, inv, pinv, matrix_power
- Rounding: rint, ceil, floor, trunc, fix
- Bitwise: bitwise_and, bitwise_or, bitwise_xor, invert, left_shift, right_shift
- Stats: amax, amin, ptp, mean, std, var, cumprod, cumsum, histogram
- Random: rand, randint, random_integer, randn, exponential, poisson, seed
- Non-NumPy
-
This is an example of dataset usage:
import scisoftpy as dnp # create a 1D dataset from 0 to 9 of doubles a = dnp.arange(10) # make it have 2 rows and 5 columns a.shape = 2,5 a # create new dataset with each element raised to power of 5/2 b = dnp.power(a,2.5) # create new dataset that is sum of two datasets c = a + b # modify dataset in-place by dividing each element by corresponding # element in other dataset c /= a # reassign a to a new (integer) dataset of 2 rows and 3 columns a = dnp.array([[0, 1, 2], [3, 4, 5]]) # create new dataset from a slice of dataset which takes just the 2nd column d = a[:,1] # modify dataset and set a slice to a given value a[1,0:1] = -2 # b is a double dataset (highest type that can contain all entries is used) b = dnp.array([[-2, 2.3], [1.2, 9.3]]) # modify dataset and set a slice to the values in another dataset a[:,1:] = b # notice the values from b are truncated to integers a # in Jython only import Jama.Matrix as Matrix # make a dataset from a Jama Matrix m = Matrix([[0,1,1.5],[2,3,3.5]]) dj = dnp.array(m) # directly da = dnp.array(m.getArray()) # from Java array db = dnp.array([m.getArray(), m.getArray()]) # from list of arrays import scisoftpy.random as drd # create dataset of shape 3,12 of uniform random numbers between 0 and 1 a = drd.rand(3,12) # take item-wise sine dnp.sin(a) # create dataset of shape 3,4 of random integers from 0 to 11 inclusive drd.randint(12, size=(3,4)) # comparison and logic # create boolean datasets where items are true where condition applies c = a >= 0.3 d = a < 0.2 # check if all or any of items in these are true all(c) any(c) all(d) all(d) # how many were true c.sum() d.sum() # flatten 1D dataset of items which were >= 0.3 a[c] # assign value where items are < 0.4 a[a < 0.4] = 0 #
2.2. RGB dataset¶
When a colour image is loaded (as described in the next chapter), a RGB dataset
is created. This type of dataset has items which are tuples of three 16-bit
integers. Each integer represents a value of one of the colour channels. The
channels are ordered as red, green and blue. There are four extra attributes
to an RGB dataset,
red,
green,
blue and
grey which retrieve
copies of the colour channel or a weighted mixture of channels in the grey case.
There are also four extra methods:
get_red(self, dtype=None) get_green(self, dtype=None) get_blue(self, dtype=None) get_grey(self, cweights=None, dtype=None)
where
dtype is an optional dataset type (default is
int16) and
cweights is an optional set of weight for combining the colour channel.
The default weights are (0.299, 0.587, 0.114) which correspond to the NTSC
formula for convert RGB to luma values.
2.3. Lazy dataset¶
Sometimes a need arises to reference a multitude of datasets or very large datasets. This need can occur when dealing with datasets held in tree structured-file formats. The memory usage could easily exceed most computers’ capabilities, so to facilitate this need, the concept of a lazy dataset is required. The laziness refers to the deferred action of loading data from file into memory. This in turn dictates that lazy datasets have few properties:
- shape
- shape of dataset
- name
- name of dataset
- dtype
- dataset type
The only access is provided by indexing or slicing a lazy dataset:
v = lazy[0,1] # index an item s = lazy[1,:] # slice entire = lazy[...] # to load in entire dataset (do so with caution) | https://alfred.diamond.ac.uk/documentation/manuals/Diamond_SciSoft_Python_Guide/trunk/dataset.html | CC-MAIN-2018-30 | refinedweb | 935 | 58.01 |
If you're looking for a namespace that begins with "Microsoft.DirectX" you won't find one. XNA isn't MDX. All the namespaces you need for XNA are under Microsoft.XNA. For example, what used to be the DirectX device is now the GraphicsDevice and is in the Microsoft.XNA.Framework.Graphics namespace, as are textures, surfaces, etc.
If you're using XNA, you DON'T want to be referencing any of the Managed DirectX assemblies. They don't play together at all. You can use DirectInput, but don't try to use the others.
Why do you think you need to reference anything in the Microsoft.DirectX... namespaces?
Well, as I said, using DirectInput is fine. I thought you were trying to use DirectX graphics, which won't work with XNA.
The "right" way is to add a reference to the Microsoft.DirectX.DirectInput assembly as you showed in your previous post. Just select Microsoft.DirectX.DirectInput. Then add "using Microsoft.DirectX.DirectInput;" to whatever source files will be making use of the namespace. | http://forums.xna.com/thread/41485.aspx | crawl-001 | refinedweb | 176 | 62.14 |
GLM: Robust Regression with Outlier Detection¶
A minimal reproducable example of Robust Regression with Outlier Detection using Hogg 2010 Signal vs Noise method.
- This is a complementary approach to the Student-T robust regression as illustrated in [Thomas Wiecki’s notebook]((GLM-robust.ipynb), that approach is also compared here.
- This model returns a robust estimate of linear coefficients and an indication of which datapoints (if any) are outliers.
- The likelihood evaluation is essentially a copy of eqn 17 in “Data analysis recipes: Fitting a model to data” - Hogg 2010.
- The model is adapted specifically from Jake Vanderplas’ implementation (3rd model tested).
- The dataset is tiny and hardcoded into this Notebook. It contains errors in both the x and y, but we will deal here with only errors in y.
Note:
- Python 3.4 project using latest available PyMC3
- Developed using ContinuumIO Anaconda distribution on a Macbook Pro 3GHz i7, 16GB RAM, OSX 10.10.5.
- During development I’ve found that 3 data points are always indicated as outliers, but the remaining ordering of datapoints by decreasing outlier-hood is slightly unstable between runs: the posterior surface appears to have a small number of solutions with similar probability.
- Finally, if runs become unstable or Theano throws weird errors, try clearing the cache
$> theano-cache clearand rerunning the notebook.
Package Requirements (shown as a conda-env YAML):
$> less conda_env_pymc3_examples.yml name: pymc3_examples channels: - defaults dependencies: - python=3.4 - ipython - ipython-notebook - ipython-qtconsole - numpy - scipy - matplotlib - pandas - seaborn - patsy - pip $> conda env create --file conda_env_pymc3_examples.yml $> source activate pymc3_examples $> pip install --process-dependency-links git+
Setup¶
In [19]:
%matplotlib inline import warnings warnings.filterwarnings('ignore')
In [20]:
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy import optimize import pymc3 as pm import theano import theano.tensor as tt # configure some basic options sns.set(style="darkgrid", palette="muted") pd.set_option('display.notebook_repr_html', True) plt.rcParams['figure.figsize'] = 12, 8 np.random.seed(0) print('Running on PyMC3 v{}'.format(pm.__version__))
Running on PyMC3 v3.5
Load and Prepare Data¶
We’ll use the Hogg 2010 data available at
It’s a very small dataset so for convenience, it’s hardcoded below
In [21]:
#### cut & pasted directly from the fetch_hogg2010test() function ## identical to the original dataset as hardcoded in the Hogg 2010 paper dfhogg = pd.DataFrame(np.array([[1, 201, 592, 61, 9, -0.84], [2, 244, 401, 25, 4, 0.31], [3, 47, 583, 38, 11, 0.64], [4, 287, 402, 15, 7, -0.27], [5, 203, 495, 21, 5, -0.33], [6, 58, 173, 15, 9, 0.67], [7, 210, 479, 27, 4, -0.02], [8, 202, 504, 14, 4, -0.05], [9, 198, 510, 30, 11, -0.84], [10, 158, 416, 16, 7, -0.69], [11, 165, 393, 14, 5, 0.30], [12, 201, 442, 25, 5, -0.46], [13, 157, 317, 52, 5, -0.03], [14, 131, 311, 16, 6, 0.50], [15, 166, 400, 34, 6, 0.73], [16, 160, 337, 31, 5, -0.52], [17, 186, 423, 42, 9, 0.90], [18, 125, 334, 26, 8, 0.40], [19, 218, 533, 16, 6, -0.78], [20, 146, 344, 22, 5, -0.56]]), columns=['id','x','y','sigma_y','sigma_x','rho_xy']) ## for convenience zero-base the 'id' and use as index dfhogg['id'] = dfhogg['id'] - 1 dfhogg.set_index('id', inplace=True) ## standardize (mean center and divide by 1 sd) dfhoggs = (dfhogg[['x','y']] - dfhogg[['x','y']].mean(0)) / dfhogg[['x','y']].std(0) dfhoggs['sigma_y'] = dfhogg['sigma_y'] / dfhogg['y'].std(0) dfhoggs['sigma_x'] = dfhogg['sigma_x'] / dfhogg['x'].std(0) ## create xlims ylims for plotting xlims = (dfhoggs['x'].min() - np.ptp(dfhoggs['x'])/5 ,dfhoggs['x'].max() + np.ptp(dfhoggs['x'])/5) ylims = (dfhoggs['y'].min() - np.ptp(dfhoggs['y'])/5 ,dfhoggs['y'].max() + np.ptp(dfhoggs['y'])/5) ## scatterplot the standardized data g = sns.FacetGrid(dfhoggs, size=8) _ = g.map(plt.errorbar, 'x', 'y', 'sigma_y', 'sigma_x', marker="o", ls='') _ = g.axes[0][0].set_ylim(ylims) _ = g.axes[0][0].set_xlim(xlims) plt.subplots_adjust(top=0.92) _ = g.fig.suptitle('Scatterplot of Hogg 2010 dataset after standardization', fontsize=16)
Observe:
- Even judging just by eye, you can see these datapoints mostly fall on / around a straight line with positive gradient
- It looks like a few of the datapoints may be outliers from such a line
Create Conventional OLS Model¶
The linear model is really simple and conventional:
where:
sigma_y
Define model¶
NOTE: + We’re using a simple linear OLS model with Normally distributed priors so that it behaves like a ridge regression
In [22]:
with pm.Model() as mdl_ols: ## Normal likelihood likelihood = pm.Normal('likelihood', mu=yest, sd=sigma_y, observed=dfhoggs['y'])
Sample¶
In [24]:
with mdl_ols: ## take samples traces_ols = pm.sample()
Auto-assigning NUTS sampler... Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (2 chains in 2 jobs) NUTS: [b1_slope, b0_intercept] Sampling 2 chains: 100%|██████████| 2000/2000 [00:01<00:00, 1969.42draws/s]
Create Robust Model: Student-T Method¶
I’ve added this brief section in order to directly compare the Student-T based method exampled in Thomas Wiecki’s notebook.
Instead of using a Normal distribution for the likelihood, we use a Student-T, which has fatter tails. In theory this allows outliers to have a smaller mean square error in the likelihood, and thus have less influence on the regression estimation. This method does not produce inlier / outlier flags but is simpler and faster to run than the Signal Vs Noise model below, so a comparison seems worthwhile.
Note: we’ll constrain the Student-T ‘degrees of freedom’ parameter
nu to be an integer, but otherwise leave it as just another
stochastic to be inferred: no need for prior knowledge.
Define Model¶
In [26]:
with pm.Model() as mdl_studentt: ## prior for Student T degrees of freedom nu = pm.Uniform('nu', lower=1, upper=100) ## Define Student T likelihood likelihood = pm.StudentT('likelihood', mu=yest, sd=sigma_y, nu=nu, observed=dfhoggs['y'])
Sample¶
In [31]:
with mdl_studentt: ## take samples traces_studentt = pm.sample(tune=2000)
Auto-assigning NUTS sampler... Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (2 chains in 2 jobs) NUTS: [nu, b1_slope, b0_intercept] Sampling 2 chains: 100%|██████████| 5000/5000 [00:03<00:00, 1275.30draws/s]
View Traces¶
In [32]:
_ = pm.traceplot(traces_studentt, figsize=(12,len(traces_studentt.varnames)*1.5), lines={k: v['mean'] for k, v in pm.summary(traces_studentt[-1000:]).iterrows()})
Observe:
- Both parameters
b0and
b1show quite a skew to the right, possibly this is the action of a few samples regressing closer to the OLS estimate which is towards the left
- The
nuparameter seems very happy to stick at
nu = 1, indicating that a fat-tailed Student-T likelihood has a better fit than a thin-tailed (Normal-like) Student-T likelihood.
- The inference sampling also ran very quickly, almost as quickly as the conventional OLS
NOTE: We’ll illustrate this Student-T fit and compare to the datapoints in the final plot
Create Robust Model with Outliers: Hogg Method¶
Please read the paper (Hogg 2010) and Jake Vanderplas’ code for more complete information about the modelling technique.
The general idea is to create a ‘mixture’ model whereby datapoints can be described by either the linear model (inliers) or a modified linear model with different mean and larger variance (outliers).
The likelihood is evaluated over a mixture of two likelihoods, one for ‘inliers’, one for ‘outliers’. A Bernouilli distribution is used to randomly assign datapoints in N to either the inlier or outlier groups, and we sample the model as usual to infer robust model parameters and inlier / outlier flags:
\(B_{i} \in [0_{(inlier)},1_{(outlier)}]\)
Note: A previous version of this example implemented the above
likelihood directly in theano. However, we can implement it more
efficiently using the Normal logp from PyMC3 and a
Potential.
Define model¶
In [133]:
with pm.Model() as mdl_signoise: ## Define informative Normal priors to give Ridge regression b0 = pm.Normal('b0_intercept', mu=0, sd=1, testval=pm.floatX(0.1)) b1 = pm.Normal('b1_slope', mu=0, sd=1, testval=pm.floatX(1.)) ## Define linear model yest_in = b0 + b1 * dfhoggs['x'] ## Define weakly informative priors for the mean and variance of outliers yest_out = pm.Normal('yest_out', mu=0, sd=10, testval=pm.floatX(1.)) sigma_y_out = pm.HalfNormal('sigma_y_out', sd=10, testval=pm.floatX(1.)) ## Define Bernoulli inlier / outlier flags according to a hyperprior ## fraction of outliers, itself constrained to [0, .5] for symmetry frac_outliers = pm.Uniform('frac_outliers', lower=0.0, upper=.5) is_outlier = pm.Bernoulli('is_outlier', p=frac_outliers, shape=dfhoggs.shape[0], testval=np.random.rand(dfhoggs.shape[0]) < 0.2) ## Extract observed y and sigma_y from dataset, encode as theano objects yobs = theano.shared(np.asarray(dfhoggs['y'], dtype=theano.config.floatX)) sigma_y_in = np.asarray(dfhoggs['sigma_y'], dtype=theano.config.floatX) # Set up normal distributions that give us the logp for both distributions inliers = pm.Normal.dist(mu=yest_in, sd=sigma_y_in).logp(yobs) outliers = pm.Normal.dist(mu=yest_out, sd=sigma_y_in + sigma_y_out).logp(yobs) # Build custom likelihood, a potential will just be added to the logp and can thus function # like a likelihood that we would add with the observed kwarg. pm.Potential('obs', ((1 - is_outlier) * inliers).sum() + (is_outlier * outliers).sum())
Sample¶
In [134]:
with mdl_signoise: traces_signoise = pm.sample(tune=5000)
Multiprocess sampling (2 chains in 2 jobs) CompoundStep >NUTS: [frac_outliers, sigma_y_out, yest_out, b1_slope, b0_intercept] >BinaryGibbsMetropolis: [is_outlier] Sampling 2 chains: 100%|██████████| 11000/11000 [00:25<00:00, 432.20draws/s] There were 3 divergences after tuning. Increase `target_accept` or reparameterize. There were 5 divergences after tuning. Increase `target_accept` or reparameterize.
View Traces¶
In [135]:
_ = pm.traceplot(traces_signoise, figsize=(12, len(traces_signoise.varnames)*1.5), lines={k: v['mean'] for k, v in pm.summary(traces_signoise).iterrows()})
NOTE:
- During development I’ve found that 3 datapoints id=[1,2,3] are always indicated as outliers, but the remaining ordering of datapoints by decreasing outlier-hood is unstable between runs: the posterior surface appears to have a small number of solutions with very similar probability.
Declare Outliers and Compare Plots¶
View ranges for inliers / outlier predictions¶
At each step of the traces, each datapoint may be either an inlier or outlier. We hope that the datapoints spend an unequal time being one state or the other, so let’s take a look at the simple count of states for each of the 20 datapoints.
In [136]:
outlier_melt = pd.melt(pd.DataFrame(traces_signoise['is_outlier', -1000:], columns=['[{}]'.format(int(d)) for d in dfhoggs.index]), var_name='datapoint_id', value_name='is_outlier') ax0 = sns.pointplot(y='datapoint_id', x='is_outlier', data=outlier_melt, kind='point', join=False, ci=None, size=4, aspect=2) _ = ax0.vlines([0,1], 0, 19, ['b','r'], '--') _ = ax0.set_xlim((-0.1,1.1)) _ = ax0.set_xticks(np.arange(0, 1.1, 0.1)) _ = ax0.set_xticklabels(['{:.0%}'.format(t) for t in np.arange(0,1.1,0.1)]) _ = ax0.yaxis.grid(True, linestyle='-', which='major', color='w', alpha=0.4) _ = ax0.set_title('Prop. of the trace where datapoint is an outlier') _ = ax0.set_xlabel('Prop. of the trace where is_outlier == 1')
Observe:
- The plot above shows the number of samples in the traces in which each datapoint is marked as an outlier, expressed as a percentage.
- In particular, 3 points [1, 2, 3] spend >=95% of their time as outliers
- Contrastingly, points at the other end of the plot close to 0% are our strongest inliers.
- For comparison, the mean posterior value of
frac_outliersis ~0.35, corresponding to roughly 7 of the 20 datapoints. You can see these 7 datapoints in the plot above, all those with a value >50% or thereabouts.
- However, only 3 of these points are outliers >=95% of the time.
- See note above regarding instability between runs.
The 95% cutoff we choose is subjective and arbitrary, but I prefer it for now, so let’s declare these 3 to be outliers and see how it looks compared to Jake Vanderplas’ outliers, which were declared in a slightly different way as points with means above 0.68.
Declare outliers¶
Note: + I will declare outliers to be datapoints that have value == 1 at the 5-percentile cutoff, i.e. in the percentiles from 5 up to 100, their values are 1. + Try for yourself altering cutoff to larger values, which leads to an objective ranking of outlier-hood.
In [137]:
cutoff = 5 dfhoggs['outlier'] = np.percentile(traces_signoise['is_outlier'], cutoff, axis=0) dfhoggs['outlier'].value_counts()
Out[137]:
0.0 17 1.0 3 Name: outlier, dtype: int64
Posterior Prediction Plots for OLS vs StudentT vs SignalNoise¶
In [153]:
from matplotlib.lines import Line2D g = sns.FacetGrid(dfhoggs, size=8, hue='outlier', hue_order=[True,False], palette='Set1', legend_out=False) lm = lambda x, samp: samp['b0_intercept'] + samp['b1_slope'] * x pm.plot_posterior_predictive_glm(traces_ols, eval=np.linspace(-3, 3, 10), lm=lm, samples=200, color='#22CC00', alpha=.2) pm.plot_posterior_predictive_glm(traces_studentt, lm=lm, eval=np.linspace(-3, 3, 10), samples=200, color='#FFA500', alpha=.5) pm.plot_posterior_predictive_glm(traces_signoise, lm=lm, eval=np.linspace(-3, 3, 10), samples=200, color='#357EC7', alpha=.3) ols_line = Line2D([0], [0], color='#22CC00') studentt_line = Line2D([0], [0], color='#FFA500') hogg_line = Line2D([0], [0], color='#357EC7') line_legend = plt.legend([ols_line, studentt_line, hogg_line], ['OLS', 'Student-T', 'Hogg'], loc=4) plt.gca().add_artist(line_legend) _ = g.map(plt.errorbar, 'x', 'y', 'sigma_y', 'sigma_x', marker="o", ls='').add_legend() _ = g.axes[0][0].set_ylim(ylims) _ = g.axes[0][0].set_xlim(xlims)
Observe:
- The posterior preditive fit for:
- the OLS model is shown in Green and as expected, it doesn’t appear to fit the majority of our datapoints very well, skewed by outliers
- the Robust Student-T model is shown in Orange and does appear to fit the ‘main axis’ of datapoints quite well, ignoring outliers
- the Robust Signal vs Noise model is shown in Blue and also appears to fit the ‘main axis’ of datapoints rather well, ignoring outliers.
- We see that the Robust Signal vs Noise model also yields specific estimates of which datapoints are outliers:
- 17 ‘inlier’ datapoints, in Blue and
- 3 ‘outlier’ datapoints shown in Red.
- From a simple visual inspection, the classification seems fair, and agrees with Jake Vanderplas’ findings.
- Overall, it seems that:
- the Signal vs Noise model behaves as promised, yielding a robust regression estimate and explicit labelling of inliers / outliers, but
- the Signal vs Noise model is quite complex and whilst the regression seems robust and stable, the actual inlier / outlier labelling seems slightly unstable
- if you simply want a robust regression without inlier / outlier labelling, the Student-T model may be a good compromise, offering a simple model, quick sampling, and a very similar estimate.
Example originally contributed by Jonathan Sedar 2015-12-21 github.com/jonsedar. Updated by Thomas Wiecki 2018-7-24. | https://docs.pymc.io/notebooks/GLM-robust-with-outlier-detection.html | CC-MAIN-2018-47 | refinedweb | 2,465 | 50.53 |
Anything related to enterprise development. Mainly about SQL server, Biztalk, .Net, patterns&practices, SOA and TDD.
I have been working on a proof of concept of unit testing with Visual Studio Team System for one of my clients. They were already familiar with the term unit testing, but up to now they have only seen some presentations/demos about it but they are quite unsure how to use it in their projects, so they asked for a PoC in order to see how the unit testing would like with the particularities of their code.
As I started I couldn't see any "oddities" about their code, they had some database access layer components (which there are already tons of articles about how to test them), business components and so on....
But after testing a couple of components I found out that in some of their components they were using the HttpContext. So I decided to create a new object of such type and use it like a normal mock object filling their collections (forms, query string and session) with custom data. But I found out that it wasn't as easy as it seemed and even if you manage to create an HttpContext object you will find out that many other objects used inside it are read-only or internal so you can barely modify this object.
So, my first thought was to search in the web to see how other guy had run into the same problem and had created a class that creates a Mock HttpContext object. Unfortunately I found many forums with guys with my same problem, a couple of articles that solved partially the problem (they could only manipulate the cache collection) and other that used a non-free third party component.
Since I couldn't find out any already made component that did such I had to create one from scratch ... The only problems were to create objects that were declared as internals or overriding read-only collections. The solution was to use my favorite namespace (reflection). I also used the reflector tool to see the implementation of the HttpContext object to see how to "inject" my own collection in the place of the read-only collections.
I attached the code to create the Mock HttpContext, My purpose was not to lose a lot of time so don't expect to have a perfect class with all the properties/methods finished. At least, in my case, it solved all the problems. If you find out some problem that doesn't solve this component, or want some more explanations about how the component works, don't hesitate to contact me.
Enjoy. | http://blogs.msdn.com/davidhernandez/archive/2006/09/21/Mocking-HttpContext-object.aspx | crawl-002 | refinedweb | 445 | 64.04 |
This is an easy problem. What we need to do is to check if a number i in ranges from 1 to n has the divisor 3 and 5.
There are many ways to realize it in Python.
- Use a loop containing condition languages. This is simple and understood by everyone. And below is my solution.
class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ ans=[] for i in range(1,n+1): if i % 15==0: ans.append("FizzBuzz") elif i % 3==0: ans.append("Fizz") elif i % 5==0: ans.append("Buzz") else: ans.append(str(i)) return ans
- I also see some amazing short solutions in the Discuss forum. These guys are really masters! Below are solutions provided by @StefanPochmann. He only writes one line. These short solutions cannot be realized without the convenience and flexibility of Python.
- 2.1.
def fizzBuzz(self, n): return['FizzBuzz'[i%-3&-4:i%-5&8^12]or`i`for i in range(1,n+1)]
- 2.2.
def fizzBuzz(self, n): return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)] | https://discuss.leetcode.com/topic/108996/fizzbuzz-solution-python | CC-MAIN-2018-05 | refinedweb | 194 | 70.7 |
More Signal - Less Noise
Tim();
19: Display( msg );
20: }
Of course, you don't have to add just strings. The value is an object and can be anything. Let's make an incredibly simple GeekObject and substitute that for the applicationSettings. We'll start by adding a GeekClass,
1: namespace SimpleIsolatedStorage
3: public class Geek,
10: Geek g = o as Geek;
11: msg += g.Name + "(" + g.FavoriteGeekBook + ")";
12:
13: }
Full Source Code SimpleIsolatedStorage.zip
Thanks.
Dude, that is one sweet article.
Very well done.
Please keep it comming.
Wouldn't it be more accurate to say that you can store anything in site/app settings that the DataContractSerializer can serialize? I believe this is going to preclude a number of advanced scenarios. That's way it worked in Beta 2 at least.
Boyan Mihaylov on SL/Amazon, David Hyde with SL Stock Portfolio, Chris Anderson with SL LOB app, Jesse
Pingback from 2008 September 30 - Links for today « My (almost) Daily Links
Great article, but that's the first time I've seen "Ulysis" spelt like that!
Pingback from Silverlight news for September 30, 2008
Rob.eisenberg: I want to check further, but I don't see any implication that you must use the DataContractSerializer with IsolatedStorage -- it seems to me that you are writing bytes. But let me look further, perhaps I'm missing something fundamental (wouldn't be the first time).
Jasonbsteele: oops. Gotta fix that!
Pingback from Dew Drop – September 30, 2008 (Evening Edition) | Alvin Ashcraft's Morning Dew
@jesse
Actually I think we are talking about two different things. I believe I misinterpreted your post. Isolated storage can store anything. But, the VS built in Settings class uses the DataContractSerializer to serialize any of its custom settings to iso storage. So the restriction is in the build-in Settings class, not in iso storage.
We have, I think, officially passed the point where anyone can keep up with the new technology available
Pingback from Silverlight Tipps vom Insider
This week I gave a Silverlight presentation at the Montreal .NET Community (
MVP Laurent Duveau recently delivered a Silverlight talk at the Montreal .NET Community . During his
用反射来动态加载XAML
2009年04月23日星期四23:25 2008年10月,写了一篇《动态加载XAML文件》,其中按照SilverlightMSDN的 | http://silverlight.net/blogs/jesseliberty/archive/2008/09/29/isolated-storage-actually-it-s-easy.aspx | crawl-002 | refinedweb | 366 | 56.96 |
MODEL EL-738F FINANCIAL CALCULATOR OPERATION MANUAL Contents Page Introduction ..................... 3 Getting Started ................ 5 General Information ........ 11 Financial Functions ......... 17 Scientific Functions ........ 60 Statistical Functions ....... 64 Appendix .......................... 72 Index ................................. 83 NOTICE • SHARP makes no guarantee that this product or this manual is suitable or accurate for any purpose, commercial or otherwise. • Rules and practices in financial calculation vary according to country, locality, or financial institution. It is the consumer’s responsibility to determine whether or not the results produced by this product conform to applicable rules and regulations. • SHARP will not be liable nor responsible for any incidental or consequential economic or property damage caused by misuse and/or malfunctions of this product and its peripherals, unless such liability is acknowledged by law. • The material in this manual is supplied without representation or warranty of any kind. SHARP assumes no responsibility and shall have no liability of any kind, consequential or otherwise, from the use of this material. • SHARP assumes no responsibility, directly or indirectly, for financial losses or claims from third persons resulting from the use of this product and any of its functions, the loss of or alteration of stored data, etc.. 1 Contents Introduction..................................................................3 Operational Notes ...............................................................3 Key Notations in This Manual ..............................................4 Chapter 1: Getting Started ..........................................5 Preparing to Use the Calculator ..........................................5 Resetting the Calculator In Case of Difficulty ..................... Scientific Calculations .......................................................61 Random Functions ............................................................62 Modify Function .................................................................63 Chapter 5: Statistical Functions ...............................64 Statistical Calculations and Variables................................67 Appendix ....................................................................72 Financial Calculation Formulas .........................................72 Statistical Calculation Formulas ........................................75 Errors and Calculation Ranges .........................................76 Battery Replacement ........................................................80 Priority Levels in Calculations ...........................................81 Specifications ....................................................................82 Index ...........................................................................83 2 Introduction Thank you for purchasing a SHARP Financial Calculator. After reading this manual, store it in a convenient location for future reference. • Display of examples shown in this manual may not look exactly the same as what is seen on the product. For instance, screen examples will show only the symbols necessary for explanation of each particular calculation. • All company and/or product names are trademarks and/or registered trademarks of their respective holders. • Some of the models described in this manual may not be available in some countries. Operational Notes. Avoid using a rough cloth or anything else that may cause scratches. • Do not drop the calculator or apply excessive force. • Never dispose of batteries in a fire. • Keep batteries out of the reach of children. • This product, including accessories, may change due to upgrading without prior notice. Hard Case 3 Key Notations in This Manual Key operations are described in this manual as follows: To specify log To specify 1 To specify Σxy : . h ..................... 1 : 1 or 1 ....................... 2 : i V ..................... 3 To specify CLR-D: To specify ENT : To specify Z : To specify DATA : . ? ..................... 1 Q i Z ..................... 3 J .............................. 4 1 Functions that are printed in orange above the key require . to be pressed first before the key. 2 Number entry examples are shown with ordinary numbers (i.e., “100” will be indicated instead of “1 0 0”). 3 To specify a memory function (printed in green), press i first. 4 Functions that are printed in black adjacent to the keys are effective in specific modes. Using the . and i keys Press s . A x , 10. i πA˚_ and i A • . mean you have to press . followed by ) key and i followed by * key. -10 Notes: • The multiplication instruction “×” and alphabetic letter “X” are distinguished as follows: Key Display Multiplication instruction → x Alphabetic letter → X × X • Examples in this manual are performed using default settings (e.g., SET UP menu items) unless values are otherwise assigned. 4 Chapter 1 Getting Started Preparing to Use the Calculator Before using your calculator for the first time, you must reset (initialize) it. Resetting the calculator Press the RESET switch located on the back of the calculator with the tip of a ball-point pen or similar object. Do not use an object with a breakable or sharp tip. • After resetting the calculator, the initial display of the NORMAL mode appears. 000 Calculator and Display Layout Calculator layout 1 Display screen 2 Power ON/OFF and Clear key 3 Key operation keys 5 Cursor keys 4 SET UP key 6 MODE key 1 Display screen: The calculator display consists of a 12-character dot matrix character line and a 12-digit 7-segment character line (10-digit mantissa and 2-digit exponent). 2 Power ON/OFF and Clear key: Turns the calculator ON. This key also clears the display. To turn off the calculator, press ., then c. 3 Key operation keys: .: Activates the second function (printed in orange) assigned to the following key. i: Activates the memory (printed in green) assigned to the following key. 4 SET UP key: Displays the SET UP menu to select the display notation, angular unit, depreciation method and date format. 5 Cursor keys: Move the cursor. 6 MODE key: Switches between NORMAL and STAT modes. 6 Display layout Symbol Equation/ variable name display Mantissa Exponent • During actual use, not all symbols are displayed at the same time. • Only the symbols required for the operation being explained are shown in the screen examples of this manual. : Appears when the entire equation cannot be displayed. Press g / y to see the remaining (hidden) part. c /d :. : Indicates that date calculations are based on a 360 360-day year (12 months with 30 days). When 360 is not displayed, date calculations use the actual calendar. ENT : Indicates that a value can be assigned to the displayed variable using Q. COMP : Indicates that the displayed variable can be solved for by using @. FLOAT A / FLOAT B / TAB / SCI: Indicates the notation used to display values. It can be changed in the SET UP menu. 7. DSP DRG DEPR 0 1 2 → i DAtE 3 • A menu item can be selected by: • Using g / y to select a number (the selected number will blink), then pressing =, or • pressing the number key corresponding to the menu item number. • If c or d is displayed on the screen, press z or i to view the previous/next part of the menu. • Press s to exit the SET UP menu. Selecting the display notation and number of decimal places The calculator has three display notation systems (fixed decimal point, scientific notation and floating point) for displaying calculation results. • If ~ 0 0 (TAB) is pressed, “DIG(0-9)?” will be displayed and the number of decimal places can be set to any value between 0 and 9. • If ~ 0 1 (SCI) is pressed, “SIG(0-9)?” will be displayed and the number of significant digit can be set to any value between 0 and 9. Entering 0 will set a 10-digit display. • If a floating point number does not fit in the specified range, the calculator will display the result in scientific notation (exponential notation). See the next section for details. • The default setting is a fixed decimal point with two decimal places. 8 Selecting the floating point number system in scientific notation The calculator has two settings for displaying a floating point number: FLO_A (FLOAT A) and FLO_B (FLOAT B). In each display setting, a number is automatically displayed in scientific notation outside the following preset ranges: • FLO_A ~ 0 2: 0.000000001 ≤ | X | ≤ 9,999,999,999 • FLO_B ~ 0 3: 0.01 ≤ | X | ≤ 9,999,999,999 Switching the notation setting Procedure Key operation Display 100000 ÷ 3 = Fixed decimal point with two decimal places s 100000 8 3 = → Scientific notation (SCI) with two significant digits ~012 → Floating point (FLO_A) ~02 1—————©3= 3 ÷ 1000 = Floating point (FLO_A) s 3 8 1000 = 3©1———= → Floating point (FLO_B) ~03 3©1———= → Fixed decimal point with two decimal places ~002 1—————©3= 3333333 1—————©3= 33 04 3333333333 0003 3©1———= 3-03 000 Selecting the angular unit (see page 61) • DEG (°) : ~ 1 0 (default setting) • RAD (rad) : ~ 1 1 • GRAD (g) : ~ 1 2 Selecting the depreciation method (see page 48) • SL (Straight-line method): ~ 2 0 (default setting) • SYD (Sum-of-the-years’ digits method): ~ 2 1 • DB (Declining balance method): ~ 2 2 9 Selecting the date format (see page 44) • US (Month-Day-Year): ~ 3 0 (default setting) • EU (Day-Month-Year): ~ 3 1 Operating Modes This calculator has two operating modes, which can be selected using the MODE key. Selecting a mode 1. Press m. NORMAL 0 The menu display appears. 2. Press 0 or = to select NORMAL mode. StAt 1 000 • Press 1 or y = to select STAT mode. SD LINE QUAD 0 1 2 Operations available in each mode NORMAL mode: Allows you to perform financial, arithmetic, or scientific calculations. STAT (statistics) mode: Allows you to perform statistical, arithmetic, or scientific symbol appears in the display. calculations. The 10 Chapter 2 General Information Basic Calculations Entering numbers and arithmetic operations • Use the number keys 0 to 9, decimal point key ., and sign change key , to enter numbers into the calculator. To clear the display or entry, press s. • Use the S key to enter a value in scientific notation. • Use the arithmetic keys + - x 8 to perform the standard arithmetic calculations of addition, subtraction, multiplication, and division. Press = to perform each calculation. • Use the ( and ) keys to place parentheses around inner parts of expressions. The closing parenthesis ) just before = or h may be omitted. • When you enter a series of operations in one sequence, the calculator performs the calculation according to the priority levels in calculation on page 81. Example Key operation 45 + 285 ÷ 3 = s 45 + 285 8 3 = 18 + 6 = 15 – 8 ( 18 + 6 ) 8 ( 15 - 8 = 42 × (–5) + 120 = (5 × 103) ÷ (4 × 10–3) = 42 x , 5 + 120 = 1 * (5 ,) 1 * 5S384S ,3= Result 14000 343 -9000 125000000 Clearing the Entry and Memories The following methods of clearing the calculator (restoring default settings) are available: 11 Operation Listed Cash Entry A-H, TVM financial *3 flow (display) M, X-Z ANS variables*1 variables *4 data STAT *7 s .b m (Mode selection) . k 0 (MEM) × × × × × × × *2 × × *5 × × *6 × *8 . k 1 (RESET) RESET switch : Cleared or restored to the default setting × : Retained *1 *2 N, I/Y, PV, PMT, and FV (P/Y and C/Y are not included.) Note that listed financial variables sharing common memory with TVM variables, such as “COUPON (PMT)” used in bond calculations, are also cleared or restored to default settings. *3 Listed variables used in financial calculations (such as “RATE (I/Y),” etc.) including P/Y and C/Y *4 When you press * to enter a financial financial variables are also cleared or restored to default settings. 6 * Press . b when a cash flow value is displayed. 7 * Statistical data (entered data) and variables (n, x, etc.) *8 Are cleared when changing between sub-modes in STAT mode. Notes: • To clear any of the “A-H, M, X-Z” or “ANS” memories, press s g and then specify the memory. • To clear or restore to the default setting one variable or value of TVM variables, listed financial variables, cash flow data, or STAT, refer to the relevant section. • If you turn off the calculator (by pressing . c or by letting it turn itself off automatically), it will resume wherever you left off when you turn it on again. Delete key To delete a number/function, move the cursor to the number/ function you wish to delete, then press L. If the cursor is located at the right end of an equation or if you are entering a value, the L key will function as a back space key. 12 Memory clear key Press . k to display the menu. MEM RESEt 0 1 • To clear all (A-H, M, X-Z, ANS, TVM variables, listed financial variables, cash flow data, and STAT), press 0 0 or 0 =. • To RESET the calculator, press 1 0 or 1 =. The RESET operation erases all data stored in memory, and restore the calculator’s default settings. Editing and Correcting an Entry Cursor keys • In a menu, such as the SET UP menu, use g or y to select a number (the selected number will blink), then press =. If you need to scroll up or down the screen, use z or i. • In financial • This calculator has two editing modes: insert mode (default), and overwrite mode. Pressing . d switches between the two modes. A triangular cursor indicates an entry will be inserted at the cursor, while the rectangular cursor indicates existing data will be overwritten as you make entries. • To insert a number in the insert mode, move the cursor to the place immediately after where you wish to insert, then make the desired entry. In the overwrite mode, data under the cursor will be overwritten by the number you enter. • This mode setting will be retained until you press . d or RESET the calculator. 13 Changing “15 ÷ 3 =” into “25 ÷ 13 =” Procedure Key operation Display s 15 8 3 = 15 ÷ 3 = 15©3= Enter the playback y function. 15©3 Switch to overwrite . d mode. 15©3 Change “15” to “25” 2 y y and move the cursor to “3”. 25©3 Change to insert mode. .d 25©3 Change “3” to “13” and calculate. 1= 25©13= 500 financial calculations and statistical calculations. Memory use in each mode for memory calculations Mode TVM Listed financial Statistical A-H, variables *3 X-Z M ANS variables *1 variables *2 NORMAL STAT : Available × × : Unavailable 14 × × × *1 *2 *3 N, I/Y, PV, PMT, FV All financial variables, except for TVM variables x, sx, σx, n, Σx, Σx2, y, sy, σy, Σy, Σy2,) • The calculation result obtained by pressing = or any other calculation ending instruction (including storing and recalling operations) is automatically stored in the last answer memory. • Listed financial specific to the type of calculation they are used in. For example, the variable N is available to the TVM solver but not to discounted cash flow analysis calculations. If you want to carry a value from a variable over into a different type of calculation, use one of the following methods: •M-Y) 2 are not stored in last answer memory. • Variables common to both calculations: If the value that you wish to carry over is held in a variable that exists in both types 15 24 ÷ (8 × 2) = (8 × 2) × 5 = Key operation s8x2gM 24 8 i M = iMx5= sgM $150×3:M1 150 x 3 h +)$250:M2=M1+250 250 h –)M2×5% fMx5.% M .jfM $1 = ¥110 ¥26,510 = $? $2,750 = ¥? 110 g Y 26510 8 f Y = 2750 x f Y = r = 3 cm (r→Y) 2 πr = ? 3gY i Y* . .;= 24 24 8 ( 4 + 6 ) = = 2.4...(A) 4+6 3 x i / + 60 8 3 × (A) + 60 ÷ (A) = i / = Result 1600 150 8000 000 45000 25000 3500 66500 11000 24100 30250000 300 2827 240 3220 * Entry of the multiplication procedure is omitted between “π” and a variable. 16 Chapter 3 Financial Functions General Information Financial calculations The following financial functions are available. Use NORMAL mode to perform financial calculations. TVM (Time Value of Money) solver: Analyze equal and regular cash flows. These include calculations for mortgages, loans, leases, savings, annuities and contracts or investments with regular payments. Amortization calculations: Calculate and create amortization schedules using values stored in the TVM solver. Discounted cash flow analysis: Analyze unequal cash flows fixed costs, variable costs per unit, unit prices, and profit. 17 Variables used in financial calculations Financial calculations use multiple variables. By entering known values into variables, you can obtain unknown values. Variables used in financial specific Bond cash flow calculations analysis Percent change/ Depreciation Day and date Compound intercalculations calculations est. 18 M-D-Y 1* D-M-Y 1 M-D-Y 2 * D-M-Y 2 Press @ and the corresponding TVM variable key. Listed financial variables A. Entering a value 1. Select the desired financial calculation method by pressing the corresponding financial calculation key. 2. Use z/i to select the variable you wish to enter. 3. Enter the value and press Q when the “ENT” symbol appears. Note: In step 3, you can also enter values into variables using arithmetic operations. Ex. 100 x 12 Q B. Displaying a value Use z/i to show the variable and value. C. Executing calculation 1. Use z/i to select the variable you wish to calculate. 2. Press @ when the “COMP” symbol appears. Note: Pressing . b resets all the variables in the displayed listed financial group to the default values. For details, see the relevant sections for each financial calculation. 19 The ENT and COMP symbols Listed financial financial function. Note: TVM variables (N, I/Y, PV, PMT and FV) can be entered (known variables) and calculated (unknown variables), however, neither “ENT” nor “COMP” will appear on the display. Category Display symbols Descriptions ENT Variable can be used as a known, but not as an unknown. For calculation only COMP Variable can be used as an unknown, but not as a known. For entry or calculation ENT COMP Variable can be used as either a known or an unknown. Calculated automatically — Unknown variable, but the calculator calculates the value automatically. For entry only Notes: • During financial calculation, the word “calculating!” will be displayed on the screen. You can press s at this time to cancel the calculation. • Calculation-only and automatically calculated variables have no default values. • The symbol will be displayed if the value of the displayed variable has not been calculated yet (for variables that can be calculated). 20 Compound interest This calculator assumes interest is compounded periodically in financial specified or assumed (usually monthly). Cash flow diagrams The direction of arrows indicates the direction of cash movement (inflow and outflow) with time. This manual uses the following cash flow diagrams to describe cash inflows and outflows. Inflow (+) Present value (PV) Time Cash flow ...... Payment (PMT) Future value (FV) Outflow (–) 21 TVM (Time Value of Money) Solver Analyze equal and regular cash flows. These include calculations for mortgages, loans, leases, savings, annuities, and contracts or investments with regular payments. Note: Discounted cash flow analysis can be done using unequal cash flows Present value 0 PV. . ". 22 3. Enter values into TVM solver variables. • Enter a value and press the appropriate TVM variable key , u, t). (N, f, • Press . w and then enter a value for P/Y. The same value is automatically assigned to C/Y as well. Values entered into P/Y or C/Y must be positive. After entering values, press s to quit the P/Y and C/Y settings. • After setting P/Y (number of payments per year), you can use . < to enter N (total number of payments). Enter the number of years and press . <. The calculator automatically calculates the total number of payments. • By pressing f / you can use the result of the previous normal calculation stored in ANS memory as a TVM variable. • Note that some variables are shared by other calculations and may have values assigned by those calculations. 4. Press @ and the TVM variable key that you wish to solve. • The calculation is performed and the obtained values are displayed. Basic examples for the TVM solver 1 Calculating basic loan interest A $56,000 mortgage loan (compounded monthly) requires monthly payments of $440 during its 20-year amortization period. Calculate the annual interest rate on the mortgage. PV = $56,000 FV = 0 ...... I/Y = ?% PMT = –$440 N = 12 × 20 years = 240 Default values for the number of payments per year (P/Y) and the number of compounding periods per year (C/Y) are both set to 1. Set these values before entering TVM variable values. 23 the same value as P/Y. Confirm the number of compounding periods per year. i Quit the P/Y and C/Y settings. s C/Y= 1200 000 Calculate the total num- 20 . < N ber of payments and store in N. ANS~N Enter the present value. 56000 56———~PV 24000 5600000 Enter payment. , 440 u (-44—)~PMT Enter the future value. 0t —~FV Calculate the annual interest rate. @f I/Y= -44000 000 717 Answer: The annual interest rate is 7.17%. Note: If you make a mistake, press L to erase the number and enter the correct number to continue. After pressing the TVM variable key, you must re-enter values from the beginning. 24 2 Calculating basic loan payments Calculate the quarterly payment for a $56,000 mortgage loan at 6.5% compounded quarterly during its 20-year amortization period. PV = $56,000 I/Y = 6.5% FV = 0 ...... PMT = ? N = 4 × 20 years = 80 Procedure Set all the variables to default values. Key operation Display .b 000 Make sure ordinary annuity is set (BGN is not displayed). Set the number of payments per year to 4. .w4Q Confirm the number of i compounding periods per year. P/Y= 400 C/Y= 400 Quit the P/Y and C/Y set- s tings. 000 Calculate the total number of payments and store in N. 20 . < N Enter the present value. 56000 56———~PV Enter the future value. 0t —~FV Enter the annual interest rate. 6.5 f 6.5~I/Y Calculate the quarterly payment. @u PMT= ANS~N 5600000 Answer: The quarterly payments are $1,255.86. 25 8000 000 650 -125586 3 Calculating future value You will pay $200 at the end of each month for the next three years into a savings plan that earns 6.5% compounded quarterly. What amount will you have at the end of period if you continue with the plan? FV = ? I/Y = 6.5% (quarterly) PV = 0 ...... PMT = –$200 PMT = –$200 N = 12 × 3 years = 36 Procedure Set all the variables to default values. Key operation Display .b 000 Make sure ordinary annuity is set (BGN is not displayed). Set the number of payments per year to 12. . w 12 Q Set the number of com- i 4 Q pounding periods per year to 4. Quit the P/Y and C/Y settings. P/Y= 1200 C/Y= 400 s 000 Calculate the total num- 3 . < N ber of payments and store in N. ANS~N Enter the present value. 0 —~PV 3600 000 Enter payment. , 200 u (-2——)~PMT Enter the annual interest rate. 6.5 f 6.5~I/Y Calculate the future value. @t FV= -20000 650 792219 Answer: You will have $7,922.19 at the end of the three-year period. 26 4 Calculating present value You open an account that earns 5% compounded annually. If you wish to have $10,000 twenty years from now, what amount of money should you deposit now? FV = $10,000 N = 20 years PV = ? Procedure Set all the variables to default values. I/Y = 5% Key operation Display .b 000 Make sure ordinary annuity is set (BGN is not displayed). Set the number of payments per year to 1. .w1Q P/Y= 100 The number of compounding periods per year is automatically set to 1. Press s to exit the P/Y and C/Y settings. Enter the total number of payments. s 20 N 2—~N Enter the future value. 10000 t 1————~FV Set payment to zero. 0u —~PMT Enter the annual interest rate. 5f 5~I/Y Calculate the present value. @ PV= Answer: You should deposit $3,768.89 now. 27 2000 1000000 000 500 -376889 Specifying payments due (. ") This calculator can select ordinary annuity or annuity due depending on the regular cash flow (payment) conditions. Ordinary annuity (END): This is the default setting for financial calculations. BGN is not displayed. A regular cash flow (payment) is received at end of each payment period. Often applied to loan calculations, etc. Annuity due (BGN): BGN appears on the display. A regular cash flow (payment) is received at the beginning of each payment period. Often applied to the finance lease of an asset. To toggle between ordinary annuity and annuity due, press . ". Note: The above selection only affects the TVM solver. 1 Ordinary annuity Your company wishes to accumulate a fund of $300,000 over the next 18 months in order to open a second location. At the end of each month, a fixed amount will be invested in a money market savings account with an investment dealer. What should the monthly investment be in order to reach the savings objective, assuming the account will earn 3.6% interest compounded monthly? FV = $300,000 PV = 0 I/Y = 3.6% ...... PMT = ? N = 18. 28 Procedure Key operation Display Enter the total number of payments. s 18 N 18~N Enter the future value. 300000 t 3—————~FV Set the present value to 0 zero. 1800 30000000 —~PV 000 Enter the annual interest rate. 3.6 f 3.6~I/Y Calculate payment. @u PMT= 360 -1624570 Answer: The monthly investment should be $16,245.70. 2 Calculating lease payments (Annuity due) You plan to purchase a new car with a value of $87,918 on a 60-month lease. If the annual interest rate is 6.75%, the contractual purchase option price at lease end is $17,500, and payment is due at the beginning of each month, how much should you pay each month? PV = $87,918 I/Y = 6.75% .................... PMT = ? FV = –$17,500 N = 60 Procedure Key operation Set all the variables to default values. .b Set to annuity due (BGN is displayed). ." Set the number of payments per year to 12. . w 12 Q 29 Display 000 000 P/Y= 1200 Procedure Key operation Display The number of compounding periods per year is automatically set to 12. Press s to exit the P/Y and C/Y settings. Enter the total number of payments. s 60 N 6—~N Enter the future value. , 17500 t (-175——)~FV Enter the present value. 87918 6000 -1750000 87918~PV 8791800 Enter the annual interest rate. 6.75 f 6.75~I/Y Calculate payment. @u PMt= 675 -147620 Answer: You should pay $1,476.20 each month. Calculating the present value of a lease with trade-in value Your client wishes to buy a machine currently leased from your company. On a five-year lease with payments of $200 at the beginning of each month, the machine has a trade-in value of $1,500 with 34 monthly payments remaining. If your company sells the machine at the present value of the lease, discounted at an annual interest rate of 18%, compounded monthly, how much should your company charge for the machine? 3 PV = ? I/Y = 18% ...... PMT = –$200 N = 34 30 FV = –$1,500 Procedure Key operation Set all the variables to default values. .b Set to annuity due (BGN is displayed). ." Set the number of payments per year to 12. . w 12 Q Display 000 000 P/Y= 1200 The number of compounding periods per year is automatically set to 12. Press s to exit the P/Y and C/Y settings. Enter the total number of payments. s 34 N 34~N Enter payment. , 200 u (-2——)~PMt Enter the annual interest rate. 18 f 18~I/Y Enter the future value. , 1500 t (-15——)~FV Calculate the present value. @ PV= 3400 -20000 1800 -150000 627995 Answer: $6,279.95 should be charged for the machine. 4 Calculating down payment and amount to borrow You wish to buy a house for $180,000. The finance company charges a 5.5% APR, compounded monthly, on a 25-year loan. If you can afford a monthly payment of $900, how much can you borrow? How much do you need for a down payment? PV = ? I/Y = 5.5% ...... PMT = –$900 N = 12 × 25 years = 300 31 FV = 0. Enter the total number of payments. s 25 . < N ANS~N Enter payment. , 900 u (-9——)~PMT Enter the annual interest rate. 5.5 f 5.5~I/Y Set the future value to zero. 0t —~FV Calculate the present value. @ PV= Calculate the down payment. s 180000 f = 18————-PV= 30000 -90000 550 000 14655892 3344108 Answer: You can borrow $146,558.92 in total. The price of the house is $180,000, so: Down payment = $180,000 – present value = $180,000 – $146,558.92 You need $33,441.08 for a down payment. 32 Amortization Calculations Calculate and create amortization schedules using values stored in the TVM solver. Note: Prior to using amortization, you need to enter values into TVM variables. Variables used in amortization Variable Description Default value AMRT P1 Start of payment (nth time) 1 AMRT P2 End of payment (nth time) 1 BALANCE Remaining balance after payment — ΣPRINCIPAL Principal paid — ΣINTEREST Interest paid over the specified periods — • BALANCE, ΣPRINCIPAL and ΣINTEREST are calculated automatically, so no default values are set. • AMRT P1 and AMRT P2 must be between 1 and 9,999. . ". 3. Enter the appropriate numeric values for the variables used in the TVM solver. • Confirm the values of N, I/Y, PV, PMT, FV, P/Y and C/Y. 4. Press * to use amortization calculation. 5. Enter a value for “AMRT P1” and press Q. AMRt P1= 100 6. Press i, enter a value for “AMRT P2” and press Q. 7. Display values for BALANCE, ΣPRINCIPAL and ΣINTEREST by pressing i once for each. Each value is calculated automatically. 33 8. Press i to calculate the next period of the amortization schedule. 9. Repeat steps 5 to 7 above. • If you press @ during “AMRT P1” and “AMRT P2” entry, the values for the next period of payment will be automatically calculated and displayed. • To end amortization calculations, press s. Pressing s during entry will clear the value entered. 1 Calculating mortgage payments and generating an amortization schedule 1. Calculate the monthly payment of a 20-year loan with a loan amount of $90,000 and a 5.45% APR. Procedure Set all the variables to default values. Key operation Display .b 000 Make sure ordinary annuity is set (BGN is not displayed). Set TVM solver variables and calculate payment. . w 12 Q s 20 . < 0 N 90000 t 5.45 f @ u PMT= -61656 Answer: The monthly payment is $616.56. Now generate an amortization schedule for the first 5 years of the loan. If the first payment is in August, the first year has 5 payment periods and the following years have 12 payment periods each. 2. Calculate the amortization schedule for the first year. Procedure Key operation Display Change to amortization * 1 Q calculation and enter 1 (August) for the starting payment. AMRT P1= Enter 5 (December) for i 5 Q the ending payment. AMRT P2= Display the remaining balance. i 100 500 BALANCE= 8895148 34 Procedure Key operation Display Display the principal paid. i ÍPRINCIPAL= Display the interest paid. i ÍINTEREST= -104852 -203428 3. Calculate the amortization schedule for the second year. Procedure Key operation Change amortization i6Q schedule to the second year and enter 6 (January) for the starting payment. Enter 17 (December) i 17 Q for the ending payment. Display AMRT P1= 600 AMRT P2= 1700 Display the remaining balance. i BALANCE= Display the principal paid. i ÍPRINCIPAL= Display the interest paid. i ÍINTEREST= 8633592 -261556 -478316 4. Calculate the amortization schedule for the third year. Procedure Key operation Change amortization [email protected] schedule to the third year and enter the next 12 months automatically. Display AMRT P2= 2900 Display the remaining balance. i BALANCE= Display the principal paid. i ÍPRINCIPAL= Display the interest paid. i ÍINTEREST= 8357421 -276171 -463701 5. Repeat the above operation for the fourth and fifth years. 35 2 Calculating payments, interest, and loan balance after a specified payment You have taken out a 30-year loan for $500,000, with an annual interest rate of 8.5%. If, after the 48th period, you want a balloon payment due, what amount of monthly payment must you make with monthly compounding and how much will the balloon payment be? Procedure Set all the variables to default values. Key operation Display s.b 000 Make sure ordinary annuity is set (BGN is not displayed). Set TVM solver variables and calculate payment. . w 12 Q s 30 . < 0 N 500000 t 8.5 f @ u PMT= -384457 Answer: The monthly payment is $3,844.57. Now generate an amortization schedule from the first to the 48th payments. Procedure Key operation Display Change to amortization * 1 Q calculation and enter 1 for the starting payment. AMRT P1= Enter 48 (December) i 48 Q for the ending payment. AMRT P2= 100 4800 Display the balance after 48 months. (balloon payment) i BALANCE= Display the principal paid over 48 months. i ÍPRINCIPAL= Display the interest paid over 48 months. i ÍINTEREST= 48275524 -1724476 -16729460 Answer: The balloon payment after the 48th period would be $482,755.24. 36 Discounted Cash Flow Analysis Analyze unequal cash flows and calculate the net present value (NPV) and the internal rate of return (IRR). Note: Use the TVM solver for equal and regular cash flow analysis (see page 22). Entering cash flow data To find NPV and IRR using discounted cash flow analysis, enter cash flow data, one data item at a time, in the following format: Single cash flows Cash flow value J Repeated cash flows Cash flow value > frequency value J Notes: • Before entering data, press > . b to clear any previously entered cash flow data. • Press , to enter a negative cash flow (outflow). • Make sure the calculator is in NORMAL mode. It is not possible to enter cash flow data when listed financial variables are shown on the display. Press s to exit. • You can enter a total of up to 100 cash flow and/or statistical data items. A single cash flow value is counted as one data item, while a cash flow value with an associated frequency value is counted as two. • Frequency values must be integers between 1 and 999. • If you wish to correct a value before pressing J, press s to delete the entry and enter the correct value. Entering cash flow data Enter cash flow data according to the following cash flow diagram. $7,000 $9,000 $5,000 $5,000 $8,000 –$25,000 37 Procedure Key operation Display Bring up the initial dis- s *1 play in NORMAL mode. Enter cash flow data. *1 *2 000 , 25000 J DATA SET:CF 000* 7000 J DATA SET:CF 9000 J DATA SET:CF 5000 > 2 J DATA SET:CF 8000 J DATA SET:CF 2 100 200 300 400 If there is cash flow data stored, press > . b to clear it. The format of the data set (cash flow and frequency values) number, which is initially set to “0.00,” is dependent on calculator display notation settings. Confirming and editing data Confirming data Press > to display any previously entered cash flow data. The data is displayed in order by data item (identifier, number, and value). Use z/i to display a data item from a previously entered data set. Cash flow identifier Data set number CF D—= -2500000 Frequency identifier CF N—= 38 Cash flow value Data set number 100 Frequency value • Press . z or . i to jump to the first or the last data item, respectively. • Each data item is displayed in the form CF Dn= (cash flow value) or CF Nn= (frequency), where n indicates the data set number. Editing data • Display the data item you wish to modify by using z/i, enter a new value and press J. • If a frequency value is set to zero, then the associated data set is deleted. Deleting data • Display the data item to be deleted by using z/i, and press . ?. • If a cash flow value/frequency is deleted, the corresponding frequency/cash flow cash flow value of zero and a frequency value of one will be inserted. Modify the new data set to include your data. Correcting cash flow data Currently the cash flow data is that shown in chart A. Change it according to chart B. Chart A Chart B $7,000 $9,000 $5,000 $5,000 $8,000 $7,000 $9,000 $6,000 $5,000 $8,000 –$25,000 Procedure –$30,000 Key operation Display previously s> entered cash flow data. (Example on page 37) 39 Display CF D—= -2500000 Procedure Key operation Change the first cash , 30000 J flow value from –25,000 to –30,000. Display CF D—= -3000000 Change the frequency of 5000 from 2 to 1. iiii CF N3= iii1J Add a new data set (6000) immediately before 5000. . e 6000 J 100 CF D3= 600000 To confirm the corrections, press . z to jump to the first data item and press i to browse through each data item. Variables used in discounted cash flow analysis Variable Description Default value RATE (I/Y) Internal rate of return (IRR) 0 NET_PV Net present value (NPV) — • The variable RATE (I/Y) is shared by the variable I/Y. NET_PV is for calculation only and has no default value. • The BGN/END setting is not available for discounted cash flow analysis. NPV and IRR The calculator solves the following cash flow values: Net present value (NPV): The total present value of all cash flows, including cash paid out (outflows) and cash received (inflows). A profitable investment is indicated by a positive NPV value. Internal rate of return (IRR): The interest rate that gives a net present value of zero. Basic operations Refer to page 19 for basic variable operations. 1. Press s to clear the display. • Make sure the calculator is in NORMAL mode. 40 2. Enter cash flow data. • Refer to page 37 for instructions on entering cash flow data. 3. Press . < to begin discounted cash flow analysis. • If a previously entered cash flow value is displayed, press s to exit and then press . <. 4. To find NPV or IRR, do the following: To obtain NPV: Enter the interest rate (discounted rate) into RATE(I/Y) and press Q. Move to NET_PV and calculate by pressing i and @. To obtain IRR: Press @ to calculate IRR (RATE(I/Y)). Note: If “Error 5” is displayed in step 4, or if you want to find another IRR, enter an estimated value into RATE(I/Y) and calculate again in step 4. 1 Solving for unequal cash flows Your company pays $12,000 for a new network system, and expects the following annual cash flows: $3,000 for the first year, $5,000 for the second to fourth years, and $4,000 for the fifth year. At what IRR does the net present value of the cash flows equal zero? $3,000 $5,000 $5,000 $5,000 $4,000 –$12,000 1. Enter cash flow data. Procedure Key operation Bring up the initial dis- s *1 play in NORMAL mode. Display 000 41 Procedure Enter cash flow data. Key operation DATA SET:CF 3000 J DATA SET:CF 5000 > 3 J DATA SET:CF 4000 J DATA SET:CF Return to the initial dis- s play in NORMAL mode. *1 Display , 12000 J 000 100 200 300 000 If there is cash flow data stored, press > . b to clear it. 2. Calculate IRR. Procedure Key operation Select discounted cash . < . b flow analysis, and set all the variables to default values. Calculate IRR (RATE (I/Y)). @ Display RATE(I/Y)= 000 RATE(I/Y)= 2314 Answer: The net present value of the cash flows equals zero at an IRR of 23.14%. 2 Calculating the present value of variable cash flows Your company has prepared forecasts for the development costs and operating profits of the next generation of your product. Development costs for each of the next three years (Years 1 to 3) will be $50,000. Manufacturing equipment costing $100,000 will be purchased at the end of Year 3. Annual profits for the five-year product life (from Year 4 to Year 8) are projected to be $80,000. The salvage value of the manufacturing equipment at the end of Year 8 is $20,000. Given a 12% discount rate, should your company proceed with the product development? 42 $80,000 $80,000 $80,000 $80,000 $80,000 –$20,000 –$50,000 –$50,000 –$50,000 –$100,000 1. Enter the cash flow data. Procedure Key operation Display Bring up the initial dis- s *1 play in NORMAL mode. Enter cash flow data. 000 , 50000 > 2 J DATA SET:CF , 150000 J DATA SET:CF 80000 > 4 J DATA SET:CF 60000 J DATA SET:CF 000 100 200 300 Return to the initial dis- s play in NORMAL mode. *1 000 If there is cash flow data stored, press > . b to clear it. 2. Calculate NPV. Procedure Key operation Display Select discounted cash . < . b flow analysis, and set all the variables to default values. RATE(I/Y)= Enter the discount rate. 12 Q RATE(I/Y)= Calculate NPV (NET_PV). [email protected] 000 1200 NET_PV= 662752 Answer: As NPV = 6,627.52 > 0, the product can be developed. 43 Bond Calculations Using bond calculations, you can obtain bond prices, yields to maturity, and accrued interest. Variables used in bond calculations Variable Description COUPON (PMT) Annual coupon rate (%) REDEMPT (FV) Redemption value *1 M-D-Y 1 *2 Default value 0 0 Settlement date (date of bond purchase) 1-1-2001 M-D-Y 2 *2 Redemption date 1-1-2001 CPN/Y (N) *3 Number of coupons per year YIELD (I/Y) Yield to maturity (%) 0 PRICE (PV) Bond price *4 0 ACCU INT Accrued interest — 1 *1 *2 *3 Redemption value of the security per $100 par value. You can change the date format to D-M-Y (see page 10). You can only enter “1” or “2” — “1” for annual coupons and “2” for semi-annual coupons. *4 Per $100 par value. Note: Bonds are associated with payment methods known as coupons. A coupon is like an “interest-only payment,” and it is based on the future value of the bond. COUPON is a percentage of the bond par value, usually annually, by the owner of the bond. For bonds that have annual coupons, the owner receives one payment of the coupon amount each year. Some bonds have semi-annual coupons. For these, each year’s coupon amount is paid in two equal payments six months apart. The date on which a coupon payment is made is called the “coupon date.” The bond maturity date is usually the last coupon date.. 44 Basic operations Refer to page 19 for basic variable operations. 1. Press s to clear the display. • Make sure the calculator is in NORMAL mode. 2. Select bond calculations by pressing #. • To end bond calculations, press s. • If you press s during entry, any entered values will be cleared. COUPON(PMt)= 000 3. Change the day-count setting, if necessary, by pressing . &. 4. Enter the coupon rate (%) into COUPON (PMT) by entering the value and pressing Q. 5. Enter the redemption value into REDEMPT (FV) by pressing i, entering the value, and pressing Q. 6. Enter the date of bond purchase into M-D-Y 1 (or D-M-Y 1) by pressing i, entering the date, and pressing Q. • For date entry, refer to page 47, ”Entering dates”. 7. Enter the redemption date into M-D-Y 2 (or D-M-Y 2) by pressing i, entering the date, and pressing Q. • For date entry, refer to page 47, ”Entering dates”. 8. Enter the number of coupon payments per year into CPN/Y (N) by pressing i, entering the value, and pressing Q. 9. To find bond price or yield to maturity, do the following: To obtain bond price (PRICE (PV)): Enter annual yield (%) into YIELD(I/Y) by pressing i, entering the value, and pressing Q. Move to PRICE (PV) and calculate by pressing i and @. Display the accrued interest (ACCU INT) by pressing i. The accrued interest is calculated automatically. To obtain yield to maturity (YIELD (I/Y)): Move to PRICE (PV) and enter the bond price by pressing i i, entering the value, and pressing Q. Move to annual yield, YIELD (I/Y) and calculate by pressing z @. Display the accrued interest (ACCU INT) by pressing i i. The accrued interest is calculated automatically. 45 Calculating bond price and accrued interest A $100, 20-year, 6.5% coupon bond is issued to mature on August 15, 2023. It was sold on November 3, 2006 to yield the purchaser 7.2% compounded semiannually until maturity. At what price did the bond sell? Also calculate the accrued coupon interest. Procedure Key operation Display Bring up the initial dis- s play in NORMAL mode. Select bond calculations. 000 COUPON(PMT)= # 000 Make sure the actual calendar is set (360 is not displayed). Enter the coupon rate (%). 6.5 Q COUPON(PMT)= Enter the redemption value. i 100 Q REDEMPT(FV)= Enter the settlement date. i 11032006 Q M-D-Y 1=[FR] Enter the redemption date. i 08152023 Q M-D-Y 2=[TU] Enter the number of coupon payments per year. i2Q Enter the annual yield (%). i 7.2 Q YIELD(I/Y)= Calculate bond price. i @ PRICE(PV)= Calculate the accrued interest. i ACCU INT= Calculate bond price including accrued interest. si + i/= PV+ANS= 650 10000 11- 3-2006 8-15-2023 CPN/Y(N)= 200 720 9323 141 9464 Answer: The bond sold at $93.23 and the accrued coupon interest was $1.41 (the bond price including accrued interest would be $94.64). The asking price on the above bond is $92.50. What will your yield be? 46 Procedure Key operation Change the bond price to $92.50. #iii i i i 92.5 Q Display PRICE(PV)= Calculate the yield. [email protected] YIELD(I/Y)= 9250 728 Answer: The yield will be 7.28%. Entering dates Refer to the following notes for date entry. • Enter using US date format (MM-DD-YYYY) or EU date format (DD-MM-YYYY). Refer to the previous example and the following explanation. Month entry Enter two digits. From 2 to 9, the preceding zero may be omitted. Day entry Enter two digits. From 4 to 9, the preceding zero may be omitted. Year entry Enter four digits. From 2010 to 2099, the zero following the first “2” may be omitted. From 1901 to 1989, the “9” following the first “1” may be omitted. • After entry, the date will be stored and the abbreviated day of the week will be displayed. • [SU]: Sunday, [MO]: Monday, [TU]: Tuesday, [WE]: Wednesday, [TH]: Thursday, [FR]: Friday, [SA]: Saturday. • The default value for dates is: January 1, 2001 (1-1-2001). • The effective range of dates is: January 1, 1901 to December 31, 2099. • If an inappropriate date is entered (e.g., February 31), an error message (Error 7) will appear immediately after pressing Q. In this case, follow either of the following procedures: • Press s to return to the display before the entry, enter the appropriate date, and press Q. • Press g/y to go back to the display that was shown before you pressed Q. Press s or L, enter the appropriate date, and press Q again. • If you wish to correct numbers during entry, use L as a backspace key. 47 Depreciation Calculations Using depreciation calculations, you can obtain depreciation base values using three types of calculation methods: the straight-line method, the sum-of-the-years’ digits method, and the declining balance method. Variables used in depreciation calculations Variable Description Default value DB (I/Y)*1 Interest per year 0 LIFE (N) Years of depreciation 1 START MONTH Starting month 1 COST (PV) Cost of asset 0 SALVAGE (FV) Salvage value 0 YEAR Year for calculating depreciation value 1 DEPRECIATE Depreciation value of above year — RBV Remaining book value — RDV Remaining depreciation value — *1 DB (I/Y) appears only when you select DB (declining balance method) for the depreciation method. Setting the depreciation method • Select the depreciation method in the SET UP menu. It is initially set to SL. Key operation ~20 Description SL (Straight-line method) ~21 SYD (Sum-of-the-years’ digits method) ~22 DB (Declining balance method) Basic operations Refer to page 19 for basic variable operations. 1. Press s to clear the display. • Make sure the calculator is in NORMAL mode. 48 2. Select the depreciation method (see page 48). 3. Select depreciation calculations by pressing O. SL • When using the declining balance method, DB (I/Y) appears. Enter the number and press Q. • To end depreciation calculations, press s. If you press s during entry, any entered values will be cleared. ---------- 4. Enter the number of years of depreciation into LIFE (N) by pressing i, entering the value, and pressing Q. • When using the straight-line method, the value should be a positive real number, while for the SYD or DB methods, it should be a positive integer. 5. Enter the starting month into START MONTH by pressing i, entering the value, and pressing Q. • You can enter values between 1 and 13. • Generally, it is not necessary to enter a decimal value. However, if you wish to enter, for example, the middle of July, enter 7.5; where the decimal is equal to the number value of the given date divided by the total number of days in the month. 6. Enter the cost of asset into COST (PV) by pressing i, entering the value, and pressing Q. 7. Enter the salvage value into SALVAGE (FV) by pressing i, entering the value, and pressing Q. 8. Enter the year for calculating depreciation value into YEAR by pressing i, entering the value, and pressing Q. • The year for calculating depreciation value is initially 1. Pressing @ increments this number by 1. • This value must be a positive integer. 9. Calculate depreciation for the year by pressing i. 10. Calculate the remaining book value by pressing i. 11. Calculate the remaining depreciation by pressing i. 12. To calculate depreciation value for another year, press z three times to go back to YEAR, enter a value for the new year, and recalculate. 49 Calculating straight-line depreciation In April, your company begins depreciation of a commercial building with a 30-year life and no salvage value. The building costs $1,500,000. Calculate the depreciation amount, remaining book value and remaining depreciable value for the third year using the straight-line depreciation method. Procedure Key operation Display Bring up the initial display in NORMAL mode, and select the straight-line depreciation method. s~20 Select depreciation calculations. O SL Enter the number of years of depreciation. i 30 Q LIFE(N)= Enter the starting month. i4Q START MONTH= 000 ---------3000 400 Enter the cost of asset. i 1500000 Q COST(PV)= Enter the salvage value. i 0 Q SALVAGE(FV)= Enter the year for calcu- i 3 Q lating depreciation value. YEAR= Calculate depreciation for the year. 150000000 000 300 DEPRECIATE= i 5000000 Calculate the remaining i book value. RBV= Calculate the remaining i depreciation value. RDV= 136250000 136250000 Answer: At the third year, the depreciation amount is $50,000, the remaining book value is $1,362,500, and the remaining depreciable value is $1,362,500. 50 Conversion between APR and EFF Interest rates can be converted between APR (annual, or nominal percentage rate) and EFF (effective interest rate). • The APR is an investment’s annual rate of interest when compounding happens only once a year. The interest rate printed on a bond is an example of an APR. • The EFF is an investment’s annual rate of interest when compounding happens more often than once a year. It reflects the actual amount of return for a given nominal rate. For example, if your investment compounds monthly, then the stated nominal percentage rate becomes a monthly rate, and the EFF reflects your actual annual rate of return. Basic operations 1. Press s to clear the display. Make sure the calculator is in NORMAL mode. 2. Enter the calculation data in the following format: • To change APR to EFF: Number of compounding periods per year > Nominal percentage rate . P • To change EFF to APR: Number of compounding periods per year > Effective interest rate . ! Converting between APR and EFF Procedure Key operation Calculate the effective interest rate for twelve compounding periods with an 18% APR. s 12 > 18 . P Convert this rate back to the original APR. 12 > 19.56 . ! Display 12,18¬EFF 1956 12,19.56¬APR 1800 51 Day and Date Calculations Using day and date calculations, you can find dates and the numbers of days between dates. Variables used in day and date calculations Variable Description Default value M-D-Y 1 *1 The first date 1-1-2001 M-D-Y 2 *1 The last date 1-1-2001 DAYS Number of days *1 0 You can change the date format to D-M-Y (see page 10).. Basic operations Refer to page 19 for basic variable operations. 1. Press s to clear the display. • Make sure the calculator is in NORMAL mode. 2. Select day and date calculaM-D-Y 1=[MO] tions by pressing K. • To end day and date calculations, press s. If you press s during entry, any entered values will be cleared. 1- 1-2001 3. Change the day-count method, using . &, if necessary. 4. Enter the values of any two known variables: the first date, the last date, or the number of days. • For date entry, refer to page 47, ”Entering dates”. 5. Move to the variable you wish to calculate, using the z and i keys, and press @ to calculate. • If the calculator is set to 360-day calendar mode (360 is displayed), it is not possible to obtain either the first or last dates, only the number of days. 52 1 Calculating number of days Calculate the number of days between December 25, 2008 and August 10, 2009 . 12252008 Q M-D-Y 1=[TH] Enter the last date. i 8102009 Q M-D-Y 2=[MO] Move to DAYS and calculate. [email protected] DAYS= 12-25-2008 8-10-2009 22800 Answer: 228 days • If the 360-day calendar is selected, the answer will be 225 days. 2 Finding a date Find the date 100 days after November 13, 2010 . 1113210 Q Move to DAYS and en- i i 100 Q ter the number of days. 53 M-D-Y 1=[SA] 11-13-2010 DAYS= 10000 Procedure Key operation Move to the last date and calculate. [email protected] Display M-D-Y 2=[MO] 2-21-2011 Answer: The last date is February 21, 2011. Percent Change/Compound Interest Calculations Using percent change/compound interest calculations, you can determine the values of percentage rates of change (increase or decrease) or interest rates compounding periodically. Variables used in percent change/compound interest calculations Variable OLD PRC (PV) Description Default value Old price (old value) NEW PRC (FV) New price (new value) 0 0 % (I/Y) Percent change 0 PERIODS (N) Number of compounding periods 1 Basic operations Refer to page 19 for basic variable operations. 1. Press s to clear the display. • Make sure the calculator is in NORMAL mode. 2. Select percent change/compound interest calOLD PRC(PV)= culations by pressing . B. • To end percent change/compound interest calculations, press s. • If you press s during entry, any entered values will be cleared. 000 3. Enter the values of any three known variables: old price, new price, percent change, or number of compounding periods. 4. Move to the variable you wish to calculate, using the z and i keys, and press @ to calculate. 54 1 Calculating percent change Sales in a company were $75,000 during the first year of operation. The second year’s sales were $116,000. What percentage greater were the second year’s sales than first year’s sales? In this calculation, the number of compound periods is set to 1 (default). Procedure Key operation Display Bring up the initial dis- s play in NORMAL mode. 000 Select percent change/ . B . b compound interest calculations, and set all the variables to default values. OLD PRC(PV)= 000 Enter the old value. 75000 Q OLD PRC(PV)= Enter the new value. i 116000 Q NEW PRC(FV)= Calculate the percent change. [email protected] %(I/Y)= 7500000 11600000 5467 Answer: The second year’s sales increased by 54.67% over the first year’s sales. 2 Calculating compound interest rate You opened an account compounding annually and deposited $8,000 eighteen years ago. You currently have $9,800. What is the compound interest rate? Procedure Key operation Bring up the initial dis- s play in NORMAL mode. 000 Select percent change/ . B . b compound interest calculations, and set all the variables to default values. Enter the old value. Display 8000 Q 55 OLD PRC(PV)= 000 OLD PRC(PV)= 800000 Procedure Key operation Enter the new value. i 9800 Q Set the number of com- i i 18 Q pound periods to 18. Calculate the compound interest rate. [email protected] Display NEW PRC(FV)= 980000 PERIODS(N)= 1800 %(I/Y)= 113 Answer: The compound interest rate is 1.13%. Cost/Sell/Margin/Markup Calculations Using cost/sell/margin/markup calculations, you can determine costs, selling prices, margins and markup. Variables used in cost/sell/margin/markup calculations Variable Description Default value COST Cost 0 SELL Selling price 0 MARGIN Profit margin (%) *1 0 MARK UP Markup (%) *2 — *1 *2 Profit margin (%) is calculated based on selling price. Markup (%) is calculated based on cost. Basic operations Refer to page 19 for basic variable operations. 1. Press s to clear the display. • Make sure the calculator is in NORMAL mode. 2. Select cost/sell/margin/markup COSt= calculations by pressing I. • To end cost/sell/margin/markup calculations, press s. • If you press s during entry, any entered values will be cleared. 000 56 3. Enter the values of any two known variables as follows: Unknown variable Known variables SELL, and MARGIN or MARK UP *1 COST SELL COST, and MARGIN or MARK UP *1 MARGIN COST and SELL MARK UP COST and SELL *1 Because only either MARGIN or MARK UP is used in any cost/sell/margin/markup calculation, the unused variable is given a value of “----------”. Initially, MARK UP is set to “---------”. If you enter a value for MARK UP, MARGIN is set to “---------”, and vice versa. 4. Move to the variable you wish to calculate, using the z and i keys, and press @ to calculate. Determining selling price In a furniture business, it is desirable to realize a 95% markup from cost to retail price for each item. A certain sofa costs $455.60. What should its selling price be? Procedure Key operations Display Bring up the initial dis- s play in NORMAL mode. 000 Select cost/sell/margin I . b markup calculations, and set all the variables to default values. COST= 000 Enter cost. 455.6 Q COST= Enter markup rate. i i i 95 Q MARK UP= Calculate selling price. [email protected] SELL= Answer: The selling price should be $888.42. 57 45560 9500 88842 Breakeven Calculations Using breakeven calculations, you can calculate fixed cost, variable cost per unit, unit price, profit and quantity. Variables used in breakeven calculations Variable Description Default value FIXED Fixed cost VARIABLE Variable cost per unit 0 0 PRICE Unit price 0 PROFIT Profit 0 QUANTITY Quantity 0 Basic operations Refer to page 19 for basic variable operations. 1. Press s to clear the display. • Make sure the calculator is in NORMAL mode. 2. Select breakeven calculations FIXED= by pressing $. • To end breakeven calculations, press s. • If you press s during entry, any entered values will be cleared. 000 3. Enter the values of any four known variables. 4. Move to the variable you wish to calculate, using the z and i keys, and press @ to calculate. Calculating the breakeven point Your company has developed a new product and plans to sell it at a price of $120 per unit. The variable cost per unit is $75.80 and the fixed costs total $15,000. What is the breakeven point for this product? Procedure Key operation Bring up the initial dis- s play in NORMAL mode. Display 000 58 Procedure Key operation Select breakeven $.b calculations, and set all the variables to default values. Display FIXED= 000 Enter fixed cost. 15000 Q FIXED= Enter variable cost per unit. i 75.80 Q VARIABLE= Enter unit price. i 120 Q PRICE= Leave profit as is. i PROFIT= Calculate quantity. [email protected] QUANTITY= 1500000 7580 12000 000 33937 Answer: The breakeven point of this product is 339.37 units. 59 Chapter 4 Scientific Functions This calculator has a variety of functions. Press m 0 to select NORMAL mode and perform scientific calculations. • For basic calculations, see page 11. • When a listed financial variable is displayed, you can enter the result of a scientific calculation into it by pressing Q immediately after completing the calculation. • Scientific calculations can also be performed in STAT mode. • The examples in this chapter are all performed under the SET UP menu’s default settings. Before starting calculation, press s to clear the display. Constant Calculations Example Key operation 34 + 57 = s 34 + 57 = 45 + 57 = 45 = 68 × 25 = 68 x 25 = 68 × 40 = 40 = Result 9100 10200 170000 272000 • In constant calculations, the addend becomes a constant. Subtraction and division behave the same way. For multiplication, the multiplicand becomes a constant. • In constant calculations, constants will be displayed as . Chain Calculations A calculation result (ANS memory) can be used in a subsequent calculation. However, it cannot be recalled after entering multiple instructions. Example Key operation 6 + 4 = ANS ANS + 5 = s6 +4 = +5 = 8 × 2 = ANS ANS2 = 8x2= .;= 44 + 37 = ANS ANS = 44 + 37 = .}= 60 Result 1000 1500 1600 25600 8100 900 Scientific Calculations Example Key operation Display s . { 60 = sin60= ~11. c(. 84 ) = cos(π©4)= tan–1 1 [g] = ~12. 71 = tan-|1= tan–1 1 [°] = ~10. 71 = tan-|1= sin 60 [°] = π cos — [rad] = 4 087 071 5000 4500 • The range of the results of inverse trigonometric functions –1 –1 θ = sin x, θ = tan x –1 θ = cos x DEG –90 ≤ θ ≤ 90 0 ≤ θ ≤ 180 RAD π π –—≤θ≤— 2 2 0≤θ≤π –100 ≤ θ ≤ 100 0 ≤ θ ≤ 200 GRAD Example Key operation (cosh 1.5 + sinh 1.5)2 = s ( . ] c1.5 + . ] {1.5 ) .;= 5 = tanh–1 — . ] 7 (5 8 7 )= log 50 = . h 50 = In 20 = . d 20 = 7 101.7 = . :1.7 = e3 = .R3= Result 2009 090 170 300 5012 2009 6.;+7.; = 031 8–2 – 34 × 52 = 8 . @ , 2 - 3 [email protected]; = -202498 1 6 1 7 —+—= 1 (123)4– = 49 – 4 12 . @ 3 . @ 4 .;= 81 = . } 49 - 4 . : 81 = 61 645 400 Example 4! = 10 5 P3 = C2 = What is 25% of 500? Key operation 4.o= 10 . q 3 = 5.p2= 500 x 25 . % 120 8 400 . % What percentage of 400 is 120? Result 2400 72000 1000 12500 3000 500 + (500 × 25%) = 500 + 25 . % 62500 400 – (400 × 30%) = 400 - 30 . % 28000 Random Functions This calculator has four kinds of random functions (the 2nd function of the - key). Random numbers A pseudo-random number, consisting of three significant digits from zero up to 0.999, can be generated by pressing . | 0 =. To generate further random numbers in succession, press = for each number. Press s to exit. • To display numbers with three significant digits, set the display notation settings to “floating point”. Random dice To simulate a die roll, a random integer between 1 and 6 can be generated by pressing . | 1 =. To generate further random numbers in succession, press = for each number. Press s to exit. Random coin To simulate a coin flip, 0 (heads) or 1 (tails) can be randomly generated by pressing . | 2 =. To generate further random numbers in succession, press = for each number. Press s to exit. 62 Random integer An integer between 0 and 99 can be generated randomly by pressing . | 3 =. To generate further random numbers in succession, press = for each number. Press s to exit. Example Key operation Pick a random number s . | 0 between zero and 9.99. x 10 = Display RANDOMx1—= 532 • The result will not be the same each time this operation is performed. Modify Function Calculation results are internally obtained in scientific notation with a mantissa of up to 14 digits. However, because calculation results are displayed in the form designated by the display notation and the number of decimal places indicated, a displayed calculation result may differ from that held internally. By using the modify function (the 2nd function of the + key), the internal value is converted to match that of the display, so that the displayed value can be used without change in subsequent operations. Example Key operation 5 ÷ 9 = ANS ANS × 9 = [FIX, TAB = 2] s589= x 9 = *1 *1 *2 589= . l x 9 = *2 5.5555555555555 × 10–1 × 9 0.56 × 9 63 Result 056 500 056 504 Chapter 5 Statistical Functions Statistical calculations can be performed in STAT mode. The symbol will be visible if you are in STAT mode. There are seven sub-modes within STAT mode, corresponding to each of the functions below: Key operation m10 m11 m12 m13 m14 m15 m16 Sub-mode Display SD: Single-variable statistics LINE: Linear regression QUAD: Quadratic regression EXP: Exponential regression LOG: Logarithmic regression PWR: Power regression INV: Inverse regression Stat — Stat 1 Stat 2 Stat 3 Stat 4 Stat 5 Stat 6 Entering statistical data Before you can perform statistical calculations, you will need to enter your data. In STAT mode, use > and J (the Q key) to enter the following: For a single-variable data set: Value J Value > frequency J (To enter multiples of the same value) For a two-variable data set: x value > y value J x value > y value > frequency J (To enter multiples of the same x and y values) Note: Before entering data, clear any previously entered data from memory by doing either of the following: • Press . b in STAT mode. • Switch sub-modes within STAT mode. 64 • You can enter a total of up to 100 statistical and/or cash flow data items. For single-variable data, a data set without a frequency is counted as one data item, and a data set with an assigned frequency is counted as two data items. For twovariable data, a data set without a frequency is counted as two data items, while a data set with an assigned frequency is counted as three data items. • If you wish to correct a value before pressing J, press L or s to delete the entry, then enter the correct value. Entering statistical data Enter the data in the table to the right using the “Stat 0” sub-mode. Procedure Key operation DATA 30 40 40 50 Display Enter the “Stat 0” submode. sm10 Stat — Enter statistical data. *1 30 J DATA SET= Return to the “Stat 0” display. 100 * 40 > 2 J DATA SET= 50 J DATA SET= s Stat — 200 300 000 there is data stored in memory, press . b (within STAT mode) to clear it. The format of the data set (the sample and frequency values) number, which is initially set to “1.00”, is dependent on calculator notation settings. *1 If *2 000 65 2 Confirming and editing data • Use z / i to display a data item from a previously entered data set. Data set number X1= 1000 x value Data set number Y1= 2000 y value Data set number FRQ1= 1100 Frequency • Press . z or . i to jump to the first or last data item, respectively. • Each data item is displayed in the form: “Xn = (x value)”, “Yn = (y value)”, or “FRQn = (frequency)”, where “n” is the data set number. Editing data • Display the data item you wish to modify by using z / i, enter a new value and press J. Deleting data • Display the data item to be deleted by using z/i, and press . ?. • If a value/frequency is deleted, the corresponding frequency/ value of zero and a frequency of one will be inserted. Modify the new data set to include your data. 66 Editing statistical data Change the previously entered data from page 65 as follows: DATA 30 40 40 50 Procedure Display the statistical data. DATA 30 45 45 45 60 Key operation Display X1= i Change the “40, 2” data i i 45 J set to “45, 3”. i3J FRQ2= 3000 300 Delete “50”. i.? Stat — Add “60”. 60 J DATA SET= 000 300 Statistical Calculations and Variables The following results can be obtained for each statistical calculation (refer to the table below): Single-variable statistical calculations Section 1 results only. Linear regression calculations Section 1 and 2 results, except for coefficients c. The estimate of y for a given x (estimate y´) and the estimate of x for a given y (estimate x´) can also be found. Quadratic regression calculation Section 1 and 2 results, and coefficients a, b, and c in the quadratic regression formula (y = a + bx + cx2). In quadratic regression calculations, no correlation coefficient r can be obtained. 67 The estimate of y for a given x (estimate y´) and the estimate of x for a given y (estimate x´) can also be found. When there are two x values, the COMP symbol will appear. Press @ to switch between x values. Exponential regression, logarithmic regression, power regression, and inverse regression calculations Section 1 and 2 results, except for coefficients c. The estimate of y for a given x (estimate y´) and the estimate of x for a given y (estimate x´) can also be found. Because the calculator converts each formula into a linear regression before actual calculation takes place, it obtains all statistics — except coefficients a and b — from converted data rather than from entered data. Variables n 1 x Mean of samples (x values) sx Sample standard deviation (x values) σx Population standard deviation (x values) Σx Sum of samples (x values) Σx 2 Content Number of samples 2 Sum of squares of samples (x values) y Mean of samples (y values) sy Sample standard deviation (y values) σy Population standard deviation (y values) Σy Sum of samples (y values) Σy 2 Sum of squares of samples (y values) Σxy Sum of products of samples (x, y) a Coefficient of regression equation b Coefficient of regression equation c Coefficient of quadratic regression equation r Correlation coefficient • Use i or f to perform a variable calculation in STAT mode. 68 1 Single-variable statistical calculation Example Key operation m10. b DATA Result S a — 000 95 95 J DATA SET=100 80 80 J DATA SET=200 80 J DATA SET=300 75 75 75 75 > 3 J DATA SET=400 50 50 J DATA SET=500 x= f= –x = 7571 σx = f2 σ≈= 1237 n= fn n= Σx = fU Í≈= 2 Σx = f[ Í≈Œ= sx = f4 Sx= .;= SxŒ= 2 sx = ( 95 - i (95 – x ) =)8i — × 10 + 50 = sx 4 x 10 + 50 = 69 700 53000 4120000 1336 17857 6443 2 Linear regression calculation Example DATA x y Key operation m11 Result S a 1 000 2 5 2>5J DATA SET=100 2 5 J DATA SET=200 12 24 12 > 24 J DATA SET=300 21 21 21 40 40 40 21 > 40 > 3 J DATA SET=400 15 25 15 > 25 J DATA SET=500 a= fa a= b= fb b= r= fr r= sx = f4 Sx= sy = f5 Sy= 3.? 3y´ 46x´ x=3 y´ = ? y = 46 x´ = ? 46 . 9 70 105 183 100 854 1567 653 2462 3 Quadratic regression calculation Example DATA x Key operation m12 Result S a ≈¡= ≈™= -343 ≈¡= 963 41 12 > 41 J DATA 8 13 8 > 13 J DATA 5 2 5>2J DATA 23 200 23 > 200 J DATA 15 71 15 > 71 J DATA 12 a= fa a= b= fb b= c= fa c= x = 10 y´ = ? 10 . ? y = 22 x´ = ? 22 . 9 10y´ @ @ 71 2 000 SET=100 SET=200 SET=300 SET=400 SET=500 536 -312 050 2449 963 y Appendix Financial Calculation Formulas TVM solver PMT, PV, FV, N If PMT ≠ 0 or N ≠ 1 then find i using the following equations: Error + Error i≤ –1 Amortization calculations Calculations (for PV, PMT, and i, see the TVM solver) END INT(1) = ROUND(–PV × i) BGN INT(1) = 0 PRN(1) = –INT(1) + ROUND(PMT) BAL(1) = PRN(1) + PV INT(m) = ROUND(–BAL(m – 1) × i) PRN(m) = –INT(m) + ROUND(PMT) BAL(m) = PRN(m) + BAL(m – 1) ROUND(NUM): If a display notation tab setting has been chosen, NUM is rounded and truncated to the specified number of places after the decimal point. Results Error AMRT P1 > AMRT P2 Discounted cash flow analysis m m CF I/Y RATE(I/Y) where i = 100 , CFimax = the maximum data set number If PMT = 0 then If N = 1 then 72 IRR is obtained as i, which satisfies NPV = 0 in the above equations. Bond calculations In its bond calculations, this calculator conforms to rules set up by the book titled Standard Securities Calculation Methods, by Jan Mayle, Securities Industry Association, 1993. Bond calculation is based on the following rules: 1. Whenever the redemption date happens to be the last day of a month, coupons are also paid on the last days of months. For example, if coupon payments are semi-annual and the redemption date is September 30, coupon payments occur on March 31 and September 30. 2. If coupons are to be paid twice a year and the redemption date is set to August 29, 30, or 31, coupon payments for February occur on the 28th (29th for leap years). 3. The “Odd Coupon” is not supported. 4. All data stored or calculated for bonds are assumed to be positive values. Negative values in any of the variables used by bond calculations will cause errors. The formulas used for bond calculations are shown using the following variable definitions: TD: Total number of days in the coupon period that begins with the coupon date previous to the settlement date and ends with the first coupon date after the settlement date. (On the 360-day calendar, TD is 180 for semi-annual coupon and 360 for annual coupon.) PD: The number of days preceding the settlement date in the coupon period described above. (see “Day and date calculations”) FD: The number of days following the settlement date in the coupon period described above (in TD). FD = TD – PD NP: The number of whole coupon periods between the settlement date and the redemption date (rounded up to the next highest whole number, if necessary). For one coupon period or less until redemption of bond: For more than one coupon period until redemption: where CPN = COUPON(PMT), RDV = REDEMPT(FV), N = CPN/Y(N), YIELD = YIELD(I/Y), PRICE = PRICE(PV). Yield is obtained as YIELD, which satisfies the above equations. Error CPN < 0 or RDV < 0 or PRICE < 0 or M-D-Y 1 ≥ M-D-Y 2 or YIELD ≤ –100 73 Depreciation calculations ROUND(NUM): If a display notation tab setting has been chosen, NUM is rounded and truncated to the specified number of places after the decimal point. In the following equations, M01 = START MONTH, LIF = LIFE(N), CST = COST(PV), SAL = SALVAGE(FV), and DB = DB(I/Y). Straight-line method (SL) Results Calculations If 1 < n < end_year then Error CST < 0 SAL < 0 CST < SAL Results LIF: when SL, LIF ≤ 0 when SYD or DB, LIF is not a positive integer I/Y < 0 (DB only) Conversion between APR and EFF Sum-of-the-years’ digits method (SYD) Calculations N, EFF ¬ APR 1 EFF + 1)N –1) N 100 100 Error (( EFF ≤ –100 N, APR ¬ EFF (( Results APR N 100 N + 1) –1) 100 Error APR ≤ –100 N Day and date calculations Declining balance method (DB) In day and date calculations, this calculator conforms to rules set up in the book titled Standard Securities Calculation Methods, by Jan Mayle, Securities Industry Association, 1993. Calculations 74 30/360 Statistical Calculation Formulas 1. Adjust D1 and D2 according to the following rules: Type (1) If D2 and D1 are both the last day of February, change D2 to 30. Regression formula Linear y = a + bx (2) If D1 is the last day of February, change D1 to 30. Quadratic y = a + bx + cx2 (3) If D2 is 31 and D1 is 30 or 31, change D2 to 30. Exponential y = a • ebx Logarithmic y = a + b • Inx Power y = a • xb Inverse 1 y=a+b x (4) If D1 is 31, change D1 to 30. 2. Calculate using the following formula: DAYS = (Y2 – Y1) × 360 + (M2 – M1) × 30 + (D2 – D1) Actual x = Σnx Percent change/Compound interest calculations Σ x2 – nx2 sx = n–1 Σ x2 – nx2 σx = n Σ x = x1 + x2 + ··· + xn Σ x2 = x12 + x22 + ··· + xn2 y= where NEW = NEW PRC(FV), OLD = OLD PRC(PV), %CH = %(I/Y), PD = PERIODS(N) sy = Error %CH ≤ –100 NEW × OLD ≤ 0 σy = Cost/Sell/Margin/Markup calculations Σy n Σ y2 – ny2 n–1 Σ y2 – ny2 n Σ y = y1 + y2 + ··· + yn Σ y2 = y12 + y22 + ··· + yn2 Σ xy = x1y1 + x2y2 + ··· + xnyn where MAR = MARGIN, MU = MARK UP Breakeven calculations 75 An error will occur in a statistical calculation if: • The absolute value of an intermediate or calculation result is equal to or greater than 1 × 10100. • The denominator is zero. • An attempt is made to find the square root of a negative number. • No solution exists for a quadratic regression calculation. Errors and Calculation Ranges Errors An error will occur if an operation exceeds the calculation ranges, or if a mathematically illegal operation is attempted. When an error occurs, pressing g or y automatically moves the cursor back to the place in the equation where the error occurred. Edit the equation or press s to clear the equation. Note: If an error occurs during the automatic calculation of a listed financial variable, pressing s, g, or y displays the first variable in the function. Error codes and error types Syntax error (Error 1): • An attempt was made to perform an invalid operation. Ex. 2 + - 5 = • During the editing or insertion of cash flow or statistical data, a value was entered but . ? was pressed before J. Calculation error (Error 2): • The absolute value of an intermediate or final calculation result equals or exceeds 10100. • An attempt was made to divide by zero. • The calculation ranges were exceeded while performing calculations. • There was a financial calculation error, such as: • an error listed in “Financial Calculation Formulas” (see pages 72 – 75) occurred • an attempt was made to find I/Y when PV, PMT × N, and FV contain all negative or all positive values • an attempt was made to find IRR when the cash flow data contains all negative or all positive values • an attempt was made to find YIELD in a bond calculation when any of COUPON, REDEMPT, or PRICE contain negative values Depth error (Error 3): • The available number of buffers was exceeded. (There are 10 buffers for numeric values and 24 buffers for calculation instructions). • The number of entered cash flow and statistics data items combined exceeded 100. 76 Equation too long (Error 4): • The equation exceeded its maximum input buffer (160 characters). An equation must be shorter than 160 characters. No solution (Error 5): • The iteration limit was exceeded while calculating one of the following values in an overly complex problem: • I/Y (TVM solver) • IRR (Discounted cash flow analysis)*1 • YIELD (Bond calculations) *1 If you get an error while calculating IRR, enter an estimated value into RATE(I/Y) and calculate again. Display error (Error 6): • An attempt was made to display “9.999 × 1099” when the display notation tab number was set to “2”. If this happens, press s and ~ 0 2 to set the display notation settings to “floating point”. Then try again. Input value error (Error 7): • An attempt was made to enter a nonexistent date. Ex. February 30th • An attempt was made to enter an invalid numeric value into a financial calculation. • a negative value or 0 into P/Y or C/Y • anything except an integer between 1 and 9,999 into AMRT P1 or AMRT P2 • a non-integer into DAYS • anything except 1 or 2 into CPN/Y • anything except an integer between 1 and 999 as a cash flow frequency • anything except a positive integer into YEAR • anything except a value between 1 and 13 into START MONTH 77 Calculation ranges of functions • Within the ranges specified, this calculator is accurate to within ±1 of the least significant digit of the mantissa. However, a calculation error increases in continuous calculations due to accumulation of each calculation error. (This is the same for financial calculations, x x x scientific calculations [y , , e , ln, n!, etc.], where continuous calculations are performed internally.) Additionally, a calculation error will accumulate and become larger in the vicinity of inflection points and singular points of functions. In financial calculations, a calculation error increases if the interest is low or the number of payments is high. Press s if you’d like to cancel the calculation while the “calculating!” screen is displayed. • Calculation ranges ±10–99 to ±9.999999999 × 1099 and 0. If the absolute value of an entry or a final or intermediate result of a calculation is less than 10–99, the value is considered to be 0 in calculations and in the display. Function sin x, cos x, tan x Calculation range DEG: | x | < 1010 (tan x : | x | ≠ 90 (2n – 1))* π RAD: | x | < — × 1010 180 π (tan x : | x | ≠ — (2n – 1))* 2 10 10 GRAD: | x | < — × 10 9 (tan x : | x | ≠ 100 (2n – 1))* sin–1 x, cos–1 x |x|≤1 tan–1 x | x | < 10100 In x, log x 10–99 ≤ x < 10100 yx • y > 0: –10100 < x log y < 100 • y = 0: 0 < x < 10100 • y < 0: x = n 1 (0 < | x | < 1: — = 2n – 1, x ≠ 0),* x –10100 < x log | y | < 100 78 Function x y Calculation range 1 • y > 0: –10100 < — log y < 100 (x ≠ 0) x • y = 0: 0 < x < 10100 • y < 0: x = 2n – 1 1 (0 < | x | < 1: — = n, x ≠ 0),* x 1 –10100 < — log | y | < 100 x 1/x 0 ≤ x < 10100 | x | < 10100 (x ≠ 0) n! 0 ≤ n ≤ 69* nPr 0 ≤ r ≤ n ≤ 9,999,999,999* n! — < 10100 (n – r)! nCr 0 ≤ r ≤ n ≤ 9,999,999,999* 0 ≤ r ≤ 69 n! — < 10100 (n – r)! * n, r: integer 79 Battery Replacement Notes on battery replacement it reaches the service life stated in the specifications. Note on the erasure of memory contents When the battery is replaced, the memory contents are erased. Erasure can also occur if the calculator is defective or when it is repaired. Make a note of all important memory contents in case accidental erasure occurs. When to replace the battery If the display has poor contrast, or if nothing appears on the screen, even when, wash them immediately with clean water. • If the product is not to be used for some time, to avoid damage to the unit from leaking battery, remove it and store in a safe place. • Keep battery out of the reach of children. • Exhausted battery that is left in the calculator may leak and damage the unit. • Explosion risk may be caused by incorrect handling. • Do not throw battery into a fire, as it may explode. 80 Replacement procedure 1. Turn the power off by pressing . c. 2. Loosen the screw and remove the battery cover. (see fig. 1) 3. Remove the used battery using a ball-point pen or similar object. Do not use a mechanical pencil or any sharp or pointed object to remove the battery. (see fig. 2) 4. Install a new battery into the battery housing with the positive side (+) facing up. (see fig. 3) fig. 1 fig. 2 5. Replace the battery cover and the screw. 6. Press the RESET switch located on the back of the calculator with the tip of a ball-point pen or similar object. Do not use an object with a breakable or sharp tip. (see fig. 4) • Make sure that the display appears as shown. If not, remove the battery, reinstall, and check the display again. fig. 3 fig. 4 000 Automatic power-off function This calculator will turn its power off automatically if no key is pressed for about 10 minutes. Priority Levels in Calculations This calculator performs operations according to the following priority: 1. Functions preceded by their argument (x2, n!, etc.) 2. yx, x 3. Implied multiplication of a memory value (2Y, etc.) 4. Functions followed by their argument (sin, cos, etc.) 5. Implied multiplication of a function (2sin 30, etc.) 6. nCr, nPr 7. ×, ÷ 8. +, – 9. =, M+, M–, ⇒M, and any other calculation ending instructions 81 Key operation and calculation priority 5 + 2 x . { 30 + 25 x 5 . @ 3 = • Parenthesized operations take precedence over other operations. Specifications Calculations: Financial calculations General arithmetic calculations Scientific calculations Statistical calculations Calculation method: D.A.L. (Direct Algebraic Logic) Internal calculations: Mantissas of up to 14 digits Pending operations: 24 calculations, 10 numeric values Power source: 3.0 V … (DC) Lithium battery (CR2032) × 1 Operating life: Approx. 5 years (with 1 hour of daily use) • May vary depending on the operating environment and operation method. Operating temperature: 0°C – 40°C (32°F – 104°F) External dimensions: 77 mm (W) × 144 mm (D) × 10.8 mm (H) 3-1/32” (W) × 5-21/32” (D) × 7/16” (H) Weight: Approx. 82.5 g (0.19 lb.) (including battery) Accessories: Battery × 1 (installed), operation manual, and hard case For more information about financial calculators Visit us on the Internet at: For USA only: This product contains a CR Coin Lithium Battery which contains Perchlorate Material – special handling may apply, California residents, See 82 Index >, 37, 51, 64 + - x 8, 4, 11 =, 11, 15 ,, 11, 37, 61 ( ), 11, 16, 61 <, 23 } :, 60, 61 %, 16, 62 B, 54 z i g y, 6, 13 ! P, 51 ., 11 , 16, 61 ;, 61 :, 61 ., 4, 6, 7 &, 44, 45, 52 i, 4, 6, 7, 15 *, 33 /, 15, 16, 23 ", 22, 28, 33 #, 45 $, 58 b, 12, 19 <, 41 >, 37, 38 ?, 39, 66 @, 7, 19 I, 56 J, 37, 64 K, 52 L, 12 O, 49 Q, 7, 19 R, 61 S, 11 t, 22, 23 ], 7, 61 f, 22, 23 d, 13 e, 39, 66 d, 61 h, 61 M, 15 h, 11, 16 j, 16 k, 5, 12, 13 l, 63 m, 6, 10, 12 N, 22, 23 o, 62 p q, 62 c, 6 s, 6, 12 w, 22, 23 u, 22, 23 , 22, 23 |, 62, 63 f, 7, 15 ~, 6, 8–10 g, 7, 15 ;, 16, 60, 61, 69 @, 61 % (I/Y), 18, 54, 75 ∑INTEREST, 33, 72 ∑PRINCIPAL, 33, 72 ACCU INT, 44 Amortization calculations, 17, 33–36, 72 AMRT P1, AMRT P2, 12, 33, 77 Angular unit, 8, 9, 61 Annuity due, 7, 22, 28 ANS (last answer memory), 14, 15 APR, 17, 51, 74 Arithmetic calculations, 11 Arithmetic operations (+, –, ×, ÷), 11 Automatic power-off function, 81 BALANCE, 33, 72 Battery replacement, 80, 81 Bond calculations, 17, 18, 44–47, 73 Breakeven calculations, 17, 58, 59, 75 (symbol), 8, 20 Calculation ranges, 78, 79 Calculator layout, 6 Calendar range, 44, 47, 52 Cash flow data, 12, 37–40, 76 Cash flow diagrams, 21 Chain calculations, 60 COMP (symbol), 7, 20 Compound interest, 21, 54–56, 75 Constant calculations, 60 Conversion between APR and EFF, 17, 51 COST, 56, 75 COST (PV), 18, 48, 74 Cost/sell/margin/markup calculations, 17, 56, 57, 75 COUPON (PMT), 18, 44, 73, 76 CPN/Y (N), 18, 44, 77 Cursor key, 6, 13 C/Y, 18, 22, 72, 77 Date format, 10, 44, 47, 52 Day and date calculations, 17, 18, 52–54, 74 Day-count method (ACT/360), 44, 52 DAYS, 52, 53, 75 DB, 9, 48, 74 DB (I/Y), 18, 48, 74 Decimal place, 8, 9, 63 DEG, 8, 9, 61, 78 Delete key, 12 DEPRECIATE, 48 Depreciation calculations, 17, 18, 48–50, 74 Depreciation method, 9, 48 83 Discounted cash flow analysis, 17, 18, 37–43, 72 Display layout, 7 Display notation, 8 EFF, 17, 51, 74 ENT (symbol), 7, 20 Entering dates, 47 Entering numbers, 11 Error, 14, 76–78 EXP, 64 Financial calculations, 17, 18, 72 FIXED, 58, 75 FLO_A (FLOAT A), FLO_B (FLOAT B), 7, 9 Floating point, 8, 9 Formulas, 72–75 FV, 18, 22, 72 GRAD, 8, 9, 61, 78 Independent memory (M), 8, 12, 14, 15 Insert mode, 13 INV, 64 IRR, 40, 41, 72, 77 I/Y, 18, 22, 72, 77 LIFE (N), 18, 48, 74 LINE, 64 Listed financial variables, 12, 14, 15, 18, 19 LOG, 64 M (symbol), 8 MARGIN, 56, 75 MARK UP, 56, 75 M-D-Y 1, M-D-Y 2, 18, 44, 52, 73, 75 Memory clear key, 5, 12, 13 Modify function, 63 N, 18, 22, 72 NET_PV, 40 NEW PRC (FV), 18, 54, 75 NORMAL mode, 10, 17, 60 NPV, 40, 41, 72 OLD PRC (PV), 18, 54, 75 Ordinary annuity, 7, 22, 28 Overwrite mode, 13 Payment period (payment due), 22, 28 Percent change/compound interest calculations, 17, 18, 54–56, 75 PERIODS (N), 18, 54, 75 Playback function, 13 PMT, 18, 22, 72 PRICE, 58, 75 PRICE (PV), 18, 44, 45, 73, 76 Priority levels in calculations, 81, 82 PROFIT, 58 PV, 18, 22, 72 PWR, 64 P/Y, 18, 22, 72, 77 QUAD, 64 QUANTITY, 58 RAD, 8, 9, 61, 78 Random coin, 62 Random dice, 62 Random functions, 62–63 Random integer, 63 Random numbers, 62 RATE (I/Y), 18, 40, 72 RBV, 48, 74 RDV, 48, 74 REDEMPT (FV), 18, 44, 73, 76 RESET switch, 5, 12, 81 Resetting the calculator, 5 SALVAGE (FV), 18, 48, 74 SCI, 7, 8 Scientific calculations, 60–63 Scientific notation, 8, 9, 11, 63 SD, 64 SELL, 56, 75 SET UP menu, 8–10 SL, 9, 48, 74 Specifications, 82 START MONTH, 48, 74, 77 (symbol), 8, 10, 64 STAT (statistics) mode, 10, 64 Statistical calculations, 10, 64–71 Statistical data, 12, 64–67, 76 Statistical variables, 12, 14, 16, 68 Symbol, 7 SYD, 9, 48, 74 TAB, 7, 8 Temporary memory (A-H, X-Z), 12, 14, 15 TVM (time value of money) solver, 17, 22–32, 72 TVM variable, 12, 14, 15, 18, 19, 22 VARIABLE, 58, 75 YEAR, 12, 48, 77 YIELD (I/Y), 18, 44, 45, 73, 76, 77 84
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project | https://manualzz.com/doc/23001628/el-738fb-english-manual | CC-MAIN-2020-45 | refinedweb | 15,193 | 64.81 |
* Miles Bader (miles@lsi.nec.co.jp) wrote: > Why should anyone assume there's a connection between packages installed > and usernames used? Indeed, if more than few packages did this, it > would utterly unworkable, because package names are often very short and > quite likely to intersect with usernames. Well, gee, how about because, in general, the username is the same as the package name, and it makes it nice and clear what username is associated w/ what package? Looking at one of my systems I see: daemon, bin, sys, sync, games, man, lp, mail, news, uucp, proxy, majordom, postgres, www-data, backup, msql, operator, list, irc, gnats, mysql, sshd, identd, smmsp I'm very happy to note that *none* of them are 'deb-<blah>' or 'Debian-<blah>', and you know what? I've never had any problems w/ namespace pollution. Have any of our users actually filed bugs about problems because of these names? >. It seems to me that a problem is being invented so that it can be 'fixed'. The problem doesn't exist and 'fixing' it just makes things ugly for no reason. Stephen
Attachment:
signature.asc
Description: Digital signature | https://lists.debian.org/debian-devel/2004/07/msg01862.html | CC-MAIN-2016-40 | refinedweb | 192 | 63.29 |
This bug was originally marked as duplicate of bug 173469, that is already resolved. This bug is still valid, so this seems to be another bug, but it might be related.
Build: NetBeans IDE Dev (Build 201008280001)
VM: Java HotSpot(TM) Client VM, 16.3-b01, Java(TM) SE Runtime Environment, 1.6.0_20-b02
OS: Windows 7
athompson: refreshed an SQL command.maven.model.pom.impl.POMComponentFactoryImpl.getQName(POMComponentFactoryImpl.java:66)
at org.netbeans.modules.maven.model.pom.impl.POMComponentFactoryImpl.create(POMComponentFactoryImpl.java:84)
at org.netbeans.modules.maven.model.pom.impl.POMComponentFactoryImpl.create(POMComponentFactoryImpl.java:54)
Created attachment 101789 [details]
stacktrace
Created attachment 102796 [details]
stacktrace
editing a pom
Created attachment 104520 [details]
stacktrace
Editing pom.xml - switched to another window for a second, then back to pom.xml and got the exception.
Created attachment 105730 [details]
stacktrace
I'm editing Maven pom.xml and am not finished typing XML so it is incorrect. I think I switched tabs to look at something else, then came back to this pom.xml editor and got this exception.
This bug already has 20 duplicates
see
Jesse, do you have an idea whether the fix needs to be on the XDM side or the Maven side?
Don't know. No known way to reproduce; not sure what the error really means, or what the caller is supposed to do about it. Need some advice from the maintainer of XDM, or perhaps XDM can just not throw an exception here - return an empty Document and log a warning, perhaps.
This is not XML functionality issue but the client issue .
The client here is : maven.grammar module.
org.netbeans.modules.maven.navigator.POMModelVisitor.visit(Project) method
is applied to the invalid model.
As result an exception appears.
Visitor should not be applied at all if model is broken .
So the problem originally in the method rescan of the POMModelVisitor.
Its implementation looks very strange.
As I am not the author of this code I have little idea what it is doing. The fixes of bug #161559 and bug #160657 may be related. My only guess is that in visit, model.sync() fails and the model is still invalid. I can try to defend against that but I don't really know whether it will solve anything.
core-main #a39b2899f195
>As I am not the author of this code I have little idea what it is doing.
Sure, so am I.
Jesse, sync is not intended to "fix" model .
It could have invalid state before sync and valid state after sync.
It is also possible to have VALID state before sync and invalid state after
sync.
sync is the method which is called to synchronize the XML model with XML content.
XML content could be invalid in the process of editing : one can start to type
some text and f.e. don't close some tag.
In this case "sync" will set the state of the model which will differs from valid state.
"sync" is not called each time usually. The model is synced with the underlying
document in the DataObject/editor support code. F.e. on switching between TopComponents editor/designer or move the focus to the some other UI component.
No need to do it each time in the client.
Visitor could do the sync ( this is not a problem because it uses the "dirty" flag ) but it should check state against VALID value BEFORE call model methods.
About the fix : Level.WARNING will open the special dialog with error message.
Probably this is not a best solution. It fixes the exception dialog but there are
still a problem: user will get an error each time when it switches between
different UI component in case its XML file has invalid state.
The common practice in similar situation : this is MVC whith several viewers.
Usually the viewers are Design view , navigator view, ....
Each time when user switches between these views and Editor "sync" should be
called.
In case of XML model has no valid state Views are marked with some message :
"Model is not well formed" ( or smth. else ) or viewer replace all it content
to the empty content. When model switches back to the VALID state all views
are rerendered respectively.
Such approach allows to avoid annoying error message which will shown each time
on switching between different UI components with broken XML : yes the XML
is broken and user knows about it ( see the comments in the bug ) but user
don't want to see this error each time .
Sorry , this phrase is bad:
>The model is synced with the underlying
document in the DataObject/editor support code.
I don't know details of the implementation in that case.
But this is the common practice .
So please replace this phrase to the :
The common practice is sync the model with the underlying
document in the DataObject/editor support code.
Integrated into 'main-golden', will be available in build *201103150400* on (upload may still be in progress)
Changeset:
User: Jesse Glick <jglick@netbeans.org>
Log: #190041: [69cat] IllegalStateException: The model is not initialized or is broken.
Thanks a lot Denis and Jesse. As a P2 bug, this should be considered for transplanting to NB 7 release.
(In reply to comment #11)
> "sync" is not called each time usually. [...]
> No need to do it each time in the client.
I am not sure why it is called here; hg annotate pointed to the two bugs I mentioned in comment #9.
> Level.WARNING will open the special dialog with error message.
It should not open any dialog, since there is no Throwable in the log record. One line will be printed to the log.
> user will get an error each time when it switches between
> different UI component in case its XML file has invalid state.
I wish they did, because that would mean I could reproduce the original bug and verify a fix! But before making any changes I tried making the XML file (syntactically) invalid and switching to another tab; nothing happened. Now when I try again (after the attempted fix), I get the following strange behavior:
1. Make pom.xml invalid by deleting part of a close tag.
2. Switch to another tab.
3. Switch back to pom.xml. Still shows original content in navigator.
4. Delete the rest of the element affected by #1, so the POM is now valid (still unsaved).
5. Switch to another tab.
6. Switch back to pom.xml. Get ISE from ProjectImpl.getModelVersion again.
Maybe it was valid before the sync and invalid after?
Checking the state outside of the if-block does not help. It is reported as VALID, and yet immediately afterwards the ISE is thrown.
The only thing I can find which suppresses the exception is actually going ahead and accessing the model, and just catching ISE. But then the POM model navigator is empty or incomplete even after you revert all modifications and save the now-valid POM; getting it to work again without restarting the IDE is tricky (reopening the document does not suffice and you have to make a series of edits).
So this is not a very attractive workaround. But I cannot figure out how to check for the XDMModel.status - which, confusingly, seems to be unrelated to the AbstractModel.state.
core-main #4017ce92980a
Integrated into 'main-golden', will be available in build *201103170400* on (upload may still be in progress)
Changeset:
User: Jesse Glick <jglick@netbeans.org>
Log: #190041: [69cat] IllegalStateException: The model is not initialized or is broken.
Crude workaround, pending a way to inspect the model state before trying to use it.
Denis could you review the fix please?
The reason of described confusing behavior could be synchronization
which is done in the other thread. As result model could be valid at the time
when its state is asked but it will be invalid on the next call.
To exclude such possibility model actions should be called under model lock.
The code in the visitor method performs a number of model request. The model
could be changed from the other thread before any of such requests.
It means that number of model calls should be atomic from the model point of view.
So the model transaction should be started before asking model state , then model
state should be asked. After this one can ask the model for the data and end transaction.
Probably this will exclude the behavior which you have described about "sync".
So there will be no need to catch ISE.
But please acquire the model lock in any case:
see AbstractModel.startTransaction()
But please note that "sync" probably should be called outside of transaction
( I don't remember whether XAM transactions could be nested ).
(In reply to comment #20)
> The reason of described confusing behavior could be synchronization
> which is done in the other thread.
I do not think that is the cause. The problem is consistently reproducible using the steps given in comment #15, which would not likely be true if the cause were a race condition. (There could be some occurrences of the bug "in the field" which are in fact caused by an unrelated race condition, but I have to assume that the known steps to reproduce are in fact representative.)
> the model transaction should be started before asking model state
I tried this and it seems to have no effect. The transaction is successfully acquired but the ISE continues to be thrown.
diff --git a/maven.grammar/src/org/netbeans/modules/maven/navigator/POMModelVisitor.java b/maven.grammar/src/org/netbeans/modules/maven/navigator/POMModelVisitor.java
--- a/maven.grammar/src/org/netbeans/modules/maven/navigator/POMModelVisitor.java
+++ b/maven.grammar/src/org/netbeans/modules/maven/navigator/POMModelVisitor.java
@@ -107,6 +107,7 @@
import org.netbeans.modules.maven.model.pom.Scm;
import org.netbeans.modules.maven.model.pom.Site;
import org.netbeans.modules.maven.model.pom.StringList;
+import org.netbeans.modules.xml.xam.Component;
import org.netbeans.modules.xml.xam.Model;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
@@ -1481,7 +1482,11 @@
continue;
}
synchronized (i < models.length ? models[i] : /*#192042*/new Object()) {
+ Component<?> c = (Component<?>) cut;
+ boolean gotIt = c.getModel().startTransaction();
+ System.err.println("XXX startTransaction on " + c + " -> " + gotIt);
m.invoke(visitor, cut);
+ c.getModel().endTransaction();
}
}
} catch (Exception x) {
OK then.
I've reviewed it and agree with fix.
Jesse , I'm sorry but it seems I've understood the problem with ISE.
The XAM/XDM models are used widely and there is no such problem in any
other domain specific model in case of correct usage.
I believe this is the consequence of the incorrect model usage.
The problem here as I understand : Project element becomes orphaned.
As result it is incorrect to ask it about data.
This is exactly the scenario your have described :
when model becomes invalid it could be recreated from the scratch on sync() request.
It means that elements from the previous model state could become orphaned
( the underlying XDM in that case will be replaced with new root reference and
old XDM could have invalid state). It seems this is exactly the case.
This is consequence of bad POMModelVisitor design : visitor should keep model
reference instead of its root element which could be not valid.
It's not a good time to completely reimplement navigator in appropriate way ,
but I would suggest to do the following :
Component<?> c = (Component<?>) cut;
model = c.getModel();
model.startTransaction();
if ( model.getState() == State.VALID ){
Project project = (Project)model.getRootComponent();
visit( project );
}
model.endTransaction();
Even if cut is orphaned it should still has the original reference to the
XML model ( which is always the same ). And then one can get root XML element
which is valid with valid underlying XDM model if XAM model state is VALID.
This approach should work for Project element which is root .
But as I understand the same problem could be with any descendant element.
So before call methods on the element it should be verified via "isInDocumentModel()" method.
Such verification is done in the beginning of the visit(Project) method
but it is supposed that "sync()" and check state of the model will
give element "in the model". This proposition is wrong.
So as result I object from catching an ISE.
Please review the code from this information perspective.
Created attachment 107265 [details]
Patch following all advice in comment #23 which still does not work
I think I did every check you recommend, but the ISE continues to be thrown under the same conditions.
As I see you didn't modify the visit methods and check the state of the model
before start transaction.
Please move check model state and "isInDocumentModel()" inside transaction.
If you still think there is need in "sync()" method then "isInDocumentModel()"
should be called AFTER "sync" is called and right before any model access data
methods are called ( i.e. before "t.getModelVersion()" in project case ).
It will exclude race conditions.
In case it will not work I can't imagine other reasons for ISE and let
use the fix you suggested.
Created attachment 107344 [details]
Patch following advice in comment #25 which also does not work
Since the bug is easily reproducible,.)
(b) Is there some way that client code can check the XDMModel status other than by trying an operation and catching ISE?
(In reply to comment #26)
> Created an attachment (id=107344) [details]
> Patch following advice in comment #25 which also does not work
>
> Since the bug is easily reproducible,
No I can't reproduce your scenario.
Only once I have been able to get ISE but the steps were different and I can't
repeat them again.
Please provide exact steps : each UI action , what exactly content needs to
be deleted in the pom.xml , what tabs have been used.
>.)
I can't say the exact reason but I believe there are design reasons for this:
XDM model is just XML representation ( very close to parser ). It performs
reading the XML file content. Its state is parsing state.
XAM state is domain model specific state which is logical level state .
It differs from parsing state.
>
> (b) Is there some way that client code can check the XDMModel status other than
> by trying an operation and catching ISE?
As I understand XDMModel is not intended for user usage at all. Model client
should use top level XAM model . Only XAM based model state should be used
in client code. XDM model iteslf and its status are "implementation"
which is somehow synchronized with XAM state.
ISE in the XDM is result an incorrect model usage: contract of model API
is broken ( as I already have mentioned it could f.e. result access to data
of orphaned model elements ).
*** Bug 185975 has been marked as a duplicate of this bug. ***
(In reply to comment #27)
> Please provide exact steps : each UI action , what exactly content needs to
> be deleted in the pom.xml , what tabs have been used.
As in comment #15, it is easy. Open any Maven project; make sure Navigator is displayed. Under Important Files, open pom.xml and settings.xml (or just any unrelated file). In pom.xml, delete say the '>' at the end of the tag; switch to another file; switch back to pom.xml; delete the entire broken tag; switch to another file; switch back to pom.xml once more -> ISE is thrown (suppressed in trunk but a warning printed to console). It is a little counterintuitive because the ISE occurs when refreshing the navigator view after you have _fixed_ the syntax error.
> ISE in the XDM is result an incorrect model usage: contract of model API
> is broken (as I already have mentioned it could f.e. result access to data
> of orphaned model elements).
That is fine but the incorrect model usage needs to somehow be reported more meaningfully; either some way to reliably check that a given model element is orphaned before accessing it (isInDocumentModel does not seem to suffice), or an exception thrown earlier when some mistake was made which corrupted internal state.
I'm still not able to reproduce the issue with steps your suggested.
So it is not so easy. Two builds are used : with catching ISE and without.
No console messages and no ISE .
The scenario which I've used:
1) Create Maven Web project.
2) Open pom.xml : it is opened in the editor pane and Navigator is visible
3) Open index.jsp : it is opened in the editor
4) Switch to the pom.xml and delete ">" in the closing tag for "artifactId"
element ( "</artifactId>" becomes "</artifactId" ).
5) Switch to the index.jsp.
6) Switch back and delete all broken element "artifactId" (
"<artifactId>mavenproject2</artifactId" becomes "" ).
7) Switch to index.jsp
8) Switch back.
No any error in the result.
.
Since there's not time to investigate further for 7.0, I will just put in the catch-ISE fix for now: releases #4ca91a74ee80 & releases #2693ab3bc160
(In reply to comment #31)
> .
Exactly , I can't reproduce it on Win 7 either.
>
> Since there's not time to investigate further for 7.0, I will just put in the
> catch-ISE fix for now: releases #4ca91a74ee80 & releases #2693ab3bc160
I agree.
(In reply to comment #32)
> > Is there any possible platform difference
> > here? The bug is consistently reproducible for me on Ubuntu so a timing issue
> > seems unlikely.
I can't imagine any platform dependency issue ( except race condition as result
of different Java threads implementation ).
So setStatus is initially called five times when opening a valid POM: UNPARSED -> PARSING -> UNPARSED -> PARSING -> STABLE. After breaking it and switching to another tab, and back, nothing happens. After fixing it and switching to another tab, it goes -> PARSING -> STABLE -> BROKEN.
(Actually you do not even have to delete the <artifact>...</>; it suffices to just _select_ it, so it is possible to reproduce this without switching editor tabs at all; just necessary to e.g. switch POM model -> POM inheritance and back to trigger refresh of the navigator content.)
Meanwhile, after the XDMModel is set to BROKEN, the POMModelImpl goes from its initial VALID to NOT_WELL_FORMED and immediately back to VALID. The tops of stack traces after the edit is made:
-> PARSING
at org.netbeans.modules.xml.xdm.XDMModel.setStatus(XDMModel.java:1008)
at org.netbeans.modules.xml.xdm.XDMModel.prepareSync(XDMModel.java:178)
at org.netbeans.modules.xml.xdm.XDMModel.sync(XDMModel.java:161)
at org.netbeans.modules.xml.xdm.xam.XDMAccess.sync(XDMAccess.java:156)
at org.netbeans.modules.xml.xam.AbstractModel.sync(AbstractModel.java:285)
at org.netbeans.modules.maven.hints.pom.StatusProvider$StatusProviderImpl.findHints(StatusProvider.java:196)
-> STABLE
at org.netbeans.modules.xml.xdm.XDMModel.setStatus(XDMModel.java:1008)
at org.netbeans.modules.xml.xdm.XDMModel.prepareSync(XDMModel.java:198)
-> BROKEN
at org.netbeans.modules.xml.xdm.XDMModel.setStatus(XDMModel.java:1008)
at org.netbeans.modules.xml.xdm.XDMModel.finishSync(XDMModel.java:212)
at org.netbeans.modules.xml.xdm.XDMModel.sync(XDMModel.java:163)
-> NOT_WELL_FORMED
at org.netbeans.modules.xml.xam.AbstractModel.setState(AbstractModel.java:212)
at org.netbeans.modules.xml.xam.AbstractModel.sync(AbstractModel.java:289)
-> VALID
at org.netbeans.modules.xml.xam.AbstractModel.setState(AbstractModel.java:212)
at org.netbeans.modules.xml.xam.dom.AbstractDocumentModel.refresh(AbstractDocumentModel.java:628)
at org.netbeans.modules.maven.model.pom.POMModel.refresh(POMModel.java:68)
at org.netbeans.modules.maven.hints.pom.StatusProvider$StatusProviderImpl.findHints(StatusProvider.java:197)
So the extra call to refresh might be the problem. I suspect that refresh is just not implemented correctly; it sets the XAM model state to valid but does not change the XDM model state.
In fact it looks like bug #157599 was fixed earlier and this bug is just the special case when there is a text selection. I can try to make an analogous fix in trunk; not sure if it ought to be backported to release70 or not: core-main #e1e6dbb60405
Integrated into 'main-golden', will be available in build *201103300400* on (upload may still be in progress)
Changeset:
User: Jesse Glick <jglick@netbeans.org>
Log: Alternate fix of #190041: ISE from POM model navigator.
not able to reproduce -> verified.
Product Version: NetBeans IDE 7.0 (Build 201104080000)
Java: 1.6.0_24; Java HotSpot(TM) 64-Bit Server VM 19.1-b02-334
System: Mac OS X version 10.6.7 running on x86_64; MacRoman; en_US (nb)
Userdir: /Users/tomas/.netbeans/7.0 | https://netbeans.org/bugzilla/show_bug.cgi?id=190041 | CC-MAIN-2017-17 | refinedweb | 3,410 | 58.99 |
These postings are provided "AS IS" with no warranties, and confer no rights. The use of any script / code samples is subject to the terms specified here.
When I threw together Twitfeed one of the things I wanted to do was to have the "swatches" scale appropriately so if there were only a few words in a particular tweet it wouldn't look too lost. The Viewbox (currently in preview as part of the Silverlight Toolkit) is perfect for this. The role of the Viewbox is to scale content to fill available space.
For example, below is a simple Silverlight application with a Border containing a TextBlock in the upper cell (Fontsize="24"). In the lower cell, an indentical TextBlock is wrapped in a Viewbox (still inside a Border). On the right is a Listbox that allows you to change the Stretch property of the Viewbox. I've set this to None initially (so no stretch but the Viewbox does have the effect of centering the TextBlock).
If you change the Stretch to Fill, the Viewbox will scale the content without respecting the aspect ratio. Uniform will scale to fill either width or height, respecting the AR and ensuring the content isn't clipped while UniformToFill will scale and allow content to be clipped. There's a good description of the enumeration on MSDN.
Now this all sounds great but I did run into a few obstacles with the Silverlight Viewbox.
As soon a I put my controls inside a Viewbox I could no longer reference them from code. Actually, all looked well in Visual Studio but at runtime the control (inside the Viewbox) could not be found. Ning Zhang who worked on the Viewbox control has a great post that describes the ins and outs of the control and specifically why x:Name doesn't work for child elements of the Viewbox (FindName doesn't work across namespaces)
That's an understatement and perhaps this mess was of my own making but trying to get things to size correctly proved nigh on impossible. The trouble is, TextWrapping requires a Width on the TextBlock and my TextBlocks are not of a fixed width. Essentially I just divide the window into a 3x3 matrix of Viewboxes. So each Textbox gets 1/3 of the width. Easy.
However, there seems to be some interaction that occurs with the Viewbox that means the scaling goes to pot (technical term) if you re-size the window then regenerate the TextBoxes. The Window resize is fine but when I refresh the page (essentially refreshing the contents of the Viewboxes) there seems to be some "history" of the original page width that causes the TextBlocks to scale incorrectly (that's my definition of incorrect - ie not the way I'd like :-)).
In the end I have rather a cludgy solution that involves storing the original window size what the app was invoked and modifying the FontSize as the application scales which seems to work okay. I'd prefer a simpler and more elegant solution though.
I wanted to scale the Listbox that represents my list of tweet terms. I could not get this to work (my mistake) but now have it working. I'll post about the tweet terms Listbox separately as there are a few things in there (eg "disabling" selection, highlighting search terms as they change) that I think are worth describing.
The Viewbox is an incredibly handy control but if you find yourself in the arrange / measure / what the heck's going on nightmare that I found myself in, maybe better step back and see if there's a simpler approach to achieve what you want.
PingBack from
In this issue: Pete Brown, Tim Greenfield, Boyan Nikolov, Jesse Liberty, Mike Ormond, David Justice,
Nice article. It's always good to know these things in advance, before I decide to use a control troughout my production code. :)
Trademarks |
Privacy Statement | http://blogs.msdn.com/mikeormond/archive/2008/12/05/adventures-with-the-silverlight-viewbox.aspx | crawl-002 | refinedweb | 656 | 66.78 |
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.
Domain on Many2Many table not working
Hi Guys,
I know there is a lot of question regarding this, but I can't make it to work on my case.
I have field selected_subject_ids under student_registration object,
in the student_registration object i have field standard_id and inside of it i have fields many2many subject_ids.
Basically what I want to do is to filter the selected_subject_ids to only select subject under the standard_id.subject_ids
What I've tried so far in the selected_subject_ids field:
domain="[('id','in',standard_id.subject_ids)]"
domain="[('id','in',standard_id.subject_ids.ids)]"
domain="[('id','in',[i.id for i in standard_id.subject_ids])]"
I also try to change the operator to '=', same case...
But when I try to hard code it, it works..
domain="[('id','in',[1,2,3,4])]"
The error is :
TypeError: context is undefined
My solution is a mix with what @Jignesh Mehta is proposing, you could do it like this:
def _get_subject_domain(self, cr, uid, ids, name, arg, context=None):
res = {}
for sub_id in self.browse(cr, uid, ids, context=context):
res[sub_id.id] = [(6, 0, [subj.id for sub_id.standard_id.subject_ids])]
return res
_columns = {
...
'subject_domain_ids': fields.function(_get_subject_domain, type='many2many', relation='subject.model_name', string='Subject Domain'),
...
}
in the view
<field name="subject_domain_ids" invisible="1"/>
<field name="standard_id"/>
<field name="selected_subject_ids" domain="[('id','in', subject_domain_ids[0][2])]"/>
and the modified @Jignesh Mehta onchange returning the domain for the field selected_subject_ids
@api.onchange('standard_id')
def standard_id_onchange(self):
return {'domain': {'selected_subject_ids': [('id', 'in', [subj.id for subj in self.standard_id.subject_ids])]}}
Hi Axel, Thanks for your reply. Actually I've been thinking to do this way, But what if the student registration already has the standard_id filled before. Then the onchange won't work. Domain works on onchange, but why it won't work on field based? This code doens't work: selected_subject_ids = fields.Many2many('subject.subject', 'reg_subject_rel', 'reg_id', 'subject_id', 'Selected Subjects', domain="[('id', 'in', [subj.id for self.standard_id.subject_ids])]") And by the way, you have some typo over here. I've modified it to work like this: @api.onchange('standard_id') def standard_id_onchange(self): return {'domain': {'selected_subject_ids': [('id', 'in', [subj.id for subj in self.standard_id.subject_ids])]}}
Yes, I see that I miss subj var in the list compression. I just try to fix the code of @Jignesh Mehta to see if using it you could solve your problem. Let me give you the way I use to do it. I will override my answer with the new one
It was a mix finally what I'm using
You could also set the initial value for the form to use a domain value from where the form is not saved yet and the function does not get calculated already.
Hi axel, I manage to make it work as per your code. Will post the updated code in the new api. Btw, what do you mean on the initial value so it doesn't calculate ? Thank you, axel
Btw Axel, don't you think that kind kind of method will make the server become slow ? (as function will always load )
I mean that function or computed field only will have their values calculated after they exist in the database. So for a new record you need to set it's value using a default or with onchanges, Otherwise the value could not be taken into account. For your second question the answer is no, I don't thinks that, it will no make the server slow
Hi all,
I manage to make it work like Axel's solution.
Here is the code in the api v8:
add this field :
@api.multi
def _get_subject_domain(self):
for record in self:
record.subject_domain_ids = [(6, 0, [subj.id for subj in record.standard_id.subject_ids])]
subject_domain_ids = fields.Many2many('subject.subject', string='Subject Domain', compute='_get_subject_domain')
on the view :
<field name="subject_domain_ids" invisible="1"/>
<field name="selected_subject_ids" domain="[('id','in', subject_domain_ids[0][2])]"/>
Hello Wilbert,
Try below code.
@api.onchange('standard_id')
def standard_id_onchange(self):
return {'domain': {'subject_ids': [('standard_id', '=', self.standard_id.id)]}}
Hope it works for you.
Thanks,
Hi Jignesh. Thanks for your reply. Please see my commend of other post above. thanks
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/domain-on-many2many-table-not-working-98588 | CC-MAIN-2017-34 | refinedweb | 743 | 51.04 |
You walk into work tomorrow morning, and your boss says this:
Boss: Hey, we're gonna need to go ahead and have you implement require_relative in rubinius. We have some new servers coming in, and we'll be running it in production, but we use some 1.9.2 features of MRI that haven't been implemented yet. So if you could just go ahead and get to implementing that, that would be terrific, OK?
Wat do?
(Disregard that your boss would never say this. I kinda wish some of mine would...)
You: Excuse me, I believe you have my stapler...
Err, sorry.
You: No problem, boss. Rubinius is mostly just Ruby, and it has a really helpful core team. I'm sure it won't be a big deal.
Would you say this? Well, you should. I'm not gonna lie and say that every feature is super simple to implement, or rbx-2.0 would be out already, but for a language interpreter, Rubinius is one of the easiest I've ever tried to get into. I actually did implement require_relative last night, and it took me about an hour and a half.
This is my story.
(note: dramatazation. Actual wording made unneccesarily silly to protect the innocent. please do try this at home)
$ ssh stevessecretserver $ tmux attach <brings up irssi, I'm already in #rubinius on Freenode> #rubinius: steveklabnik: hey, I need require\_relative to run my app. How hard would you think that is to implement? #rubinius: evan: Naw, man, it'd take like fifteen minutes. Go check out, it's alredy basically got what you want #rubinius: steveklabnik: sweet. #rubinius: brixen: just grep for 'def require' #rubinius: brixen: and run bin/mspec -tx19 core/kernel/require\_relative to run the RubySpecs for it.
Armed with this knowledge, I found where require is defined in rbx:
def require(name) Rubinius::CodeLoader.require name end module_function :require
Of course, I had to look at CodeLoader:
# Searches for and loads Ruby source files and shared library extension # files. See CodeLoader.require for the rest of Kernel#require # functionality. def require Rubinius.synchronize(self) do return false unless resolve_require_path return false if CodeLoader.loading? @load_path if @type == :ruby CodeLoader.loading @load_path end end if @type == :ruby load_file else load_library end return @type end
Hmm, see
CodeLoader.require. There are codeloader18 and codeloader19
files...
module Rubinius class CodeLoader # Searches $LOAD_PATH for a file named +name+. Does not append any file # extension to +name+ while searching. Used by #load to resolve the name # to a full path to load. Also used by #require when the file extension is # provided. def search_load_path(name, loading) $LOAD_PATH.each do |dir| path = "#{dir}/#{name}" return path if loadable? path end return name if loading and loadable? "./#{name}" return nil end end end
Okay. So we define specific stuff into the 19 file. There's also a kernel19. So I worked this up:
# Attempt to load the given file, returning true if successful. Works just # like Kernel#require, except that it searches relative to the current # directory. # def require_relative(name) Rubinius::CodeLoader.require_relative(name) end module_function :require_relative
# requires files relative to the current directory. We do one interesting # check to make sure it's not called inside of an eval. def self.require_relative(name) scope = Rubinius::StaticScope.of_sender script = scope.current_script if script require File.join(File.dirname(script.data_path), name) else raise LoadError.new "Something is wrong in trying to get relative path" end end
But then... running the specs gives me bunches of errors. What gives?
<back in irc> #rubinius: steveklabnik: yo, my specs are failing, and I'm a n00b. Halp pl0x? #rubinius: brixen: oh, yeah, well, the StaticScope is the current scope, and you're down another method, so that's _totally_ gonna screw up your paths. Just get it above and pass it down. Oh, and File.join is dumb, File.expand_path that shit! #rubinius: steveklabnik: words.
So then I made this one little change:
# Attempt to load the given file, returning true if successful. Works just # like Kernel#require, except that it searches relative to the current # directory. # def require_relative(name) scope = Rubinius::StaticScope.of_sender Rubinius::CodeLoader.require_relative(name, scope) end module_function :require_relative
# requires files relative to the current directory. We do one interesting # check to make sure it's not called inside of an eval. def self.require_relative(name, scope) script = scope.current_script if script require File.expand_path(name, File.dirname(script.data_path)) else raise LoadError.new "Something is wrong in trying to get relative path" end end
$ bin/mspec -tx19 core/kernel/require_relative rubinius 2.0.0dev (1.9.2 cade3517 yyyy-mm-dd JI) [x86_64-apple-darwin10.8.0] ..................... Finished in 0.191995 seconds 1 file, 20 examples, 47 expectations, 0 failures, 0 errors
One more pull request, and I've got a patch in on rbx. I had one a few months ago, but this one was way cooler.
Even if I didn't have some code to look at, because Rubinius is just Ruby, it was really easy to dive in and check out the code, because it's all Ruby. Seriously. Rubinius is just Ruby. Just Ruby. Ruby.
So dive in and add some features today! If having an awesome alternate Ruby implementation isn't enough for you, the rbx team will bribe you with special stickers for committers, and sweet black-on-black tshirts for people with 10 commits or more! | http://blog.steveklabnik.com/posts/2011-10-04-rubinius-is-awesome | CC-MAIN-2018-47 | refinedweb | 908 | 68.87 |
Playground and Cheatsheet for Learning PythonPlayground and Cheatsheet for Learning Python.
It is a cheatsheet because you may get back to these code examples once you want to recap the syntax of standard Python statements and constructions. Also because the code is full of assertions you'll be able to see expected functions/statements output right away without launching them.
You might also be interested in 🤖 Interactive Machine Learning Experiments
How to Use This RepositoryHow to Use This Repository
Each Python script in this repository has the following structure:
"""Lists <--- Name of the topic here # @see: <-- Link to further readings goes here Here might go more detailed explanation of the current topic (i.e. general info about Lists). """ def test_list_type(): """Explanation of sub-topic goes here. Each file contains test functions that illustrate sub-topics (i.e. lists type, lists methods). """ # Here is an example of how to build a list. <-- Comments here explain the action squares = [1, 4, 9, 16, 25] # Lists can be indexed and sliced. # Indexing returns the item. assert squares[0] == 1 # <-- Assertions here illustrate the result. # Slicing returns a new list. assert squares[-3:] == [9, 16, 25] # <-- Assertions here illustrate the result.
So normally you might want to do the following:
- Find the topic you want to learn or recap.
- Read comments and/or documentation that is linked in each script's docstring (as in example above).
- Look at code examples and assertions to see usage examples and expected output.
- Change code or add new assertions to see how things work.
- Run tests and lint the code to see if it work and is
written correctly.
Table of ContentsTable of Contents
PrerequisitesPrerequisites
Installing Python
Make sure that you have Python3 installed on your machine.
You might want to use venv standard Python library to create virtual environments and have Python, pip and all dependent packages to be installed and served from the local project directory to avoid messing with system wide packages and their versions.
Depending on your installation you might have access to Python3 interpreter either by
running
python or
python3. The same goes for pip package manager - it may be accessible either
by running
pip or
pip3.
You may check your Python version by running:
python --version
Note that in this repository whenever you see
python it will be assumed that it is Python 3.
Installing dependencies
Install all dependencies that are required for the project by running:
pip install -r requirements.txt
Testing the CodeTesting the Code
Tests are made using pytest framework.
You may add new tests for yourself by adding files and functions with
test_ prefix
(i.e.
test_topic.py with
def test_sub_topic() function inside).
To run all the tests please execute the following command from the project root folder:
pytest
To run specific tests please execute:
pytest ./path/to/the/test_file.py
Linting the CodeLinting the Code
Linting is done using pylint and flake8 libraries.
PyLintPyLint
To check if the code is written with respect to PEP 8 style guide please run:
pylint ./src/
In case if linter will detect error (i.e.
missing-docstring) you may want to read more about
specific error by running:
pylint --help-msg=missing-docstring
Flake8Flake8
To check if the code is written with respect to PEP 8 style guide please run:
flake8 ./src
Or if you want to have more detailed output you may run:
flake8 ./src --statistics --show-source --count
Supporting the projectSupporting the project
You may support this project via ❤️️ GitHub or ❤️️ Patreon. | https://giters.com/trekhleb/learn-python | CC-MAIN-2021-31 | refinedweb | 583 | 63.7 |
Day 23, Java Holiday Calendar 2016, Use Mappable Types Instead of Bloated Ones
Today's tips is about mappable types. Traditionally we Java developer have relied on inheritance and types with a number of methods to support convenient use of our classes. A traditional Point class would contain x and y coordinates and perhaps also a number of functions that allows us to easily work with our Point.
Imagine now that we add new shapes like Circle and that Circle inherits from Point and adds a radius. Further imagine that there are a bunch of other geometric shapes like Line, Square and the likes that also appear in the code. After a while, all our classes becomes entangled in each other and we end up in a messy hair ball.
However, there is another way of structuring our geometric classes such that there is a minimum of inter-class coupling. Instead of letting each geometric class provide specific methods for translations like add() and flipAroundXAxis() we could add just one or two generic methods that operates on the geometric figure and returns a value of any type. We could then break out the old methods from the geometric classes and convert them to functions and just apply them on the objects rather than letting the objects handle that responsibility.
Let us take the concept for a spin!
TraitsWe start with some basic Traits of the geometrical shapes that are shared amongst most shapes. Here are the basic traits:
interface HasX { int x(); } // x is the x-coordinate interface HasY { int y(); } // y is the y-coordinate interface HasR { int r(); } // r is the radius
What's the Point?Now it is time to create our Point interface like this:
interface Point extends HasX, HasY { static Point point(int x, int y) { return new Point() { @Override public int x() { return x; } @Override public int y() { return y; } }; } static Point origo() { return point(0, 0); } default <R> R map(Function<? super Point, ? extends R> mapper) { return Objects.requireNonNull(mapper).apply(this); } default <R, U> R map(BiFunction<? super Point, ? super U, ? extends R> mapper, U other) { return Objects.requireNonNull(mapper).apply(this, other); } }
I have purposely refrained from creating an implementation class of the Point interface. Instead, each time the static point() method is called, an instance from an anonymous class is created. This illustrates that the implementation class is "pure" and does not inherit or override anything. In a real solution, there could of course be an implementation of an immutable class PointImpl.
In the middle, there is a conveniency method that return a point in origo (e.g. point(0, 0)).
The two methods at the end of the class are where the interesting stuff starts. They allow us to apply almost any function to a Point.
The first one takes a mapping function that, in turn, takes a point and maps it so something else (i.e. a Function)
The last one takes a mapping function that takes two points and maps it to a Point (e.g. a Binary Function). The mapping function applies the current Point (i.e. "this") as the first parameter and then it also applies another point. That other point is given as the second argument to the map() function. Complicated? Not really. Read more and it will be apparent what is going on.
The FunctionsNow we can define a number of useful functions that we could apply to the Point class.
interface PointFunctions { static UnaryOperator<Point> NEGATE = (f) -> point(-f.x(), -f.y()); static BinaryOperator<Point> ADD = (f, s) -> point(f.x() + s.x(), f.y() + s.y()); static BinaryOperator<Point> SUBTRACT = (f, s) -> point(f.x() - s.x(), f.y() - s.y()); static UnaryOperator<Point> SWAP_OVER_X_AXIS = (f) -> point(f.x(), -f.y()); static UnaryOperator<Point> SWAP_OVER_Y_AXIS = (f) -> point(-f.x(), f.y()); static BinaryOperator<Point> BETWEEN = (f, s) -> point((f.x() + s.x()) / 2, (f.y() + f.y()) / 2); static Function<Point, String> TO_STRING = (p) -> String.format("(%d, %d)", p.x(), p.y()); static BiFunction<Point, Point, Boolean> EQUALS = (f, s) -> (f.x() == s.x()) && (f.y() == s.y()); // static BiFunction<Point, Point, Double> DISTANCE = (f, s) -> Math.sqrt((f.x()-s.x())^2+(f.y()-s.y())^2); // static Function<Point, UnaryOperator<Point>> ADD2 = s -> (f) -> point(f.x() + s.x(), f.y() + s.y()); }
These methods (or any other similar methods or lambdas) can now be applied to points without polluting the classes.
Example of UsageThis code snippet will create a first point at origo, apply a number of translations to it and then convert it to a string using the TO_STRING mapper. Note how easy it would be to use another string mapper because now the "to string" functionality is separate from the class itself. It would also be easy to use a custom lambda instead of one of the pre-defined functions.
System.out.println( origo() .map(ADD, point(1, 1)) // 1 .map(SWAP_OVER_X_AXIS) // 2 .map(NEGATE) // 3 .map(BETWEEN, point(-1, -1)) // 4 .map(TO_STRING) );
This will produce the following output:
(-1, 0)
As can be seen in the picture below, this seams to be correct:
Expanding the ConceptIf we later introduce a Circle interface like this
interface Circle extends HasX, HasY, HasR { // Stuff similar to Point... }
and we change our methods so that they can work with the traits directly (and after some additional refactoring not shown here) we can get a decoupled environment where the functions can be made to operate on any relevant shape. For example, the following method can return a "toString" mapper that can work on anything having an x and a y value (e.g. both Point and Circle)
static <T extends HasX & HasY> Function<T, String> toStringXY() { return (T t) -> String.format("(%d, %d)", t.x(), t.y()); }
After further modification, we could take a Circle and ADD a Point to it and the circle will be translated using the point's coordinates.
Alternate SolutionsIt is possible to wrap any class in an Optional and then use the Optional's map() method to map values. In that case we do not need the map() functions in the shapes. On the other hand, we would have to create an Optional and then also get() the end value once all mappings have been applied.
Another way would be just having a bunch of static methods that takes a Point and other shapes as parameters like this:
static <T extends HasX & HasY> Point add(Point p, T other) { return point(p.x() + other.x(), p.y() + other.y()); }
But that... is another story...
Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season. I am contributing to open-source Speedment, a stream based ORM tool and runtime. Please check it out on GitHub.
return Objects.requireNonNull(mapper).apply(this);
I think, 'Objects.requireNonNull(' here is redundant.
True. I always make a habit of checking input parameters. In this case though, the result would be the same regardless of the check... | http://minborgsjavapot.blogspot.com/2016/12/day-23-java-holiday-calendar-2016-use.html | CC-MAIN-2018-34 | refinedweb | 1,176 | 64.1 |
My life would be much easier if I could inspect what variables are assigned to what arguments.
In the line:
self.manager.addState("", [0,0]) # start with 2 empty buckets
The
addState method is defined in
manager class as taking 2 parameters. It is called in the
playGame method. I am having trouble understanding what parameters in the signature map to what arguments in the call.
def addState (self, parentState, newState) : "add state if it's new. Remember its parent" if self.seen.has_key(str(newState)) : return self.seen[str(newState)] = str(parentState) self.queue.append (newState)
In the code below, if I assume that
newState corresponds to
[0,0] because it is not a singular value(I'm not sure what
"" maps to) then this code should not run at all.
self.manager.addState("", [0,0]) # start with 2 empty buckets
Question(s):
Is my understanding of this correct?
What is the easiest way to inspect the running state of this so I can verify which parameters map to which arguments?
problem link: | http://www.howtobuildsoftware.com/index.php/how-do/7kp/python-debugging-interpreter-how-can-i-figure-out-which-parameters-map-to-which-variables | CC-MAIN-2017-13 | refinedweb | 174 | 66.94 |
Hello,
I would like to know if Silverlight can use methods, properties or events of a custom library, activex components.
And how to register and use them if possible ?
Thanks in advance for your help.
You can declare a Silverlight library (not one built with/for .NET Framework) in XAML using the namespace declaration and specify the type and assembly name. Then you can reference those types in XAML or in code-behind. If your declared assembly has other referenced assemblies, the Silverlight CLR assembly resolution mechanism will trigger their download without you having to declare them in the XAML. They will be looked for in the same location as your declared assembly was downloaded from on the server.
Silverlight does not provide you any way to install or run an ActiveX control. You need to use the browser's facilities for this and this requires users to explicitly opt in. However, it is possible for two functional ActiveX controls on an HTML page to talk to each other via the Javascript layer. In fact I have a sample of this using Silverlight and Google Gears - two separate ActiveX controls in IE from separate vendors with the integration coming together in the HTML page with script. See
Ashish Shetty | Program Manager | Microsoft
Thanks. You help me very much on that particular point.
Regards.
hello.
do keep in mind that this will limit your solution to IE only. | http://silverlight.net/forums/p/1896/4669.aspx | crawl-001 | refinedweb | 237 | 64.1 |
During the Spring Workshop, Rod Johnson started a brief discussion on how to find out in a Java Class who invoked the method currently being executed. The best trick: create a new Throwable and inspect the stacktrace. In Java 1.3 you had to use the printstackTrace() method and parse the String, in Java 1.4 there is the StackTraceElement[] that you can inspect. A simple utility class that informs any caller about his own caller could look like this:
public static String whoCalledMe() { Throwable t = new Throwable(); return t.getStackTrace()[2].toString(); }
or:
public static Class whoCalledMe() { Throwable t = new Throwable(); return t.getStackTrace()[2].getClass(); // that is: Class, not Object! }
example code:
/* * Created on Jun 10, 2005 * */ package nl.amis.util; /** * @author Lucas * */ public class CallStackUtils { public static String whoCalledMe() { Throwable t = new Throwable(); return t.getStackTrace()[2].toString(); } public String getCall() { return whoCalledMe(); } public String inBetween() { return getCall(); } public static void main(String[] args) { CallStackUtils call = new CallStackUtils(); System.out.println(call.inBetween()); } }
The output of running main is: nl.amis.util.CallStackUtils.inBetween(CallStackUtils.java:24)
Methods on StackTraceElement include: isNativeMethod() getLineNumber() getClass() getMethodName() getFileName() getClassName()
2 thoughts on “Who is calling me? – Analyzing the Java Callstack”
Hi!
I blogged about this more than 2 years ago, and was then told by someone that it was an old well known trick. I guess there’s always someone else ahead…
In Java 1.5 you don’t need to create Throwable anymore (expensive operation), use Thread.getStackTrace() instead. | https://technology.amis.nl/it/who-is-calling-me-analyzing-the-java-callstack/ | CC-MAIN-2021-17 | refinedweb | 251 | 58.18 |
162513/what-does-include-iostream-do
When I had started learning the basics of C++, I've always used the headings
#include <iostream>
using namespace std;
I want to ask what is the point of iostream and Is it required every time as a heading?
In order to read or write the standard input or output streams, you need to include it by using:-
int main( int argc, char * argv[] )
{
std::cout << "Hello World!" << std::endl;
return 0;
}
This given program will not compile unless you add #include <iostream> and also the second line is not needed:-
using namespace std;
This function will inform the compiler that the name symbol which is defined in the std namespace has to be brought in the scope of the program to let you remove the qualifier of the namespace. Below is an example:-
#include <iostream>
using namespace std;
int main( int argc, char * argv[] )
{
cout << "Hello World!" << endl;
return 0;
}
You would have noticed that there is no longer a need to refer to the output stream with the entire qualified name std::cout and one can use the shorter name cout. I would personally recommend not to bring in all symbols in the namespace of a header file and rather you should individually select the symbols which you would want to be shorter so I would suggest you use this:
#include <iostream>
using std::cout;
using std::endl;
int main( int argc, char * argv[] )
{
cout << "Hello World!" << endl;
return 0;
}
Please note that this is subjective and a matter of personal preference.
Hey, @Josh,
Be Clear About Your End Goal. Software ...READ MORE
To answer your question, “passing by value” ...READ MORE
When any POST request is made, then ...READ MORE
canonical URLs are distinct URL used to ...READ MORE
There is a seemingly undocumented feature of setup that ...READ MORE
Hadoop is not designed for records about ...READ MORE
params needs to be an array, try
{"jsonrpc":"2.0","method":"eth_se ...READ MORE
The .map method will take an object ...READ MORE
According to James Shore, the term “Dependency ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/162513/what-does-include-iostream-do?show=162592 | CC-MAIN-2022-27 | refinedweb | 374 | 68.3 |
UNGETC(3S) UNGETC(3S)
NAME
ungetc - push character back into input stream
SYNOPSIS
#include <<stdio.h>>
ungetc(c, stream)
FILE *stream;
DESCRIPTION
ungetc() pushes the character c back onto an input stream. That char-
acter will be returned by the next getc() call on that stream.
ungetc() returns c, and leaves the file stream unchanged.
One character of pushback is guaranteed provided something has been
read from the stream and the stream is actually buffered. In the case
that stream is stdin, one character may be pushed back onto the buffer
without a previous read statement.
If c equals EOF, ungetc() does nothing to the buffer and returns EOF.
An fseek(3S) erases all memory of pushed back characters.
SEE ALSO
fseek(3S), getc(3V), setbuf(3V)
DIAGNOSTICS
ungetc() returns EOF if it cannot push a character back.
18 November 1987 UNGETC(3S) | http://modman.unixdev.net/?sektion=3&page=ungetc&manpath=SunOS-4.1.3 | CC-MAIN-2017-30 | refinedweb | 143 | 74.79 |
Compatibility
- 0.8.1 and master5.35.25.15.04.2
- 0.8.1 and masteriOSmacOS(Intel)macOS(ARM)LinuxtvOSwatchOS
A wrapper for libavif + Xcode project. Support Carthage && CocoaPods && SwiftPM.
A wrapper for libavif + Xcode project. This enables Carthage && SwiftPM support.
This repo also including the CocoaPods's spec file to use libavif.
By default, libavif is built with aom codec support. aom is the first AV1 codec during the standard draft implementation.
dav1d is the new and next generation AV1 codec, focused on speed and correctness.
See more about explanation for why starting a new project but not improving aom
From v0.3.0, libavif can built with dav1d. For CocoaPods user, you can simply use the subspec for this. Carthage for optional dav1d codec is not supported currently.
rav1e is the fastest and safest AV1 encoder. Which use Rust programming to provide fast and safe codec compared to aom. Its current form it is most suitable for cases where libaom (the reference encoder) is too slow.
See more about performance
From v0.4.3, libavif can built with rav1e. For CocoaPods user, you can simply use the subspec for this. Carthage for optional rav1c codec is not supported currently.
Note rav1e currently only support iOS && macOS. watchOS and tvOS supports need Rust community upstream support.
libavif is (via this repo) available through Carthage.
github "SDWebImage/libavif-Xcode"
Note Carthage does not support dav1d or rav1e optional codec, use only aom.
libavif is available through CocoaPods.
By default, libavif is built with aom decoding/encoding codec, which is stable, but slow.
pod 'libavif'
If you need the dav1d decoding codec, use the subspec:
pod 'libavif/libdav1d'
If you need the rav1e encoding codec, use the subspec:
pod 'libavif/librav1e'
libavif is available through Swift Package Manager.
let package = Package( dependencies: [ .package(url: "", from: "0.4.5") ], // ... )
Note SwiftPM does not support dav1d or rav1e optional codec, use only aom.
Use libavif as you would normally, this is just a repo that adds an Xcode proj.
For Swift Package Manager user, it's recommended to use the modular import instead of C headers.
@import libavif; // or if you don't use module #import <avif/avif.h>
import libavif
libavif is available under the BSD License. | https://swiftpackageindex.com/SDWebImage/libavif-Xcode | CC-MAIN-2021-10 | refinedweb | 375 | 69.68 |
Programming Tutorial
First starting with c++
prerequisite for this is c some guys get books of deep c i hope
This tutor designed for noobs so anybody who knows c++ well just keep quiet and dont show off ur ...... etccc
i go slowly one chapter per day starting some theories it may quite boring pls adopt that
if u wont understand some concepts later we go by examples u can understand everything .....
after the session overs any doubts just leave ur questions here...
about compiler its ur wish ....
i wont help the compiler configuration and all ..... download it via software zones...
That's it
lets start c++
A little historyThe C++ programming language was initially created by Bjarne Stroustrup, as a "better C". C++ was an attempt to extend and (to some extent) change the C programming language to overcome some problems. C++ standardized in 1998.
Should I Learn C First?The question arises in ur mind .For my tutorial u should have learnt atleast upto for loop,functions. Because C++ is a superset of C. I have one good book for c named deep c …leave mail id in my scrap I will send through mail mention everything properly.
Comparison c++ with other languagesAfter learnin this tutorial …. Finally I will tell.
skipping
variables, conditional statements, loops ,operators, functions. These r similar in C.
What Is a Program?
The word program is used in two ways: to describe individual instructions, or source code,created by the programmer ex. Hello.cpp and to describe an entire piece of executable software.ex.hello.exe
Move to compiler
-----------------Top 6 c-c++ compiler-------------------
1. DevC++
2. MinGW Studio
3. GNU Emacs and XEmacs
4. Microsoft Visual C++ 2005
5. Eclipse for C++ with CDT
6. Code::Blocks
Compiler types
16-bit compiler ex: familiar one turbo c++
32-bit compiler ex: Microsoft Visual C++ 2005
64-bit compiler
Wat makes difference
In 16 bit compiler the int size is 2 bytes
For 32 bit int size is 4 bytes
Now compiling phases
First u will create a code using any editor even our notepad is a editor.
Most of them have turbo c++ but i recommend move to mingw studio or Microsoft
Turbo c++ also u can practice
code:
And save it as hello.cpp
-->>Note: wait look the code once .. std ve u heard about it …. Note it that is namespace
>>Before compilation, a special program called the preprocessor scans the source code and preforms simple substitution.
>>The preprocessor examines all lines beginning with # , performs the corresponding actions and macro replacements, and produces a preprocessed version of your program with the file name suffix .i. The .i file is created in a directory used to store temporary files.
>>Preprocessor is separate topic will be discussed elaborately later.
>>Compiler ensures that the code is valid(syntax checking like that) and will sequence into an executable program(sequence arrangement for execution). Under some compilers, you may get messages or warnings with your program
Wat this hello.obj or hello.o contains?
The .o or .obj contains the binary version of the source code which is not directly executable.
>>The final form hello.exe
Here we have one component named linker which combines the object codes into one complete program by integrating libraries(header files) and the code(program which contains 2 or more source codes in separate files ) and producing an executable program.
>>>>>Note: reversing using c++ object code to exact source code is almost impossible to do.If u get many tools in net about reversing but 98% will not give the exact source.Maybe if u wanna knw more about reversing ask some forms and do and report here I got no practice in that .. I too will learn
Wat is class and object?
Ex : Apple is a fruit
Class : fruit
Object :apple
(classes)
• Putting behaviors (functions) and attributes (data) together.
• A class does not exist in the memory of computer during program execution.
(Object)
• An instance of a class. There can be more than one instance for a class.
Frm above example
Consider fruit
Lets check out fruits attributes
(programmatic view inside C++ program looks like this…)
Fruit color - string strFruitColor;
Fruit name - string strFruitName;
Lets check out fruits behaviors
Fruit weight
int weight(string strFruitName)
{
// some code to find weight
return intFruitWeight;
}
code:
class Fruit {
// fields
string strFruitColor;
string strFruitName;
// a function
int weight(string strFruitName)
{
// some code to find weight
return intFruitWeight;
}
}
move to encapsulation, polymorphism,inheritance
What is encapsulation? What’s its uses?
In general the definition is hiding the non-essential characteristics to others.
ex:
->If I want to show the gifts I have received from my girlfriend I'll show otherwise I'll hide them If I don’t wish to.
-> in simple means just hiding the some data in one class not sharing to other class … ex will be given when we move to access specifier topic.
()()Uses:()()
Just hiding our data by covering up (encapsulating) from others…
What is polymorphism?
->It means multiple possible states for a single property.
->polymorphism (Poly-many, orphism-form).
->Consider u ve one elder brother he is lecturer of ur class
U will act bro in ur home and student to ur bro in college… u r taking some forms (now its clear)
->The concept of polymorphism applies to both data types and functions.
()()Purpose:()()
Need to override or overload to change the function behaviors according to the application.
what is Inheritance?
even child knows inheritance
->Acquiring some of the common qualities from parents (for instance eyes like mother, a mole like father etc..) is called inheritance.
->In oop it can also be defined as acquiring some property from others is called inheritance. Based on the sources it differs.
()()Uses:()()
->Inheritance is intended to help reuse existing code with little or no modification.
->The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes, which are referred to as base classes.
the best book for c is deep c by ganesan have it
i will continue tomorrow
Like it on Facebook, +1 on Google, Tweet it or share this article on other bookmarking websites. | https://www.boddunan.com/programming/28-c-a-c/3600-programming-tutorial.html | CC-MAIN-2017-04 | refinedweb | 1,030 | 64.61 |
Adding SVG to a webpage
This topic introduces common ways to render SVG in your webpage and assumes that you have basic HTML and JavaScript knowledge.
- Introduction
- Ways to Render SVG
- Summary
- Related topics
Introduction
If you are just learning about Scalable Vector Graphics (SVG) and you want to experiment with it, one of your first questions might be how to add SVG to a basic webpage. If you take a look at a relatively basic webpage template, you can get a good idea of how to begin.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head> <meta content="text/html; charset=utf-8" http- <title>My First SVG Page</title> </head> <body> <p>SVG to be inserted here.</p> </body> </html>
There are a number of ways to add SVG to this basic template. The following example shows a straightforward way of doing so.
<?xml version="1.0" encoding="utf-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head> <!-- <meta content="text/html; charset=utf-8" http- --> <title> My First SVG Page</title> </head> <body> <svg xmlns="" version="1.1" width="200px" height="200px"> <rect x="0" y="0" width="100%" height="100%" fill="none" stroke="black"/> <circle cx="100" cy="100" r="50" style="stroke: black; fill: red;"/> </svg> </body> </html>
xhtmlfile extension. By changing the file extension from
htmlto
xhtml, you effectively transform the template from an HTML document to an XHTML document. This is why the
xmldeclaration (first line in the previous example) has been added and the
metaelement has been commented out. See the following list for more detailed information about the previous example.
<?xml version="1.0" encoding="utf-8" standalone="no"?>
The
xmldeclaration is a browser processing instruction that identifies the document as XML/XHMTL. The required version attribute specifies the version of the XML standard that the XML document conforms to. The optional
encodingattribute indicates to the browser how to interpret the associated bytes of the document based on a particular character set (the default encoding is UTF-8). The optional
standalone="no"attribute indicates that the Document Type Definition (DTD) that is specified in the
DOCTYPEelement will be used for more than just validation. Be aware that specifying
standalone=”no”is actually not necessary. The
standalone=”no”value is assumed when an external markup declaration (DTD in this case) is present.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
The
DOCTYPEdeclaration is not technically an HTML element. This declaration is an instruction to the web browser, which describes what version of markup language the page is written in. Be aware that the declaration refers to a DTD that specifies the rules for the markup language, so that browsers can render the content correctly. The DOCTYPE also enables you to use page validators. In this case, the XHTML 1.0 Transitional DTD enables all HTML elements and attributes, including presentational and deprecated elements (for example,
<font>). However, frames are not allowed and the markup must be written as well-formed XML.
<html xmlns="">
The
htmlelement indicates to the browser that this is an HTML document in the general sense, and specifically, an XHTML document as indicated by
DOCTYPE. The
xmlnsattribute specifies the XML namespace for the XHTML document. In general, developers should explicitly include the XHTML xmlns declaration when writing XHTML documents.
<head>
The
headsection of a webpage enables you to define page titles, provide search engine information, set page location, add style sheets, write scripts, and so on. (For example,
base,
link,
meta,
script, and
style).
<meta content="text/html; charset=utf-8" http-
The
metaelement provides metadata about the document. Metadata is information about the contents of the document (that is not displayed to the reader). This metadata can be used by the browser or other software such as search engines, document management systems, and so on. In the first template (with no
svgelement), the content attribute specifies that the page should first be served (from web server to client) by using an HTTP header called
Content-Typethat has a value of
text/html; charset=utf-8before the actual page content is delivered by the server. This process enables the browser to correctly render the incoming page data (text/html) by using the correct character encoding (charset=utf-8). In the second XHTML (SVG) sample, the
metaelement is commented out because specifying character encoding using the
metaelement is ignored in XML/XHML documents, and must be shifted to the
xmldeclaration. Developers can switch between using the
metaelement for HTML and the
xmldeclaration for XML/XHTML.
<title>
Generally, the
titleelement renders its associated text in the browser’s tab.
</head>
The closing element for
head.
<body>
The
bodyelement is the container for the content of the XHTML document that is displayed.
<svg xmlns="" version="1.1" width="200px" height="200px">
The
svgelement defines the SVG document fragment. The
xmlnsattribute defines the namespace for the SVG fragment. The
versionattribute indicates the SVG language version to which this document fragment conforms, and the
widthand
heightattributes define the size of the SVG viewport (a 200 x 200 pixel square, in this case).
<rect x="0" y="0" width="100%" height="100%" fill="none" stroke="black"/>
Relative to the SVG viewport, the SVG
rectelement draws a black rectangle starting at the upper-left corner of the viewport, or at point (0, 0), that has a maximum width and height. This positioning outlines the given SVG viewport.
<circle cx="100" cy="100" r="50" style="stroke: black; fill: red;"/>
Similarly, the SVG
circleelement draws a red circle that has a black border, whose radius is 50 pixels. The circle is centered in the middle of the 200 x 200 pixel SVG viewport.
</svg>
The closing element for
svg.
</body>
The closing element for
body.
</html>
The closing element for
html.
Ways to Render SVG
There are other methods you can use to render SVG as well. The following table summarizes these methods.
Examples of each of the above five methods are described in the following section.
Inline HTML5
The following example shows a basic inline HTML5 SVG template. The code example creates a circle in SVG markup and registers the click event. When the circle is clicked, the circle changes size.
<!DOCTYPE html> <html> <head> <meta http- <script> function doCircle(evt) { var theCircle = evt.target; var radius = theCircle.getAttribute("r"); if (radius == 50) { radius = 75; } else { radius = 50; } theCircle.setAttribute("r",radius); } </script> </head> <body> <svg width="300px" height="300px"> <text x="25" y="50" font-SVG Circle Element</text> <text x="25" y="275">Click the circle to change its size.</text> <circle cx="125" cy="150" r="50" fill="pink" stroke="green" stroke- </svg> </body> </html>
The
<!DOCTYPE html> element indicates to the browser that this is an HTML5 document. The
<meta http- element is used to force Windows Internet Explorer into IE9 Standards mode for correct rendering on intranet sites. Be aware that for HTML5, the
html element’s
xmlns="" attribute is not applicable.
htmlfile extension.
Inline XHTML
Because SVG is XML-based, you can add SVG to an XHTML document by using the correct namespaces, as indicated in the following basic inline XHTML template.
<?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head> <title>Manipulating the Radius of an SVG Circle</title> <script language="javascript" type="text/javascript"> <![CDATA[ var red_circle; // The object representing circle. var r; // The variable representing circle's radius. window.onload = function() { red_circle = document.getElementById('redCircle'); r = red_circle.getAttribute("r"); } function grow() { r = 2*r; red_circle.setAttribute("r",r); } function shrink() { r = r/2; red_circle.setAttribute("r",r); } ]]> </script> </head> <body> <svg width="200px" height="200px" version="1.1" xmlns="" xmlns: <circle id="redCircle" cx="100" cy="100" r="50" style="stroke: black; fill: red;" onmouseover="grow()" onmouseout="shrink()"/> <rect x="0" y="0" width="100%" height="100%" style="fill: none; stroke: black;"/> </svg> </body> </html>
This code example creates a 200 × 200 pixel viewport and draws a red, 50px radius circle that has a black border. If you move the mouse pointer over the rendered circle, the circle doubles its radius; if you move the mouse pointer off the rendered circle, the circle's current radius reduces by half. The rectangle element is used to outline the boundaries of the viewport.
xhtmlfile extension.
Inline XHTML works well but requires the
xhtml file extension and namespaces. Until the recent advent of HTML5, this was the best option.
Stand-Alone SVG
The original intention of SVG was to provide a vector graphic file format by using
the
svg file extension. The following example shows a basic stand-alone SVG template.
<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ""> <svg width="100%" height="100%" version="1.1" xmlns="" xmlns: <script language="javascript" type="text/javascript"> <![CDATA[ function doSomething(evt) { var myRect = evt.target; if (myRect.id != "redRect") { alert("Please click on the rectangle"); document.location.reload(); } var myWidth = myRect.getAttribute("width"); if (myWidth == 50) myRect.setAttribute("width", 100); else myRect.setAttribute("width", 50); } ]]> </script> <!-- Outline the SVG viewport. --> <rect x="0" y="0" width="100%" height="100%" style="fill: none; stroke: black; stroke-width: 5px;" /> <rect id="redRect" x="100" y="100" width="50" height="50" fill="red" stroke="blue" /> </svg>
This code example alternately expands and contracts the red rectangle with each interior click. If the click is outside the red rectangle, an alert appears and the page reloads.
As noted previously, the
standalone="no" attribute in the
xml element (the first line) of
the template indicates that the DTD that is specified in the
DOCTYPE element will be used
for more than just validation. You do not need to specify
standalone=”no” because this value is assumed when an external markup declaration
(DTD in this case) is present.
svgextension.
Embedded
The
iframe,
embed,
object, and
img elements and CSS
background-image style can be used, depending on the browser, to embed SVG into a webpage. Be aware that not all of these embedding methods may be available for a particular browser. The following example shows the basic SVG template, which uses the
object element.
<?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head> <title>Embedding SVG</title> </head> <body> <h1>Embedding SVG in an XHTML Document</h1> <p>Embedding the file <em>standAlone.svg</em> using the <strong>object</strong> element:</p> <object data="standAlone.svg" width="302px" height="302px" type="image/svg+xml"> <img src="standAlone.png" alt="PNG image of standAlone.svg" /> </object> </body> </html>
xhtmlfile extension. Also be aware that the embedded SVG file,
standAlone.svgin this case, must have a
svgfile extension.
Assuming the SVG file is not embedded via the
img element or as a CSS background, the embedded SVG file generally contains whatever programming it had, but embedding does not provide an easy way to have programmable interaction between the embedded SVG document and the embedding HTML document unless the embedded SVG file is from the same domain as the embedding page. This method is generally not recommended for programming SVG in a webpage but it's handy for easy insertion of an SVG file and could be useful, with respect to fallback, for earlier browsers, such as Internet Explorer 8, which does not natively support SVG.
Plug-in
The following list identifies a few reasons why the plug-in solution is not recommended:
- The primary SVG browser plug-in, Adobe SVG Viewer, is no longer supported by Adobe.
- Most modern browsers natively support SVG.
- Third-party plug-ins might introduce browser instability or may cease being supported by the plug-in provider.
Summary
The following tables summarizes the templates reviewed in this topic.
.svgfile extension. In order to request
.svgweb pages from IIS, you must add a "MIME Typing" mapping for
.svgto
image/svg+xml.
For browsers that support SVG and HTML5 natively, the best option is the Inline HTML5 method.
For browsers that do not fully support HTML5 but support SVG natively, use the Inline XHTML or Stand-Alone method, followed by the Embedded method, as applicable.
For browsers that do not support SVG natively, implementing appropriate fallback measures, such as rendering a static image of the SVG graphic, is suggested.
Use
<meta http- to enable SVG for an HTML Application (HTA). For more information, see Introduction to HTML Applications (HTAs).
Related topics | https://msdn.microsoft.com/en-us/library/gg589526 | CC-MAIN-2016-40 | refinedweb | 2,079 | 56.55 |
Goals:
By the end of this tutorial, you will have a starting point for writing unit tests for a web scraper. I also hope that this motivates the reader to learn more about test-driven development. This tutorial is less about teaching you how to do something. Instead, it suggests how to set up and think about your testing for web scrapping scripts.
Tools and prereqs:
The reader should know how to run pytests, if you don't, I suggest you read the first part of clean architecture for a primer listed in the resources section.
It will benefit the reader to have done at least one web scrape using Beautiful Soup before going over this tutorial.
Step 1
The example website we will be using is. This website is a service to practice web scraping.
The first step is to decide what data we will want to collect.
Luckily, the "Product information" section makes it an easy task. We will collect the fields: UPC, Product Type, Price (excl. tax), Tax, and Availability In stock.
Step 2
My first suggestion begins before we start writing any code. I think all of your cleaning code should be organized together and tested together. Therefore you should separate your cleaning code in a "clean.py" file.
touch clean.py
Step 3
With Test-Driven Development, you write your test before writing your program code. I like using a format similar to follow Ken Youens' format in "Tiny Python Project" (link below). He starts with testing that the file exists in the right location. He then separates each of the tests with a commented outline.
import os prg = './clean.py' # ------------------------------------------------- def test_exists(): """checks if the file exist""" assert os.path.isfile(prg)
You can run the test by typing this:
pytest -xv test.py
This test should pass, if it doesn't make sure the
clean.py is in the correct directory.
Step 4
For the next step, we will be going back to the Product Information section of the webpage. When storing our Price and tax data, we will want to keep them as float data. However, if we tried to get the text, the pound symbol would prevent python from converting it into a float number. This problem lends itself to our first test.
# ------------------------------------------------- def test_price(): """£51.77 -> 51.77 type float""" res = monetary('£51.77') assert res == float(51.77)`
Now when we run the test using:
pytest -xv test.py . We will see an error, which is a great thing.
I want to take the time to discuss this step a little more because this step is the main focus of the tutorial. There are much better TDD sources and excellent web scraping tutorials, but I don't always see where to start with TDD for your scrapes. Starting with how you want your data to look is a great way to get started with TDD and a great way to ensure your data is clean. As a data analyst, data engineer, or data scientist, there will most likely be several cleaning data steps. Web getting your data from the web; this can be your first step.
I know I got a bit wordy, but I would like to summarize these thoughts and the tutorial: write a test script to reflect what your data should look like and then write the code.
Step 5
Now we can write the code for this test. This code is how I chose to write the code; there can be more than one way. When I write code for small projects, I like to think of two advice pieces that I have read from real smart developers. First, get the code to pass the test and make sure it does what you are trying to get done. Second, is don't overcomplicate it with features you think you'll need in the future. Here is my code:
import re def monetary(value_field): """Returns a float for items that are values""" amount = re.sub('[^0-9.]', '', value_field) return float(amount)
Sure, I could have written it this way:
def monetary(value_field): """Returns a float for items that are values""" amount = value_field[1:] return float(amount)
and for this project, it would be fine. I used regrex, because any time I see characters, I think to myself, "just use regrex". However, it doesn't matter as long as you are getting the desired result.
Step 6:
Now it is time for you to do the same thing for writing a test and code that returns an integer for the availability column! You can see my complete code and "answer" at the link below under resources.
Conclusion
We went over a starting point to create Unit tests for a web scraper. Thank you for reading and please let me know if you have any questions our suggestions!
Quick side note
In my project, I save the data as a NamedTuple in a model file. There will be a link at the end of this article with more information about NamedTuples if you have not used one before.
Resources:
Clean Architectures:
Tiny Python Projects:
NamedTuple:
My code:
Discussion (0) | https://dev.to/albertulysses/unit-testing-your-web-scraper-1aha | CC-MAIN-2021-25 | refinedweb | 861 | 81.53 |
QR codes are everywhere these days: magazine advertisements, billboards, even TV commercials. Chances are you have a phone in your pocket that can read a QR code and decode the URL or message contained within. In this tutorial, you'll learn how to create a SWF that can reverse the process: create a QR code from a URL or message. Read on!
Final Result Preview
Let's take a look at the final app we will be working towards:
Step 1: Brief Overview
Using pre-made graphic elements we'll create good looking interface that will be powered by several ActionScript 3 classes.
The code will make good use of a QR Code Encoder class, created by Jean-Baptiste Pin.
Step 2: Flash Document Settings
Open Flash and create a 480 pixels wide, 480 pixels tall document. Set the Frame rate to 24fps.
Step 3: Interface
A colorful nice looking interface will be displayed, this involves multiple shapes, buttons and more.
Simple shapes were created using the Flash Drawing Tools so it won't be necessary to include their creation.
Step 4: Instance Names
The image above shows the Instance Names used in the MovieClips. The ones that start with a Capital Letter are Library Class Names and should not be on stage.
Step 5: TweenNano
We'll use a different tween engine from the default included in Flash, this will increase performace as well as being easier to use.
You can download TweenNano from its official website.
Step 6: QR Code Library
We'll make use of a fantastic QR Code Encoder library which can be downloaded from here. You can learn more about using external libraries in your code with this tutorial.
Editor's note: Use the SWC file, not the classes in the \org\ folder, for best results.
Step 7: Set Main Class
Add the class name to the Class field in the Publish section of the Properties panel to associate the FLA with the Main document class.
Step 8: Create a New ActionScript Class
Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder.
Step 9: Class Structure
Create your basic class structure to begin writing your code.
package { import flash.display.Sprite; public class Main extends Sprite { public function Main():void { // constructor code } } }
Step 10: Required Classes
These are the classes we'll need to import for our class to work, the
import directive makes externally defined classes and packages available to your code.
import flash.display.Sprite; import flash.events.MouseEvent; import org.qrcode.QRCode; import flash.display.Bitmap; import com.greensock.TweenNano; import com.greensock.easing.Expo;
Step 11: Variables
These are the variables we'll use, read the comments in the code to know more about them, some of their names are self explaining so there will be no comment there.
private var textView:TextView; private var smsView:SMSView = new SMSView(); private var emailView:EmailView = new EmailView(); private var linkView:LinkView = new LinkView(); private var lastView:Sprite; private var currentTarget:String; //current string to convert private var qrImg:Bitmap;
Step 12: Constructor
The constructor is a function that runs when an object is created from a class, this code is the first to execute when you make an instance of an object or runs using the Document Class.
It calls the necessary functions to start the app. Check those functions in the next steps.
public final function Main():void { addTextView(); addListeners(); }
Step 13: Add Text View
The first function executed by the constructor. It will instantiate the TextView and add it to the stage. This will be the default view that will be shown starting the application. It includes a call to remove the currently visible view (in case there's one) and also performs a Tween as a detail to the interface.
private final function addTextView():void { removeLastView(); textView = new TextView(); textView.x = stage.stageWidth * 0.5; textView.y = 110; addChild(textView); TweenNano.from(textView, 0.5, {y: textView.y - 10, alpha:0, ease:Expo}); lastView = textView; }
Step 14: SMS View
This code handles the SMSView position and animation. It is called when the SMS button tab is pressed.
private final function addSMSView():void { removeLastView(); smsView = new SMSView(); smsView.x = stage.stageWidth * 0.5; smsView.y = 150; addChild(smsView); TweenNano.from(smsView, 0.5, {y: smsView.y - 10, alpha:0, ease:Expo}); lastView = smsView; }
Step 15: Email View
The EmailView code. It will place and animate this view on the stage.
private final function addEmailView():void { removeLastView(); emailView = new EmailView(); emailView.x = stage.stageWidth * 0.5; emailView.y = 155; addChild(emailView); TweenNano.from(emailView, 0.5, {y: emailView.y - 10, alpha:0, ease:Expo}); lastView = emailView; }
Step 16: Link View
This is the final tab, it removes the last visible view and adds the LinkView to the stage.
private final function addLinkView():void { removeLastView(); linkView = new LinkView(); linkView.x = stage.stageWidth * 0.5; linkView.y = 110; addChild(linkView); TweenNano.from(linkView, 0.5, {y: linkView.y - 10, alpha:0, ease:Expo}); lastView = linkView; }
Step 17: Remove Last View
This function removes the currently visible view from the stage and frees it up for garbage collection.
private final function removeLastView():void { if(lastView != null) { removeChild(lastView); lastView = null; } }
Step 18: Add Listeners
The next code links the buttons to their corresponding functions. This will enable the tab based navigation.
private final function addListeners():void { abcBtn.addEventListener(MouseEvent.MOUSE_UP, indicatorHandler); smsBtn.addEventListener(MouseEvent.MOUSE_UP, indicatorHandler); emailBtn.addEventListener(MouseEvent.MOUSE_UP, indicatorHandler); linkBtn.addEventListener(MouseEvent.MOUSE_UP, indicatorHandler); refreshBtn.addEventListener(MouseEvent.MOUSE_UP, refreshCode); }
Step 19: Indicator Handler
The Indicator MovieClip is the little arrow that shows the active tab. This function places it in the correct position and calls the tab function.
private final function indicatorHandler(e:MouseEvent):void { indicator.x = e.target.x; switch(e.target.name) { case 'abcBtn': addTextView(); break; case 'smsBtn': addSMSView(); break; case 'emailBtn': addEmailView(); break; case 'linkBtn': addLinkView(); break; default: trace('Button Names Error'); } }
Step 20: Refresh QR Code
This function will run when the Refresh button is pressed, it determines the current string to convert and the QRObject
encode() method to generate a bitmap that is next added to the stage.
private final function refreshCode(e:MouseEvent):void { switch(lastView) { case textView: currentTarget = textView.textTF.text; break; case smsView: currentTarget = 'SMSTO:' + smsView.phoneTF.text + ':' + smsView.contentTF.text; break; case emailView: currentTarget = 'SMTP:' + emailView.toTF.text + ':' + emailView.subjectTF.text + ':' + emailView.bodyTF.text; break; case linkView: currentTarget = linkView.linkTF.text; if (currentTarget.indexOf('://') == -1) { currentTarget = 'http://' + currentTarget; //automatically add http:// to the front of links if required } break; default: trace('Target Error'); } if(qrImg != null) { removeChild(qrImg); qrImg = null; } var qrObj:QRCode = new QRCode(); qrObj.encode(currentTarget); qrImg = new Bitmap(qrObj.bitmapData); qrImg.x = stage.stageWidth * 0.5 - (qrImg.width * 0.5); qrImg.y = 300 - (qrImg.height * 0.5); addChild(qrImg); TweenNano.from(qrImg, 1, {alpha:0, ease:Expo}); }
Conclusion
Use this application to generate your custom QR Codes and remember to explore the source files.
I hope you liked this tutorial, thank you for reading!
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
| https://code.tutsplus.com/articles/create-a-qr-code-generator-in-flash-using-as3--active-10088 | CC-MAIN-2019-18 | refinedweb | 1,193 | 58.28 |
When I was working on mod_wsgi, but also in a previous job where I was working on web application performance monitoring tools, I was always after good sample Python web applications to test with. Unlike other programming languages for the web there weren’t many end user applications written in Python that you could quickly download and get running. Most of what existed out there were incomplete framework extensions which you still had to customise to get running for your own personal needs. Even if they did provide a way of starting up a skeletal application to at least see what they did, the steps to get them running were often quite complex.
One of the problems with deploying Python web applications you download are that they are often set up to be run in a very specific way with a particular hosting service or WSGI server. This fact meant you could end up spending quite a bit of time fiddling with it to get it all running in the environment you have. This made the exercise of trying to use a Python web application for testing quite frustrating at times. I can quite easily imagine that for users who might be trying to evaluate an Open Source framework extension to see if they could use it, that such difficulties in getting it running could be quite a turn off.
Where I am currently working at Red Hat as part of the OpenShift evangelist team, we are currently running a hackathon (ends 21st September) where the theme is health related applications. I have already seen that there are some Python developers out there participating in the hackathon, so I thought I might do a bit of a search around to see what I could find in the way of existing web applications or framework extensions out there for the Python programming language and test out deploying them using my warpdrive package. I actually wasn’t really expecting to find anything too interesting, but was pleasantly surprised.
One framework extension I found which I thought was quite interesting was called Opal. The Opal framework makes use of Django, along with toolkits for developing the front end such as Angular JS and Bootstrap. It was created by Open Health Care UK. The point of this blog post, as well as highlighting what looks like a quite interesting package out there that you can use, is to see how my warpdrive package stacks up when trying to deploy an arbitrary Python web application off the Internet.
Getting Opal running locally
First up is getting Opal running locally. For this Opal provides some good documentation and also a starter script to get you going. Installation and creation of an initial application I could test with was as simple as running:
pip install opal
opal startproject mynewapp
Once this was done to start up the starter application you run:
cd mynewapp
python manage.py runserver
From a browser you could then visit '' and even login to the admin interface using a pre created user account. The latter was possible as Opal has added hooks which are automatically triggered when ‘runserver’ is used, which will set up the database and create a super user account. They have therefore optimised things for the local developer experience when using the builtin Django development server.
What now though if you wanted to deploy Opal to a production environment? They do provide a ‘Procfile’ for Heroku, but don’t provide anything which really helps out if you want to deploy to another WSGI server such as Apache/mod_wsgi or uWSGI, in a container using a local Docker service, or other PaaS environments such as OpenShift.
It is making deployment of Python web applications easy across such different environments that my warpdrive project is targeting, so lets now look at using warpdrive to do this.
Preparing the project for warpdrive
With warpdrive already installed, the first thing we want to do is activate a new project using it. In the ‘mynewapp’ directory we run ‘warpdrive project opal’.
$ warpdrive project opal
Initializing warpdrive project 'opal'.
(warpdrive+opal) $
What this command will do is create us a new Python virtual environment just for this application and activate it. This will be an empty Python virtual environment, so next we need to install all the Python packages that the project requires.
When we originally create the project using the ‘opal startproject’ command this conveniently created for us a ‘requirements.txt’ file. This can be used with ‘pip’ to install all the packages, but we aren’t actually going to do that. This is because warpdrive also knows about ‘requirements.txt’ files and we can use it to install the required packages.
Rather than run ‘pip’ directly, we are therefore going to run ‘warpdrive build’ instead. This will not only ensure that any required Python packages are installed, but also ensures that any other framework specific build steps are also run. The output from running ‘warpdrive build’ starts out with:
-----> Installing dependencies with pip (requirements.txt)
Collecting cryptography==1.3.2 (from -r requirements.txt (line 2))
Using cached cryptography-1.3.2-cp27-none-macosx_10_6_intel.whl
Collecting Django==1.8.3 (from -r requirements.txt (line 3))
Using cached Django-1.8.3-py2.py3-none-any.whl
...
Obtaining opal from git+git://github.com/openhealthcare/opal.git@master#egg=opal (from -r requirements.txt (line 18))
Cloning git://github.com/openhealthcare/opal.git (to master) to /tmp/warpdrive-build.12067/opal
...Installing collected packages: pycparser, cffi, pyasn1, six, idna, ipaddress, enum34, cryptography, Django, coverage, dj-database-url, gunicorn, psycopg2, static3, dj-static, django-reversion, django-axes, ffs, MarkupSafe, jinja2, letter, requests, djangorestframework, django-appconf, django-compressor, meld3, supervisor, python-dateutil, pytz, billiard, anyjson, amqp, kombu, celery, django-celery, opal
Running setup.py develop for opal
Successfully installed Django-1.8.3 MarkupSafe-0.23 amqp-1.4.9 anyjson-0.3.3 billiard-3.3.0.23 celery-3.1.19 cffi-1.7.0 coverage-3.6 cryptography-1.3.2 dj-database-url-0.2.1 dj-static-0.0.6 django-appconf-1.0.2 django-axes-1.4.0 django-celery-3.1.17 django-compressor-1.5 django-reversion-1.8.7 djangorestframework-3.2.2 enum34-1.1.6 ffs-0.0.8.1 gunicorn-0.17.4 idna-2.1 ipaddress-1.0.16 jinja2-2.8 kombu-3.0.35 letter-0.4.1 meld3-1.0.2 opal psycopg2-2.5 pyasn1-0.1.9 pycparser-2.14 python-dateutil-2.4.2 pytz-2016.6.1 requests-2.7.0 six-1.10.0 static3-0.7.0 supervisor-3.0
Collecting mod_wsgi
Installing collected packages: mod-wsgi
Successfully installed mod-wsgi-4.5.3
One thing of note here is that ‘pip’ when run is actually trying to install Opal direct from the Git repository on GitHub. This is because the ‘requirements.txt’ file generated by ‘opal startproject’ contains:
-e git://github.com/openhealthcare/opal.git@master#egg=opal
As far as deploying to a production environment, pulling package code direct from a Git repository, and especially from head of the master branch isn’t necessarily the best idea. We instead want to ensure that we are always using a known specific version of the package which we have tested with. To remedy this, this time we will run ‘pip’ directly, but only to uninstall the version of ‘opal’ installed so it will not cause a problems when trying to reinstall it from PyPi.
pip uninstall opal
We now edit the ‘requirements.txt’ file and replace that line with:
opal==0.7.0
Worth highlighting is that this isn’t being done specially because of warpdrive. It is simply good practice to be using pinned versions of packages in a production environment so you know what you are getting. I can only imagine the ‘requirements.txt’ file is generated in this way as it makes the Opal developers job easy when testing themselves when they are working on it.
Having fixed that, we can rerun ‘warpdrive build’ and it will trigger ‘pip’ once more to ensure we have the packages we need installed, and since we removed the ‘opal’ package, it will now install the version we actually want.
Beyond installing any required Python packages, one other thing that warpdrive will do is that it will realise that the Django web framework is being used and will automatically trigger the Django ‘collectstatic’ command to collate together any static files used by the application. The next thing after package installation we therefore see in the output of ‘warpdrive build’ is:
-----> Collecting static files for Django
...
OSError: [Errno 2] No such file or directory: '/Users/graham/Projects/openshift3-opal/mynewapp/mynewapp/static'
Unfortunately this fails though. The reason it fails is actually because the Django settings module for the generated Opal project contains:
# Additional locations of static files
STATICFILES_DIRS = (
os.path.join(PROJECT_PATH, 'static'),
)
With this setting, when ‘collectstatic’ is run, it expects that directory to actually exist and if it doesn’t it will fail.
This is easily fixed by creating the directory:
mkdir mynewapp/static
The directory should though have been created automatically by the ‘opal startproject’ command. That it doesn’t has already been addressed for version 0.7.1 of Opal.
After fixing this, ‘warpdrive build’ then completes successfully. It may have looked a bit messy, but that was only because we had to correct the two things related to the project that ‘opal startproject’ created for us. We could simply have left it using the ‘opal’ project from the Git repository, but felt it better to clarify what is best practice in this case.
Starting up the application
When we first started up the application we used Django’s builtin development server. This server should not though be used in a production system. Instead of the development server you should use a production grade WSGI server such as Apache/mod_wsgi, gunicorn, uWSGI or Waitress. For most use cases any of these WSGI servers will be suitable, but depending on your specific requirements you may find one more appropriate.
Setting up a project for one WSGI server even can still be a challenge in itself for many people. Trying to set up a project for more than one WSGI server so you can compare them only replicates the pain. Usually people will totally muck up the configuration of one or the other and get a totally incorrect impression of which one may actually be better.
In addition to aiming to simplify the build process, another aim of warpdrive is therefore to make it much easier to run up your WSGI application, no matter what WSGI server you want to use. This means you can get started much more quickly, but also give you the flexibility to swap between different WSGI servers.
That said, having prepared our application for warpdrive, to actually run it up and have it start accepting web requests, all we now need to do is run ‘warpdrive start’.
-----> Configuring for deployment mode: of 'auto'
-----> Default WSGI server type is 'mod_wsgi'
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin/ /Users/graham/Projects/openshift3-opal/mynewapp/mynewapp/assets/'
Server URL :
Server Root : /tmp/mod_wsgi-localhost:8080:502
Server Conf : /tmp/mod_wsgi-localhost:8080:502_AU.UTF-8
[Mon Aug 01 14:20:13.092722 2016] [mpm_prefork:notice] [pid 13220] AH00163: Apache/2.4.18 (Unix) mod_wsgi/4.5.3 Python/2.7.10 configured -- resuming normal operations
[Mon Aug 01 14:20:13.092995 2016] [core:notice] [pid 13220] AH00094: Command line: 'httpd (mod_wsgi-express) -f /tmp/mod_wsgi-localhost:8080:502/httpd.conf -E /dev/stderr -D FOREGROUND'
And that is it. Our Opal application is now running.
You may be thinking at this point that using ‘runserver’ is just as easy, so what is the point, but if you look closely at the output of ‘warpdrive start’, you will see that the Django development server is not being used. Instead Apache/mod_wsgi is being used. That is, a production grade WSGI server. Not only that, you didn’t have to configure anything, all the set up and running of Apache and mod_wsgi was done for you.
Using a different WSGI server such as uWSGI is not any harder. In the case of uWSGI, all you would need to do is create the file ‘.warpdrive/server_type’ and place in it ‘uwsgi’, to override the default of using Apache/mod_wsgi. Then run ‘warpdrive build’ and once again ‘warpdrive start’ and you will instead be running with uWSGI.
-----> Configuring for deployment mode: of 'auto'
-----> Default WSGI server type is 'uwsgi'
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)-----> Running server script start-uwsgi
-----> Executing server command 'uwsgi --master --http-socket :8080 --enable-threads --threads=5 --thunder-lock --single-interpreter --die-on-term --module mynewapp.wsgi --callable application --static-map /assets/=/Users/graham/Projects/openshift3-opal/mynewapp/mynewapp/assets/'
[uwsgi-static] added mapping for /assets/ => /Users/graham/Projects/openshift3-opal/mynewapp/mynewapp/assets/
*** Starting uWSGI 2.0.13.1 (64bit) on [Mon Aug 1 14:27:02 2016] ***
...
In all cases, no matter which WSGI server you are using, warpdrive will worry about ensuring the minimum sane set of options are provided to the WSGI server as well as any required for the specific WSGI application. In this case warpdrive even handled the task of making sure the WSGI server knew how to host the static files the application needs.
Initialising an application database
Our Opal application is again running and we can access it via the browser from ''. Do so though and we encounter a new problem though.
Exception Type: OperationalError
Exception Value: no such table: axes_accessattempt
This gets back to that magic that was being done when ‘runserver’ was being used. Specifically, the ‘runserver’ command had been set up to also automatically ensure that the database being used was initialised and that an initial account created.
Doing that for a development system is fine, but you would have to be careful about automating that in a production system. For starters, although in a development system you can use a file based database such as SQLite, in production you are more likely going to be using a database such as MySQL or PostgreSQL. These will be handling your real data and so you have to be much more careful in what you do with those databases.
When using Django, which Opal is based on, it provides two management commands for initialising a database and creating accounts. These are ‘migrate’ and ‘createsuperuser’. The ‘migrate’ command actually serves two purposes. It can be used to initialise the initial database, but also perform database migrations when the database model used by the application code changes.
These are slightly magic steps which you need to know about how Django works to know how to run. When they were automatically triggered by ‘runserver’ you didn’t have to know how to run them as that knowledge was coded into the scripts triggered by ‘runserver’.
As codifying such steps is beneficial from the stand point of ensuring that such steps are captured and always done the same way, warpdrive provides a mechanism called action hooks for recording what these steps are. You can then get warpdrive to run them for you and you don’t have to know the details. You can embed in the action as much magic as you need to, including steps like ensuring that your database is actually running before attempting anything, or allowing details of accounts to create to be supplied through environment variables or configuration files.
As an example, lets create our first action hook. This we will save away in the file ‘.warpdrive/action_hooks/setup’.
#!/bin/bashecho " -----> Running Django database migration"python manage.py migrateif [ x"$DJANGO_ADMIN_USERNAME" != x"" ]; then
echo " -----> Creating predefined Django super user"
(cat - | python manage.py shell) << !
from django.contrib.auth.models import User;
User.objects.create_superuser('$DJANGO_ADMIN_USERNAME',
'$DJANGO_ADMIN_EMAIL',
'$DJANGO_ADMIN_PASSWORD')
!
else
if (tty > /dev/null 2>&1); then
echo " -----> Running Django super user creation"
python manage.py createsuperuser
fi
fi
This captures the steps we need to initialise the database and create an initial account. For the account creation, we can either supply the details via environment variables, or if we are running in an interactive shell, it will prompt us. Having created this action hook we can now run ‘warpdrive setup’.
-----> Running .warpdrive/action_hooks/setup
-----> Running Django database migration
Operations to perform:
Synchronize unmigrated apps: search, staticfiles, axes, messages, compressor, rest_framework
Apply all migrations: sessions, admin, opal, sites, auth, reversion, contenttypes, mynewapp
Synchronizing apps without migrations:
Creating tables...
Creating table axes_accessattempt
Creating table axes_accesslog
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
...
Applying sites.0001_initial... OK
-----> Running Django super user creation
Username (leave blank to use 'graham'):
Password (again):
Superuser created successfully.
Running ‘warpdrive start’ once again we find the application is now all working fine and we can log in with the account we created.
The contents of the ‘setup’ script is typical here of what is required for database initialisation when using Django. The other set of actions we want to capture for Django is what needs to be done when migrating the database after database model changes. These we can capture in the file ‘.warpdrive/action_hooks/migrate’.
#!/bin/bashecho " -----> Running Django database migration"python manage.py migrate
Why it is better to capture these commands as action hooks and have warpdrive execute them for you, is that the commands are now a part of your application code. You don’t need to go look up some documentation to remember what the steps are. All you need to remember is the commands ‘warpdrive setup’ and ‘warpdrive migrate’.
Another important reason is that if there are any special environment variables that need to be set to replicate the actual environment when your web application is run, warpdrive will also worry about setting those as well. This means you wouldn’t need to remember to set some special value for the ‘DJANGO_SETTINGS_MODULE' environment variable in order to run the Django management commands directly. The warpdrive command will know what is required and set it up for you based on what you have captured about that in your application code.
Moving to a production environment
Using ‘warpdrive’ in our local environment has allowed us to more easily use a production grade WSGI server during development. Using the same WSGI server as we will use in production means we are more likely to pick up problems which will not show up using the development server.
The action hooks feature of warpdrive has also resulted us in capturing those important steps we need to run to initialise any database and later perform database migrations when we make changes to our database model.
That is a good start, but what now if we want to run our Opal application in a production environment?
The first example of how we might want to do that is to use Docker. For that though we first need too create a Docker image which contains our application along with any WSGI server and configuration needed to startup the application.
This step is where people often waste quite a lot of time. Developers can’t resist new toys to play with and so they feel it is imperative that they learn everything about this new Docker tool, throwing away any wisdom they may have accumulated about best practices over time and start from scratch, building up their own special Docker image piece by piece.
More often than not this results in a poorly constructed Docker image that doesn’t follow best practices and which can well be insecure, running as root and requiring it be run in a way that could easily lead to being able to break into your wider systems if someone can compromise your web application.
With warpdrive there is a much better way of moving to Docker. That is to have warpdrive build the Docker image for you. You don’t need to know anything about creating Docker images as warpdrive will build up the image ensuring that best practices are being used.
To package our Opal application up into a Docker image, all we need to do is run the ‘warpdrive image’ command.
(warpdrive+opal) $ warpdrive image opal
I0801 15:35:29.321041 14900 install.go:251] Using "assemble" installed from "image:///opt/app-root/s2i/bin/assemble"
I0801 15:35:29.321223 14900 install.go:251] Using "run" installed from "image:///opt/app-root/s2i/bin/run"
I0801 15:35:29.321280 14900 install.go:251] Using "save-artifacts" installed from "image:///opt/app-root/s2i/bin/save-artifacts"
---> Installing application source
---> Building application from source
-----> Installing dependencies with pip (requirements.txt)
Collecting cryptography==1.3.2 (from -r requirements.txt (line 2))
Downloading cryptography-1.3.2.tar.gz (383kB)
Collecting Django==1.8.3 (from -r requirements.txt (line 3))
Downloading Django-1.8.3-py2.py3-none-any.whl (6.2MB)
...
-----> Collecting static files for Django
78 static files copied to '/opt/app-root/src/mynewapp/assets', 465 unmodified.
---> Fix permissions on application source
This should look familiar to you as in building the Docker image it is using the same ‘warpdrive build’ command that you used in your local environment. This is being done within a Docker base image which has already been set up with Python and warpdrive.
By using the same tooling, in the form of warpdrive, in your local environment as well as in constructing the Docker image, you have a better guarantee that things are being set up in the same way and will also run in the same way. This removes the disparity that usually exists between working in a local environment and what you have in your production environment.
The final result of that ‘warpdrive image’ command is that you now have a Docker image named ‘opal’ which we can be run using ‘docker run’.
(warpdrive+opal) $ docker run --rm -p 8080:8080 opal
---> Executing the start up script
-----> Configuring for deployment mode: of 'auto'
-----> Default WSGI server type is 'mod_wsgi'
Python 2.7.12 (default, Jul 29 2016, 00:52:26)
[GCC 4.9.2] on linux2/ /opt/app-root/src/mynewapp/assets/'
Server URL :
Server Root : /tmp/mod_wsgi-localhost:8080:1001
Server Conf : /tmp/mod_wsgi-localhost:8080:1001_US.UTF-8
[Mon Aug 01 05:49:45.774485 2016] [mpm_event:notice] [pid 20:tid 140425572333312] AH00489: Apache/2.4.23 (Unix) mod_wsgi/4.5.3 Python/2.7.12 configured -- resuming normal operations
[Mon Aug 01 05:49:45.774622 2016] [core:notice] [pid 20:tid 140425572333312] AH00094: Command line: 'httpd (mod_wsgi-express) -f /tmp/mod_wsgi-localhost:8080:1001/httpd.conf -E /dev/stderr -D MOD_WSGI_MPM_ENABLE_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_WORKER_MODULE -D MOD_WSGI_MPM_EXISTS_PREFORK_MODULE -D FOREGROUND'
Like with how ‘warpdrive build’ was used in constructing the Docker image, the ‘warpdrive start’ command is also used in the final container when run.
We are still only using the file system database SQLite, which will not survive the life of the container, at this point, and we also need to initialise that database, but we can again use the ‘warpdrive setup’ command.
$ docker exec -it berserk_galileo warpdrive setup
-----> Running .warpdrive/action_hooks/setup
-----> Running Django database migration
Operations to perform:
Synchronize unmigrated apps: compressor, staticfiles, search, messages, rest_framework, axes
Apply all migrations: sessions, contenttypes, admin, mynewapp, sites, reversion, auth, opal
Synchronizing apps without migrations:
Creating tables...
Creating table axes_accessattempt
Creating table axes_accesslog
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
...
-----> Running Django super user creation
Username (leave blank to use 'default'): graham
Password (again):
Superuser created successfully.
This is where the benefit of having captured all those steps to initialise the database in an action hook comes into play. You only need to know the one command and not all the individual commands.
Making an application production ready
As you can see using warpdrive can certainly help to simplify getting a Python web application running and getting it into production using a container runtime such as Docker. Part of the benefits of using warpdrive are that it handles the WSGI server for you, but also features like action hooks, which help to ensure you capture important key steps around how to setup your application.
There is still more to getting an application production ready than just this though. Especially when using containers, because the running container is ephemeral and so any local data is lost when the container stops, it is important to use an external database or persistent storage. Work also needs to be done around how you configure your application as well as log information from it.
In followup posts I will start to delve into these issues and how warpdrive can help you configure your application for the target environment. I will also go into detail about how warpdrive can be used with PaaS offerings such as OpenShift.
8 comments:
Looks like the next Opal version will also switch away from the generated requirements.txt file installing opal package from the Git repository according to
Hi Graham,
Thanks for your post, and for the things it nudged us to fix and think about !
Deployment in settings other than the ones we routinely use at Open Health Care isn't something we've spent a lot of time with thus far in Opal's development. We often deploy to heroku, ec2 and some private infrastructure owned by individual hospitals with a mixture of ansible and fabric automation.
The hooks for e.g. running migrations or creating users are there to be nice for development - they certainly aren't intended to be used in production deployments!
Thanks to this post, I've been taking a look at warpdrive and docker - unfortunately I'm struggling to get the Docker image to build (I think I may have run into this issue upstream with s2i: ) but we'll take another look and see if we can get through those and hopefully get one of our real world applications dockerised and running on something like OpenShift.
In the meantime do let us know if you have any other feedback or thoughts on the project.
Brief point of order - those extra hooks on top of Django's standard procedure, like creating users and running migrations are actually run at the 'opal startproject' stage rather than being triggered by runserver.
My mistake over where database setup was done then. I thought I had removed the SQLite database and it had all come back. I may have run my warpdrive stuff in between though and it had recreated it.
As to S2I issue, I thought I had fixed the place in my S2I wrappers for warpdrive where that problem came up. So curious as to exactly what you are trying to do and with what. Might be easier to try and drop me an email direct about it or use the mod_wsgi mailing list as place for discussion.
Okay, I probably haven't done anything to address that s2i issue. Was getting it confused with another issue which I had done something for. Has been a busy couple of weeks because of travelling so had forgotten about the /bin/env issue.
Should have added the solution, which is to use s2i version 1.0.9 for now. My other choices are to hope for a proper fix of some sort, or create a symlink from /bin/env to /usr/bin/env in my Debian based images.
I have updated my Docker images with the /bin/env workaround now and so the 'warpdrive image' command should work fine.
Hi Dumpleton, sorry to contact you from here.
I have a django app deployed in AWS EB using autoscaling. This app uses Django Rest with Token Authentication. In order for this to work, I have to add the following lines in etc/httpd/conf.d/wsgi.conf file:
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
WSGIPassAuthorization On
The problem is: when AWS do an autoscale or ElasticBeanstalk environment upgrade, the wsgi.conf file is updated and the custom settings are deleted.
How can I avoid that?
Thanks in advance
@Ronaldo If you need help, the mod_wsgi documentation explains how to get it. See | http://blog.dscpl.com.au/2016/08/testing-out-deployment-of-python-based.html | CC-MAIN-2016-44 | refinedweb | 4,789 | 53.61 |
Goal
This tutorial guides you through the process of creating a sample application to perform CRUD operations on entities. These entities are stored and retrieved using the DataStore APIs from datastore defined by GAE.
For this exercise we will build a sample product catalog with two entities: Product and Item. The application provides UI to perform all the CRUD operations on the entities.
Following actions will be covered in this exercise:
- Create entities of type product, item
- List entity details
- Edit entity details
- Delete entity
Time for completion
Approximately 30 minutes.
Prerequisites
Before you begin this tutorial, you should be familiar with:
- Web application basics and deployment process
- Servlet basics
- Knowledge on XML-HTTP request
- Working with Eclipse IDE
Index
This tutorial is organized into the following sections:
- Code lab overview
- Setup: Import Code Lab Exercise 1
- Working with the exercise
- Run the Application
- Admin Console
- Deploy your application on GAE
- Summary
Code lab overview
- Code lab exercise is a web application template. The idea of the template based sample is to get hands-on experience with Google App Engine concepts. This exercise will cover all the steps required to create, deploy and monitor application on GAE environment.
The picture shows a solution overview. Goal of this exercise is to demonstrate the GoogleDataStore service API for persisting data.
In this exercise we will create the Product and Item entities, store and retrieve them. The datastore is the service provided by the App Engine. UI is built using HTML and javascript and data from the application is sent to browser in JSON format.
The use of memcache is demonstrated in the next exercise.
Setup : Import Code Lab Exercise 1
- Import the source code from the downloaded folder CodeLabEx1-starter as follows. Select File > Import from Eclipse IDE and select CodeLabEx1-starter folder.
Working with the exercise
The App Engine provides a robust and scalable Datastore for storing, searching and retrieving data. The App Engine datastore saves data objects as entities. An entity has one or more properties, named values of one of several supported data types for instance a string, an integer, or even a reference to another entity.
About Entity
An entity is an object representation of a datastore row. Unlike a row in a relational database, there are no predefined columns. There are no tables corresponding to types of data.
Entities don’t have columns – they have properties. A property represents a field of your entity. For instance, a person entity would have a kind of person, a key corresponding to a unique identifier corresponding to their name. The Kind of the entity is stored as part of the entity key. Entity Key is the primary way by which entities are fetched, even when the queries are issued. It’s similar to a primary key in an RDBMS. The key encodes your application ID, your entity’s kind, any parent entities and other metadata. The entity ID can also be a string that can be provided by the application.
This exercise shows how to create and retrieve entries to and from a data store. Each entity also has a key that uniquely identifies the entity. The simplest way is to have the Kind and Entity ID provided by the datastore. Kind indexes the entity and helps in querying the datastore efficiently.
Getting the Handle to DataStoreService
Take a look at the
com.google.appengine.codelab.Util class. The Util class has all the methods to store and retrieve entities from the datastore. It is wrapper for DatastoreService provided by the App Engine api.
Edit the Util class as follows. Locate the following line of code in the Util class.
private static DatastoreService datastore = null;
Replace the above line with the code below.
private static DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
- The
getDatastoreService()method of DatastoreServiceFactory returns DataStoreService that an application can use. The DatastoreService has
put(),
get()and
delete()methods. There is no need to worry about opening or closing service.
persistEntity()method saves the entity using the datastore service
put()API.
deleteEntity()method deletes the entiry using the datastore service
delete()API.
findEntity()method searches the datastore given a key usign the datastore service
find()API.
listEntities()methods allows to search by adding filters through Query class. Executes the query using prepare. Prepare also returns an iterator.
writeJSON()method is an utility method to send back the servlet response as JSON to the browser.
Creating OR Updating Item Entity
The code demonstrates creation of entities.
An entity can be created with an app-assigned key name (in this case, name) string or a system-assigned numeric ID as its identifier to create the object. To set a key name, provide it as the second argument to the Entity constructor. Simply omit the argument, to indicate that the datastore should assign a unique numeric ID automatically.
Entity does not contain setKey() or setKind() methods. This is because an entity’s key is immutable. Once an Entity has a key, it can never be changed.
Locate the
createOrUpdateItem()method in com.google.appengine.codelab.Item and insert the following lines of code.
Make sure to return item instead of null.
Entity product = Product.getProduct(productName); Entity item = getSingleItem(itemName); if(item == null){ item = new Entity("Item",product.getKey()); item.setProperty("name", itemName); item.setProperty("product", productName); item.setProperty("price", price); } else{ if (price != null && !"".equals(price)) { item.setProperty("price", price); } } Util.persistEntity(item); return item;
util.persistEntity()invokes the DatastoreService’s
put()to persist the Entity.
The product’s name is used as key. The same key is used to retrieve the product later.
Deleting Item Entity
An Entity can be deleted using
deleteItem()method in Item class. Add the below code to
deleteItem()method.
Entity entity = getSingleItem(itemKey); if(entity != null){ Util.deleteEntity(entity.getKey()); return("Item deleted successfully."); } else return("Item not found");
Util.deleteEntity()invokes the DatastoreService’s
delete()to delete the Entity.
Finding Item Entity
To search an entity, use
findEntity()method of
Util.java. Add the below code to
getSingleItem()method of Item class.
Ensure the found Entity is returned.
Query query = new Query("Item"); query.addFilter("name", FilterOperator.EQUAL, itemName); List<Entity> results = Util.getDatastoreServiceInstance().prepare(query).asList(FetchOptions.Builder.withDefaults()); if (!results.isEmpty()) { return (Entity)results.remove(0); } return null;
Run the Application
Refer Appendix A
- Once the application is deployed locally, open a browser and access the following URL
The welcome screen is shown below.
- Click on “Add” button from top panel. Make sure you are on Product tab.Fill in the create form and click on “Save” button
- On saving the product, the product list view appears
- Click “Add” button from the top panel. Make sure you are on Create Item tab.Fill the form, select the product type and then click on “Save” button.
- On saving the Item, the Item list view appears
- To update an item, Click on “Edit” which shows the below screen.
- To verify the entity creation, check for newly created item in the item listing.In next section, we can see the admin console and verify the data entities created.
Admin Console
- Login to ‘Admin Console’ to verify the entity present in the data store.Admin console can be opened on development machine using
Click on DataStore Viewer –> Select Item from Entity Kind list and click List Entities to view the product created.
Deploy your application to GAE
- Refer Appendix B
Summary
- Congratulations! You’ve completed the code lab exercise.You can also see the solution to the exercise in folder CodeLabEx1 folder. | http://jesidea.com/pakdb/gae-tutorial-code-lab-exercise-1-working-with-entities/ | CC-MAIN-2018-09 | refinedweb | 1,255 | 50.84 |
ECAD and Architecture Practical Classes
Ring based request/response message router
Introduction
The final design will consist of the Nios-II sending off individual points to be calculated by a processor-farm-on-a-programmable-chip of TTCs. In FPGA design, particularly when trying to exploit parallelism by replicating a single component several times, resource usage can become a critical. Attaching a memory mapped master to many memory mapped slaves will introduce lots of multiplexing logic.
For example, for a master to read data from 4 different memory mapped slaves, each with 4 words the multiplexing for the response may look something like:
|\ readdata_0[0:31] -| \ | | | |----------\ | | \ |\ readdata_1[0:31] -| / \------| \ |/| | | |addr[3] | |---readdata[0:31] |\ | | readdata_2[0:31] -| \ /------| / | | / |/| | |----------/ |addr[2] | | readdata_3[0:31] -| / |/| |addr[3]
Note the following:
- There is corresponding demultiplexing on the request side;
- Each multiplexer must be replicated 32 times, once for each bit in the word;
Rather than using a tree structure to route messages, we will use ring structure. This will ensure the per processor resource usage of the TTC in the final design is closer to its individual, isolated cost. The primary disadvantage of this routing structure is that it introduces latency (O(n) as opposed to O(lg(n))), however, this application is mostly throughput bound, at least at the generation speeds aimed for here.
Ring
We have created some SystemVerilog which instantiates up to 64 TTCs and connects their input and output ports in a ring using Avalon Streaming interfaces. These interfaces include a channel number which is used to stear data to TTCs and to identify which TTC produced data.
Download:
- ring_ttc.sv - the SystemVerilog describing the ring network
- ring_ttc_hw.tcl - a TCL file generated by Qys which contains the parameters needed to connect it to the system.
Take a look at ring_ttc.sv. It consists of three modules:
- ring_switch which instantiates one TTC and wraps it in a simple ring switch. There is one Avalon input stream and one Avalon output stream coming in and out of this module. Data coming in has its channel number inspected and if it is detined for this node it is fowarded to the TTC otherwise it is sent to the output port. Data from the TTC is sent to the output port with the corresponding channel number added. Note that the names of the inputs and output might look rather odd but they correspond to the default names that Qsys expects which makes importing the module easier.
- ring_ttc is the toplevel module. It too has single input and output Avalon Streaming interfaces. Inside you will see a generate block containing a for loop which instantiates num_ttc copies of the ring_switch, i.e. num_ttc TTCs.
- TestRing which can be used to test the system in simulation.
If you open up Qsys (or hit "Refresh" if Qsys is already open) then the new ring_ttc component should appear.
Making a new Qsys component (this can be skipped)
Since we provided you the ring_ttc_hw.tcl file, you do not need to do this step. But if you are interested in seeing how to import a component into Qsys and generate the TCL file, here goes...
Open Qsys and click File | New component.... Click the HDL Files then click the Add... button and select ring_ttc.sv. Make sure ring_ttc.sv is selected as Top and that ring_ttc is selected as the Top Level Module:.
Under the Interfaces tab, scroll down to in (Avalon Streaming Sink) and set its Associated Reset: to reset, the number of Data bits per symbol to 32 and the Maximum channel to 255. Do the same thing for out (Avalon Streaming Source). Click Finish... and answer Yes, Save when asked (this will generate the TCL file).
When you come to add ring_ttc to your project tou'll notice at this point that if you refresh the system by pressing F5, a new error appears regarding TOP_LEVEL_MODULE. This is a bug in Qsys. To fix it, open ring_hw.tcl, delete the line set_module_property STATIC_TOP_LEVEL_MODULE_NAME "", save it and refresh your Qsys system by pressing F5.
Add memory-mapped FIFOs
We're going to use memory mapped FIFOs to talk to the ring of TTCs. You can find this component under Component Library | Memories and Memory Controllers | On-Chip | On-Chip FIFO Memory. We need to add two of these, one with a memory mapped write port and a streaming read port and the other a mirror image (i.e. a streaming write port and a memory mapped read port):
- Memory mapped writer:
- Tick singleResetMode
- Set the Depth to 128, tick Allow backpressure, select Clock setting: Dual clock mode
- Under Status port tick Create status interface for input and untick the others
- Under Input select AVALONMM_WRITE
- Under Output select AVALONST_SOURCE
- Under Avalon-ST port settings select Bits per symbol: 32, Symbols per beat: 1, Error width: 8, Channel width: 8 and untick Enable packet data
- Memory mapped reader:
- Tick singleResetMode
- Set the Depth to 64, tick Allow backpressure, select Clock setting: Dual clock mode
- Under Status port tick Create status interface for output (note: output this time, not input) and untick the others
- Under Input select AVALONST_SINK
- Under Output select AVALONMM_READ
- Under Avalon-ST port settings select Bits per symbol: 32, Symbols per beat: 1, Error width: 8, Channel width: 8 and untick Enable packet data
In the System Contents window, select the first FIFO, hit Ctrl-R and change its name to fifo_write. Set the second FIFO's name to fifo_read. Connect fifo_write,out to fifo_read,in. Connect fifo_write,clk_in and fifo_read,clk_out to the sys_clk and their other clocks to video_clk (you'll see why when we connect ring_ttc). Connect the memory mapped interfaces to the data interface on the NIOS.
Testing memory mapped FIFOs
Test the system you've built by generating the system in Qsys and then synthesising it in Quartus. You will then need to write some C code for the Nios to exercise the FIFOs using the altera_avalon_fifo_util.h library in the board support package. The following example you could add to your C code to test the ring out by writing values on channels 20,21,22. If there are no TTCs on these channels then the data will be routed around the ring without going to a TTC and will be sent back to the NIOS. Use this code as a basis of the code you will need to write to communicate with the TTCs.
#include <stdio.h> #include <system.h> #include <io.h> #include "altera_avalon_fifo_util.h" void test_fifo(void) { int j; puts("Starting test_fifo\n"); // initialise fifo_write altera_avalon_fifo_init(FIFO_WRITE_IN_CSR_BASE, 0, // disable interrupts, 2, // almost empty level FIFO_WRITE_IN_FIFO_DEPTH-2); // almost full level // initialise fifo_read altera_avalon_fifo_init(FIFO_READ_OUT_CSR_BASE, 0, // disable interrupts, 2, // almost empty level FIFO_READ_OUT_FIFO_DEPTH-2); // almost full level // write 10 values to channels 20, 21 and 22 // N.B. if there are no TTCs on these channels then data from the NIOS // will be routed around the ring and back to the NIOS without being modified. for(j=0; j<10; j++) { if(altera_avalon_fifo_write_other_info(FIFO_WRITE_IN_BASE, FIFO_WRITE_IN_CSR_BASE, (20 + (j % 3))<<8) != ALTERA_AVALON_FIFO_OK) printf("Failed to write channel number when j=%d\n",j); if(altera_avalon_fifo_write_fifo(FIFO_WRITE_IN_BASE, FIFO_WRITE_IN_CSR_BASE, j) != ALTERA_AVALON_FIFO_OK) printf("FAILED to write %1d since FIFO is full\n",j); } // read back data and channel information from the FIFOs for(j=0; (altera_avalon_fifo_read_level(FIFO_READ_OUT_CSR_BASE)>0); j++) { int data = altera_avalon_fifo_read_fifo(FIFO_READ_OUT_BASE,FIFO_READ_OUT_CSR_BASE); int status = altera_avalon_fifo_read_other_info(FIFO_READ_OUT_BASE); int chan = (status>>8) & 0xff; printf("Read back from FIFO: %1d chan: %1d\n",data,chan); } }
Add a ring of TTCs
There is a minor bug here - Qsys doesn't like the debug code in ttc.sv and for some reason we didn't pick this up in testing. The ttc.sv has been updated to add some:
`ifdef MODEL_TECH
and
`endif
statements around the simulation code so that Qsys ignores it. We recommend you add these to your version of ttc.sv, specifically around the module DisplayTraces (definition and use).
Double click ring_ttc from the Component Library (or select and hit the Add... button). This will open up a window containing parameters for the TTC. Enter 16 for the num_ttc and the name of your fractal machine code MIF file for the progpath_mif. The progpath_rmb should be greyed out and is not needed (it is only used by the simulator). Then click Finish. Note that you should be able to add up to 64 TTCs but the more you add the more time Quartus will spend doing place & route. 16 should be sufficient to meet the ticking criteria.
Since this version of the TTC is unpipelined, it has long chains of combinational logic which have pushed its Fmax almost down to 40Mhz, therefore it will be clocked according to video_clk. Connect the output stream from fifo_write to the input of the ring_ttc. Connect the output of the ring_ttc to input stream of fifo_read. Qsys will then complain that the timing on the streams doesn't match since the ring_ttc has a zero read latency and the FIFOs have a one cycle read latency. This is easily fixed using menu option System | Insert Avalon-ST Adapters.
Generate the system in Qsys and synthesize in Quartus (this will take quite a bit of time). Since you've already tested one TTC running your fractal code in simulation, and we're already tested the ring_ttc, there is a reasonable chance that you'll only need to build the hardware once. Whilst you're waiting for the hardware to build, get on with the software!
Modifying the Nios-II program
The next and final task is to modify mandelbrot.c to make use of the 16 TTCs running Mandelbrot accelerators. Make use of the test_fifo code (above) as a template to initialise the FIFOs and then write and read data to/from the TTCs.
Benchmark it
Once you've successfully run your program, you should notice an approximately x10 speedup over the Nios-II only implementation running at -O3. The ticking criteria is to get the Nios-II + TTCs to render a full screen mandelbrot with a maximum of 255 iterations per pixel in under 10 seconds. We'll have a competition to see if people can do much better than this. | http://www.cl.cam.ac.uk/teaching/1112/ECAD+Arch/lab2/ring.html | CC-MAIN-2016-36 | refinedweb | 1,703 | 60.45 |
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
I just installed ScriptRunner and am trying to get a very basic Hello World script to run. Failing miserably...
I installed the add-on and copied the sample code for Email Notify on Priority Change.
import groovy.xml.MarkupBuilder def priorityChange = get(issue.self) .queryString('expand', 'changelog') .asObject(Map) .body .changelog .histories .last() .items .find { it['field'] == 'priority' } . . .
This fails right out of the chute because it complains that
[static type checking] - the variable [issue] is undeclared
.
I must be missing something basic here. Any thoughts?
Hi Joseph,
The static type checking is only advisory. It is something we are working on to improve the accuracy of. The script you have there should run just fine when the event fires.
Regards, J. | https://community.atlassian.com/t5/Jira-questions/Jira-Cloud-Scriptrunner-Hello-World/qaq-p/7094 | CC-MAIN-2018-09 | refinedweb | 144 | 66.23 |
Hey Folks, Our old Server 2008 R2 fileserver is near capacity and needing to be put out to pasture. I have a new Server 2016 VM with much more space ready to go, but there's a catch. Or two. First, for various reasons we cannot just archive old documents, etc., so I have some file paths that go back over a decade and might exceed the 256 character limit. I'm looking for a tool that can copy the roughly 1TB of files to their new home and not be bothered by this, PLUS... I need the files and folders copied with no shares or permissions because we're starting fresh. Really fresh, and need to configure access per best (not beast) practices. What recommendations do you have for me? I'm not afraid of paying a bit for a quality product.
Thanks you spicy people!
7 Replies
Oct 12, 2018 at 21:49 UTC
No need to buy something robocopy would work for you.
Oct 12, 2018 at 21:51 UTC
RoboCopy, Unstoppable Copier, RichCopy...all free, all will work.
Oct 12, 2018 at 21:52 UTC
I've used xxcopy in the past for things like this, it's command line but very feature rich.
Oct 12, 2018 at 21:54 UTC
No need to buy something robocopy would work for you.
Even better, I forgot about robocopy.
Oct 12, 2018 at 21:57 UTC
Robocopy for the tool and RBAC for the permissions. done.
Oct 12, 2018 at 23:45 UTC
Or create a DFS, you can later have the advantage of the namespace without a second sever, but any future additional file server can be added and you only fix the drive mappings once...
Oct 13, 2018 at 16:58 UTC
+ 1 for robocopy | https://community.spiceworks.com/topic/2168756-bulk-copy-tool | CC-MAIN-2018-43 | refinedweb | 299 | 81.63 |
The Azure AD Graph team is very pleased to announce the availability of the next version of Azure AD Graph API, api-version=1.5. With this release we've opened up a new set of scenarios for developers, which we'll describe in more detail below:
- Authorize access to your applications based on group claims or application specific roles claims present
in tokens. Through Graph API you can now:
- Configure the group membership claims issuance policy on an application
- Define roles specific to your application. These roles can be chosen when assigning the application to users, groups or service principals, either programmatically or through the Azure Management Portal. When the user signs in to the application the user token will contain a roles claim with any of the application roles the user was assigned to - either directly or indirectly through group assignment.
- Expose your application as a web API secured by Azure AD by defining OAuth2.0 permission scopes. These permission scopes may then be chosen by client applications that call your web API.
- Directory Extensions is now released for General Availability, with a new additional capability that differential query will now respond with any changes to schema extended properties too.
For full details of all the changes in api-version 1.5 (from the previous api-version=2013-11-08), please see.
NOTE: In this blog we'll also provide some details on the latest application manifest updates. You should note that the operations described in 1 and 2 above are also configurable through the application manifest.
At the same time as releasing a new version of Graph API, we've also released a new Graph client library with lots of cool new capabilities. You can check out our blog post for that here.
General information about version 1.5
In this release we also focused on improvements based on developer’s feedback. Versioning scheme has been updated to numeric major.minor format and is better aligned with versioning scheme of Office 365 REST APIs GA release.
The schema namespace of Graph API has changed from Microsoft.WindowsAzure.ActiveDirectory to Microsoft.DirectoryServices. This affects all entities and complex types exposed by Graph API.
Additionally starting with this version, we plan to start adding new entities and properties more frequently without revisiting the service version in order to allow developers to take advantage of new features sooner. If you are using the WCF client library, then you should make sure to set “IgnoreMissingProperties” to true. You’ll need this anyway to support directory schema extensions. Please do let us know what you think. We are looking forward to hearing your feedback about this approach.
Application roles
You can define roles specific to your application. Imagine you have a Dental Practice app - you might define the following roles:
- "Dentist" role allowed to create, view and update
patient health records
- "Receptionist" role allowed to create and manage patient
information (but not personal health details), and manage appointments.
These application roles can be assigned to a user or group (as well as a service principal). Then when a user signs in to the application, the user token will contain a roles claim with any of the application roles the user was assigned to - either directly or indirectly through group assignment. This then allows your application to make authorization decisions purely based on the roles claim. We'll show you how to create, view, update and delete application roles, as well as assigning and removing assignments of application roles.
Adding and viewing application roles
NOTE: application roles can be created as part of application creation - however that is not shown here. Instead we'll just how you how to add app roles to an existing application. The following shows the addition of the 2 roles described above.
allowedMemberTypes describes the entities that the role may be assigned to. User means the role can be assigned to a useror group. Application means the role can be assigned to another application - in the form of a service principal. This latter scenario is allows a different client application to call this application's API in a particular role. More details can be found on the AppRole complex type description.
Viewing a role
Viewing a role is as simple as getting the application entity:
GET
The application role is returned in the appRoles collection.
Updating a role
The following updates the existing Dentist role to allow it to be assigned to an application, as well as changing the description.. Note that the whole appRoles collection must be sent again in the update, including the edits that you wish to make. If you want to add a new app role then you need to add it to the existing collection.
Deleting a role
Deleting a role is possible, but you'll need to be sure to update your application code to account for the fact that existing users, groups and service principals may have already been assigned this deleted role. Your app code will still need to support this roles claim value showing up.
To delete an app role, you must first update the app role (PATCH) by setting isEnabled to false. Once that is done, create a new JSON appRoles collection payload without the app role you want to delete, and update using PATCH.
Viewing application role assignments
The following will list all application role assignments for a user:
GET
Similarly for a group:
GET
Similarly for a service principal (to see the app role assignments an application has to call into a resource application):
GET
To view the list of all app role assignments to a resource (represented by a service principal) – this will allow you to tell which users, groups and service principals are assigned to this resource:
GET
Assigning application roles
The following will assign the dentist application role described earlier to a user.
NOTE: It is possible to assign a user or a group to a resource through appRoleAssignments. This is possible even if the resource does not declare any app roles. In this case you should set the “id” in the request body to a zero GUID value.
NOTE: Currently assignment of a service principal to a resource is broken and we’ll work to fix this problem, and update this post when it's fixed.
Removing application role assignments
DELETE
OAuth2.0 Permission Scopes
Expose your application as a RESTful API secured by Azure AD by defining OAuth2.0 permission scopes. These permission scopes may then be chosen by client applications that call your API using the RequiredResourceAccess complex type.
Creating OAuth2.0 Permission Scopes
NOTE: Permission scopes can be created as part of application creation - however that is not shown here. Instead we'll just how you how to add permission scopes to an existing application. The following shows the addition of a single permission that represents the ability for the calling application to fully impersonate the signed in user without any constraint. This permission may be granted by both users and administrators (type = User) and contains different display names and descriptions depending on whether this app is being consented to by a user, or by an admin on behalf of the school or company.
Updating OAuth2.0 Permission Scopes
This follows the same pattern as updating application roles.
Deleting OAuth2.0 Permission Scopes
This follows the same pattern as deleting application roles.
Granting OAuth2.0 permissions
The mechanism for this has not been updated in 1.5, although the link has been renamed from "permissions" to "oauth2PermissionGrants".
Configuring your app to access other resources
While this is possible through the RequiredResourceAccess complex type, discovering other developer’s API appId and the oauth2Permissions or appRole unique identifiers they expose may be difficult. For those scenarios, it’s recommended to actually configure this through UX – either in the Azure Management Portal (under the configure applications “Access to other applications” section) or through the Office
365 API tools for Visual Studio.
RequiredResourceAccess can also be viewed and set through the application manifest file.
Updates to directory roles
In Graph API 1.5, roles has been renamed to DirectoryRoles, so that we avoid any confusion with appRoles (described earlier). DirectoryRoles represent the built-in roles exposed by the directory itself, some of which are described here.
By default, when a tenant is created, only the Company Administrator role is instantiated (along with an implicit User role). In order to assign users or service principals to one of the built-in roles, that role
first has to be instantiated from a directory role template. The set of available roles can be listed using the DirectoryRoleTemplate read-only entity.
To instantiate the role from a template, use the objectId of the desired role template. So for example, if we want to instantiate the User Account Administratorrole, perform the following POST operation on DirectoryRoles, setting roleTemplateId to fe930be7-5e62-47db-91af-98c3a49a38b1:
Querying the DirectoryRoles will show the instantiated directory roles including the newly instantiated User Account Administrator role:
GET
You can assign a user to a directory role by performing a POST operation on a specific directory roles link members as described here, where the directory role is specified by its objectId (and not its role template ID). When an application is configured to request group membership claims, the directory roles (object id) that the user is a member of will appear in these claims.
A little information about the Application Manifest
Through the Azure Management Portal, you are able to download, as well as upload a file representation of your application (in JSON format). No actual file is stored in the directory - the application manifest is merely a GET on the application entity, and the upload is a PATCH on the application entity. As a result, in order to find documentation on the format and properties of the application manifest, simply review the MSDN reference documentation on the application entity.
The Azure Management Portal provides UX for you to update the most common properties of an application. For more advanced scenarios, that are not exposed in the UX, you can use the application manifest, as an alternative to writing an application to call the Graph API to update your applications. Example updates that can be performed though app anifest upload include:
- Declare permission scopes (oauth2Permissions) exposed by your web API
- Declare application roles (appRoles) exposed by your app
- Declaring known client applications
- Request Azure AD issue group memberships claim for the signed in user. NOTE: this can be configured to additionally issues claims about the user's directory roles memberships.
- Allow your application to support OAuth 2.0 Implicit grant flows (for embedded JS web pages or SPA)
- Enable use of X509 certificates as the secret key
The application manifest also provides a good way to track the state of your app registration, and this file representation can be checked in along with your app's source code.
NOTE: For the Graph API 1.5 release, the application manifest signature has changed. There is currently no versioning support, so any attempts to upload an older format application manifest (generated before the release of Graph API 1.5) will result in an error. In this case simply re-download your app manifest from the Azure Management Portal to get the latest format.
Directory Schema Extensions
Directory extensions is now released for General Availability.
You can use directory schema extensions to store application data in the directory without having to store the same data in your own application profile database. For more scenarios anddetails on the entities that can be extended, possible extensions, and how to use the Graph API to manipulate extensions please see our topic on Directory Schema Extensions.
NOTE: Any extensions you created during the preview period for this feature are supported in 1.5.
Additionally, differential query will now respond with any changes to schema extended properties too.
Feedback
We hope you like the new functionality that we've added to the graph API in version 1.5. Please let us know what you think.
Thanks,
The Azure AD Graph API team.
Graph API (api-version=1.5) : How to remove user from Application Role using C# .NET
Hi,
I am using Azure AD for user and role management operations from my MVC web application. I am using version of Graph API as 1.5 and Microsoft.Azure.ActiveDirectory.GraphClient .Net library 2.0.6.
I need to remove an AppRoleAssignement (Application Role) assigned to user by calling Graph API. I was referring Stackoverflow link. Is there any method available in which I can use in my C# code to delete AppRoleAssignment.
When I get users from active directory, the AppRoleAssignement always come null, even if an application role is assigned to a user.
Kindly, help me providing a correct version of dll and available method to delete AppRoleAssignment.
Thank you.
Thanks for this post.
Referring to the note: "NOTE: Currently assignment of a service principal to a resource is broken and we’ll work to fix this problem, and update this post when it's fixed"
How close is it getting to seeing that resolved?
I follow this instruction but always get status 403 "Insufficient privileges to complete the operation" when I try with PATCH Method. I configured all permissions by check all options at "permissions to other applications" on my AAD.
I am not able to delete the application role assigned to the user(am getting "Invalid resource identifier for Entitlement Grant").Am assuming the parameter in the last is the role id in the example : graph.windows.net/…/kwi4hEmHo0CXt2hRO2AFRKOaYLLQbgVIqOCz-qKlrO0
Co-ask:
Referring to the note: "NOTE: Currently assignment of a service principal to a resource is broken and we’ll work to fix this problem, and update this post when it's fixed"
How close is it getting to seeing that resolved?
I'm trying to add a new app role dynamically via Graph API for .NET (rather than having to manually tweak the manifest) but am getting an insufficient privileges error.
id="Microsoft.Azure.ActiveDirectory.GraphClient" version="2.1.0"
Error:
{"odata.error":{"code":"Authorization_RequestDenied","message":{"lang":"en","value":"Insufficient privileges to complete the operation."}}}
Very similar codes works for adding a new group just fine.
Any clue as to how to programmatically add a new app role and add a user into the new role? | https://blogs.msdn.microsoft.com/aadgraphteam/2014/12/12/announcing-the-new-version-of-graph-api-api-version1-5/ | CC-MAIN-2018-30 | refinedweb | 2,399 | 52.6 |
View all headers
Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!newsfeed.stanford.edu!newsfeed.berkeley.edu!ucberkeley!newsfeed.arcor.de!newsfeed.freenet.de!novso.com!news-out.newsfeeds.com!local!news.eskimo.com!eskimo.com!scs
From: scs@eskimo.com (Steve Summit)
Newsgroups: comp.lang.c,comp.lang.c.moderated,comp.answers,news.answers
Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ List)
Followup-To: poster
Date: 1 Nov 2008 10:00:10 GMT
Organization: better late than never
Lines: 7132
Approved: news-answers-request@MIT.Edu
Expires: 3 Dec 2008 00:00:00 GMT
Message-ID: <2008Nov01.0600.scs.0003@eskimo.com>
Reply-To: scs@eskimo.com
NNTP-Posting-Host: eskimo.com
X-Trace: eskinews.eskimo.com 1225533610 13780 204.122.16.13 (1 Nov 2008 10:00:10 GMT)
X-Complaints-To: abuse@eskimo.com
NNTP-Posting-Date: 1 Nov 2008 10:00:10 GMT
X-Last-Modified: July 3, 2004
X-Archive-Name: C-faq/faq
X-Version: 4.0
X-URL:
iQCSAwUBQOcyEt6sm4I1rmP1AQEP0gPlF0jTBBuSUanN9BtX74zLEx29gHNhd206
Gv1J92XaRo+m0b5MRrXyqLlDGzuQj8Xu4yoGGGedQ+dHuYyYOfUJ+SyXN1sY26/t
QBUBQrp0cJy42/xUW2z3RcWkAsHEL4S9CnFnLgkXuzKFUz24xpTffbkLEjhGafpF
QJtIPLI=
=KkvT
Originator: scs@eskimo.com
Xref: senator-bedfellow.mit.edu comp.lang.c:918690 comp.lang.c.moderated:31875 comp.answers:66142 news.answers:320936
View main headers
.:
Bibliography
Acknowledgements
.
See also questions 10.6.
1.11: What does extern mean in a function declaration?
A:.])())();... */
3.."; in the case of the above example:
...
char namestr[MAXSIZE];.
2.8: : above.
References: H&S Sec. 5.6.7 pp. 139-40.
2.14:.
References: ISO Sec. 7.1.6; Rationale Sec. 3.5.4.2; H&S
Sec. 11.1 pp. 292-3.
2.15:;:';
See also questions 1.21, 7.1, 7.3c, and 8.3.
References: CT&P Sec. 3.1 p. 28.
4.3:.
4.5:);?.
4.15:.
Section 5. Null Pointers
5.1:, the address-of operator & will never yield
a null pointer, nor will a successful call to malloc().
:.2.
5, to be known by the name "p". This
pointer can point almost anywhere: to any char, or to any
contiguous array of chars, or nowhere (see also questions 5.1
and 1.30).
As usual, a picture is worth a thousand words. The declarations
char a[] = "hello";
char *p = "world";
would initialize data structures which could be represented like
this:
+---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
+---+---+---+---+---+---+
+-----+ +---+---+---+---+---+---+
p: | *======> | w | o | r | l | d |\0 |
+-----+ +---+---+---+---+---+---+
It is useful other words, a[3] is
three places past (the start of) the object *named* a, while
p[3] is three places past the object *pointed to* by p. In the
example above, both a[3] and p[3] happen to be the character
'l', but the compiler gets there differently. (The essential
difference is that the values of an array like a and a pointer
like p are computed differently *whenever* they appear in
expressions, whether or not they are being subscripted, as
explained further in: How can I set an array's size at run time?
How can I avoid fixed-sized arrays?
A: The equivalence between arrays and pointers (see question 6.3)
allows a pointer to malloc'ed memory to simulate an array
quite effectively. After executing
#include <stdlib.h>
int *dynarray;
dynarray = malloc(10 * sizeof(int));
(and if the call to malloc succeeds), you can reference
dynarray[i] (for i from 0 to 9) almost as if dynarray were a
conventional, statically-allocated array (int a[10]). The only
difference is that sizeof will not give the size of the "array".. An array of arrays (i.e. a two-
dimensional array in C) decays into a pointer to an array, not a
pointer to a pointer. Pointers to arrays can be confusing, and
must be treated carefully; see also question 6.13.
If you are passing a two-dimensional array to a function:
int array[NROWS][NCOLUMNS];
f(array);
the function's declaration must match:
void f(int a[][NCOLUMNS])
{ ... }
or
void f(int (*ap)[NCOLUMNS]) /* ap is a pointer to an array */
{ ... }
In the first declaration, the compiler performs the usual
implicit parameter rewriting of "array of array" to "pointer to
array" (see questions 6.3 and 6.4); in the second form the
pointer declaration is explicit. Since the called function does
not allocate space for the array, it does not need to know the
overall size, so the number of rows, NROWS, can be omitted. The
width of the array is still important, so the column dimension
NCOLUMNS (and, for three- or more dimensional arrays, the
intervening ones) must be retained.
If a function is already declared as accepting a pointer to a
pointer, it is almost certainly meaningless to pass a two-
dimensional array directly to it.
See also questions 6.12 and 6.15.
References: K&R1 Sec. 5.10 p. 110; K&R2 Sec. 5.9 p. 113; H&S
Sec. 5.4.3 p. 126.
6.19:.
6.20: How can I use statically- and dynamically-allocated
multidimensional arrays interchangeably when passing them to
functions?
A: There is no single perfect method. Given the declarations
int array[NROWS][NCOLUMNS];
int **array1; /* ragged */
int **array2; /* contiguous */
int *array3; /* "flattened" */
int (*array4)[NCOLUMNS];
with the pointers initialized as in the code fragments in
question 6.16, and functions declared as
void f1a(int a[][NCOLUMNS], int nrows, int ncolumns);
void f1b(int (*a)[NCOLUMNS], int nrows, int ncolumns);
void f2(int *aryp, int nrows, int ncolumns);
void f3(int **pp, int nrows, int ncolumns);
where f1a() and f1b() accept conventional two-dimensional
arrays, f2() accepts a "flattened" two-dimensional array, and
f3() accepts a pointer-to-pointer, simulated array (see also
questions 6.18 and 6.19), the following calls should work as
expected:
f1a(array, NROWS, NCOLUMNS);
f1b(array, NROWS, NCOLUMNS);
f1a(array4, nrows, NCOLUMNS);
f1b(array4, nrows, NCOLUMNS);
f2(&array[0][0], NROWS, NCOLUMNS);
f2(*array, calls would probably work on most systems, but
involve questionable casts, and work only if the dynamic
ncolumns matches the static NCOLUMNS:
f1a((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
f1a((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
f1b((int (*)[NCOLUMNS])array3, nrows, ncolumns);
f1b((int (*)[NCOLUMNS])array3, nrows, ncolumns);
It must again be noted that passing &array[0][0] (or,
equivalently, *array) to f2() is not strictly conforming; see
question 6.19.
If you can understand why all of the above calls work and are
written as they are, and if you understand why the combinations
that are not listed would not work, then you have a *very* good
understanding of arrays and pointers in C.
Rather than worrying about all of this, one approach to using
multidimensional arrays of various sizes is to make them *all*
dynamic, as in question 6.16. If there are no static
multidimensional arrays -- if all arrays are allocated like
array1 or array2 in question 6.16 -- then all functions can be
written like f3().:. That is, we cannot say where
the pointer answer points. .
7.2: I can't get strcat() to work. I tried
char *s1 = "Hello, ";
char *s2 = "world!";
char *s3 = strcat(s1, s2);
but I got strange results.
A: As in question 7.1 above,. Therefore, one fix would be to
declare the first string as an array:
char s1[20] = "Hello, ";
Since strcat() returns the value of its first argument (s1, in
this case), the variable s3().: What is alloca() and why is its use discouraged?
A: alloca() allocates memory which is automatically freed when the
function which called alloca() returns. That is, memory
allocated with alloca is local to a particular function's "stack
frame" or context.
alloca() cannot be written portably, and is difficult to
implement on machines without a.).)
Some people prefer variants like
#define TRUE (1==1)
#define FALSE (!TRUE)
or define "helper" macros such as
#define Istrue(e) ((e) != 0)
These don't buy anything (see question 9.2 below; see also
questions 5.12 and 10.2).
9.2:, it is guaranteed to be 1 or 0.:. (C
is unlike C++ in this regard.) When you need a true compile-
time constant, use a preprocessor #define (or perhaps an enum).
References: ISO Sec. 6.4; H&S Secs. 7.11.2,7.11.3 pp. 226-7.
11.8.
11.9: What's the difference between "const char *p" and
"char * const p"?
A: "const char *p" (which can also be written "char const *p")
declares a pointer to a constant character (you can't change any
pointed-to characters); :.)
References: ISO Sec. 5.1.2.2.1, Sec. G.5.1; H&S Sec. 20.1 p.
416; CT&P Sec. 3.10 pp. 50-51.
11.13:.
11.14.
11.14().:.
11.20:.:.
11.29: My compiler is rejecting the simplest possible test programs,
with all kinds of syntax errors.
A: Perhaps it is a pre-ANSI compiler, unable to accept function
prototypes and the like.
See also questions 1.31, 10.9, 11.30, and 16.1b.
11.30:, 13.25, and 13.26.
11.31:.)
11.32:? It is usually a bad idea to perform
experiments with a particular compiler to determine properties
of a language; the applicable standard may permit variations, or
the compiler may be wrong. See also question 11.35.
11.33: People seem to make a point of distinguishing between
implementation-defined, unspecified, and undefined behavior.
What's the difference?
A: Briefly: implementation-defined means that an implementation
must choose some behavior and document it. Unspecified means
that an implementation should choose some behavior, but need not
document it. Undefined means that absolutely anything might
happen. In no case does the Standard impose requirements; in
the first two cases it occasionally suggests (and may require a
choice from among) a small set of likely behaviors...
11.33b: uses the language
exactly as specified in the Standard, and that does not depend
on any implementation-defined, unspecified, or undefined
behavior.
A "conforming implementation" is one that does everything the
Standard says it's supposed to.
References: ISO Sec. ; Rationale Sec. 1.7.
11.34: question 11.35.
References: Rationale Sec. 1.1.
11.35:. See also questions 7.3b,.1b: I have a simple little program that reads characters until EOF,
but how do I actually *enter* that "EOF" value from the
keyboard?
A: It turns out that the value of EOF as seen within your C program
has essentially nothing to do with the keystroke combination you
might use to signal end-of-file from the keyboard. Depending on
your operating system, you indicate end-of-file from the
keyboard using various keystroke combinations, usually either
control-D or control-Z.
12.2: Why does the code -- fgets(), for example, returns NULL on end-
of-file. In virtually all cases, there's no function.12b: Why *does* the call
char s[30];
scanf("%s", s);
work (without the &)?
A: You always need a *pointer*; you don't necessarily need an
explicit &. When you pass an array to scanf(), you do not need
the &, because arrays are always passed to functions as
pointers, whether you use & or not. See questions 6.3 and 6.4.a:)., and it may be called with a buffer size
of 0. Therefore, the call
nch = snprintf(NULL, 0, fmtstring, /* other arguments */ );
predicts. The Standard fgets() function is a vast
improvement over gets(), although it's not perfect, either.
(If long lines are a real possibility, their proper handling
must be carefully considered.):
of about 2 billion (2**31-1)..
12.26.
12.26b:, nor would such a way necessarily be
sufficient, since unread characters can also accumulate in
other, OS-level input buffers. If you're trying to actively
discard typed-ahead input (perhaps in anticipation of issuing a
critical prompt), you'll have to use a system-specific
technique; see questions 19.1 and 19.2.
References: ISO Sec. 7.9.5.2; H&S Sec. 15.2.
12.27: fopen() is failing for certain pathnames.
A: See questions 19.17 and 19.17b.
12.30:, and that overwriting in text mode may
truncate the file at that point, and that you may have to
preserve line lengths.:.
It may be possible, in a nonportable way, to save away
information about a stream before calling freopen(), such that
the original stream can later be restored. One way is to use a
system-specific call such as dup() or dup2(), if available.
Another is to copy or inspect the contents of the FILE
structure, but this is exceedingly nonportable and unreliable.
12.36b: How can I arrange to have output go two places at once,
e.g. to the screen and to a file?
A: You can't do this directly, but you could write your own printf
variant which printed everything twice. Here is a simple
example:
#include <stdio.h>
#include <stdarg and it prints to both of them.
See also question 15.5.
12.38:". questions 8.6 and)..
13.8:().
(Don't be misled by the discussion in K&R2 Sec. 5.11 pp. 119-20,
which is not discussing the Standard library's qsort).
References: ISO Sec. 7.10.5.2; H&S Sec. 20.5 p. 419.
13.9:.:.
References: Knuth Sec. 5.2.1 pp. 80-102, Sec. 5.2.4 pp. 159-168;
Sedgewick Sec. 8 pp. 98-100, Sec. 12 pp. 163-175.
13.11:. %s", ctime(&now));
return 0;
}
If you need control over the format, use strftime().
If you need sub-second resolution, see question 19.37.
References: K&R2 Sec. B10 pp. 255-7; ISO Sec. 7.12; H&S Sec. 18..
13.14:.
(For conservatively-sized time_t, that range is often -- but not
always -- from 1970 to approximately 2037; note however that
there are time_t representations other than as specified by Unix
and Posix.), which will work over a much
wider range of dates, is to use "Julian day numbers"..
References: K&R2 Sec. B10 p. 256; ISO Secs. 7.12.2.2,7.12.2.3;
H&S Secs. 18.4,18.5 pp. 401-2; David Burki, "Date Conversions".
13.15:".
13.16:) (or at least variable) initial value, such
as the time of day. Here is a simple example:
#include <stdlib.h>
#include <time.h>
srand((unsigned int)time((time_t *)NULL));
(Unfortunately, this code isn't perfect -- among other things,
the time_t returned by time() might be a floating-point type,
hence not portably convertible to unsigned int without the
possibility of overflow. See.:
;
}
See the extended versions of this list (see question 20.40) for
other ideas.
References: Knuth Sec. 3.4.1 p. 117; Marsaglia and Bray,
"A Convenient Method for Generating Normal Variables";
Press et al., _Numerical Recipes in C_ Sec. 7.2 pp. 288-290.
13.25: I keep getting errors due to library functions being undefined,
but I'm #including all the right header files.
A: In general, a header file contains only external declarations.
In some cases (especially if the functions are nonstandard)
obtaining the actual *definitions* may require explicitly asking
for the correct libraries to be searched when you link the
program. (#including the header doesn't do that.) See also
questions 10.11, 11.30, 13.26, 14.3, and 19.40.
13.26: options towards the end of the command
line.) See also question 13.28.
13.28:.)
13.29: My compiler is complaining that printf is undefined!
How can this be?
A: Allegedly, there are C compilers for Microsoft Windows which do
not support printf(). It may be possible to convince such a
compiler that what you are writing is a "console application"
meaning that it will open a "console window" in which printf()
is supported.
Section 14. Floating Point
14.1: When I set a float variable to, say, 3.1, why is printf printing
it as 3.0999999?
A: Most computers use base 2 for floating-point numbers as well as
for integers. Although 0.1 is a nice, polite-looking fraction
in base 10, its base-2 representation is)...
14.4a:) or acos(-1.0).
References: PCS Sec. 13 p. 237.
14.9: How do I test for IEEE NaN is
exemplified by
#define isnan(x) ((x) != (x))
although non-IEEE-aware compilers may optimize the test away.
C99 provides isnan(), fpclassify(), and several other
classification routines.
Another possibility99 supports complex
as a standard type. See also questions 2.10 and 14.12.
References: C9X Sec. 6.1.2.5, Sec. 7.8.
14.12:.
14.13:.)
Section 15. Variable-Length Argument Lists
15.1:.
15.2:.
15.3:.
See also questions 5.2, 11.3, 12.9, and 15.2.
15.4:;
}
Usage is something like
char *str = vstrcat("Hello, ", "world!", (char *)NULL);
Note the cast on the last argument; see questions 5.2 and 15.3.
(Also note that the caller must free the returned, malloc'ed
storage.).
15.5: How can I write a function that takes a format string and a
variable number of arguments, like printf(), and passes them to
printf() to do most of the work?
A: Use vprintf(), vfprintf(), or vsprintf().");
}99 (but *not* any earlier C Standard) supports vscanf(),
vfscanf(), and vsscanf().
References: C9X Secs. 7.3.6.12-14.
15, 10.9, 11.12b,
and 11.14a),a)", "Bus error", and "General
protection fault",.
See also question 10.6.
References: K&R1 Sec. 1.2 p. 10; K&R2 Sec. 1.2 p. 10.
17.3: use a macro:
#define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
See also question 17.10.
17.4:.
(Of course, the trick only helps when comparing to a constant.)
References: H&S Sec. 7.6.5 pp. 209-10.
17.4b:
The extra parentheses in the invocation
extern int func __((int, int));
are required so that the entire prototype list (perhaps
containing many commas) is treated as the single argument
expected by the macro.
17.5: I came across some code that puts a (void) cast before each call
to printf(). Why?
A: printf() does return a value,.
17.8:" .
17.9:.
17.10:).
Most observations or "rules" about programming style. It's usually futile to get dragged into "style wars,"
because on certain issues (such as those referred to in
questions 5.3, 5.9, 9.2, and 10.7), opponents can never seem to
agree, or agree to disagree, or stop arguing.
Section 18. Tools and Resources
[NOTE: Much of the information in this section is fairly old and may be
out-of-date, especially the URLs of various allegedly publicly-available
packages. Caveat lector.] there is also a package sold by
McCabe and Associates
a C lines-of-source this can be done very crudely
counter with the standard Unix utility
wc, and somewhat better with
grep -c ";"
a C declaration aid check volume 14 of
(cdecl) comp.sources.unix (see question
18.16) and K&R2
a prototype generator see question 11.31
a tool to track down see question 18.2
malloc problems
a "selective" C see question 10.18
preprocessor
language translation see questions 11.31 and 20.26
tools
C verifiers (lint) see question 18.7
a C compiler! see question 18.3
(This list of tools is by no means complete; if you know of
tools not mentioned, you're welcome to contact this list's
maintainer.)
Other lists of tools, and discussion about them, can be found in
the Usenet newsgroups comp.compilers and comp.software-eng.
See also questions 18.3 and 18.16.;
MEMDEBUG from in pub/sources/memdebug ; and
Electric Fence. See also question 18.16.
A number of commercial debugging tools exist, and can be
invaluable in tracking down malloc-related and other stubborn
problems:
CodeCenter (formerly Saber-C) from Centerline Software
().
Insight (now Insure?), from ParaSoft Corporation
().
Purify, from Rational Software (-
306.ibm.com/software/rational/, formerly Pure Software,
now part of IBM).
ZeroFault, from The ZeroFault Group,.
18.3: What's a free or cheap C compiler I can use?
A: A popular and high-quality free C compiler is the FSF's GNU C
compiler, or gcc; see the gcc home page at.
An MS-DOS port, djgpp, is also available; see the djgpp home
page at. As far as I know, there
are versions of gcc for Macs and Windows machines, too.
Another popular compiler is lcc, described at and. at include an
FAQ list and a catalog of free compilers. are available from Gimpel
Software at.) at.
In the absence of lint, many modern compilers do attempt to
diagnose almost as many problems as lint does. (Many netters
recommend gcc -Wall -pedantic .)
18.8: Don't ANSI function prototypes render lint obsolete?
A: Not really. by ftp from svr- in
misc/sawtell_C.shar and garbo.uwasa.fi in pc/c-lang/c-
lesson.zip, or on the web at .
Tim Love's "C for Programmers" is available by ftp from svr- in the misc directory. An html version is at
teaching_C.html ..
18.9b: Where can I find some good code examples to study and learn
from?
A: Here are a couple of links to explore:
(Beware, though, that there is all too much truly bletcherous
code out there, too. Don't "learn" from bad code that it's the
best anyone can do; you can do better.) See also questions
18.9, 18.13, 18.15c, and 18.16.
18.10: What's a good book for learning C? What about advanced books
and references?.
The Association of C and C++ Users (ACCU) maintains a
comprehensive set of bibliographic reviews of C/C++ titles at.
See also question 18.9 above.
18.13: by Jim Roskind
is available at in u/s/scs/roskind_grammar.Z .
A fleshed-out, working instance of the ANSI C90.
18.15d:.
Section 19. System Dependencies
19.1:..).) The extended versions of this FAQ list
(see question 20.40) contain examples of such functions for
several popular systems.
See also question 19.2.
References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1; POSIX
Sec. 7.
19.2:(). See also question 19.1.
19.3:. (But remember
to call fflush(), too.):.
19.6:.
19.7:.
19.8:..9b: How can I access an I/O board directly?
A: In general, there are two ways to do this: use system-specific
functions such as "inport" and "outport" (if the device is
accessed via an "I/O port"), or use contrived pointer variables
to access "memory-mapped I/O" device locations. See question
19.25.
19.10:.
19.10b: How can I display GIF and JPEG images?
A: It will depend on your display environment, which may already
provide these functions. Reference JPEG software is at .
19.11:.
19.12: How can I find out the size of a file, prior to reading it in?
A: If the "size of a file" is the number of characters you'll be
able to read from it in C, it can be difficult or impossible to
determine this number exactly.
Under Unix, the stat() call will give you an exact answer.
Several other systems supply a Unix-like stat() which will give
an approximate answer. You can fseek() to the end and then use
ftell(), or maybe try fstat(), but these tend to have the same
sorts of.:()).
19.16:().
References: K&R2 Sec. B1.1 p. 242; ISO Sec. 7.9.4.1; H&S
Sec. 15.15 p. 382; PCS Sec. 12 pp. 208,220-221; POSIX
Sec. 5.5.1, Sec. 8.2.4.
19.16b:.
References: K&R Sec. 1, Sec. 7.
19.17:.)
19.17b:().
19.17c: How can I suppress the dreaded MS-DOS "Abort, Retry, Ignore?"
A: Among other things, you need to intercept the DOS Critical Error
Interrupt, interrupt 24H. See the comp.os.msdos.programmer FAQ
list for more details.
19.18:.
19.20:.: question 6.16..
19.24:."
19.25: How can I access memory (a memory-mapped device, or graphics
memory) located at a certain address?. If the
location is a memory-mapped I/O register, you will probably also
want to use the volatile qualifier. ().
Depending on your operating system, you may also be able to use
system calls such as exec or spawn (or execl, execv, spawnl,
spawnv, etc.).() when you're done.):.
19.32: How can I automatically locate a program's configuration files
in the same directory as the executable?
A: It's hard; see also question 19.31 above..)
19.33:. Under MS-DOS, it's possible to manipulate the master
copy of the environment, but the required techniques are arcane.
(See an MS-DOS FAQ list.)
19.36:.:.
References: H&S Sec. 18.1 pp. 398-9; PCS Sec. 12 pp.
197-8,215-6; POSIX Sec. 4.5.2.
19.38:.
19.39: above) to catch SIGFPE. See
also question 14.9.
References: Rationale Sec. 4.5.1.
19.40:" at ,
and "Beej's Guide to Network Programming" at.
(One tip: depending on your OS, you may need to explicitly
request the -lsocket and -lnsl libraries; see question 13.25.)
19.40b:..40d: What are "near" and "far" pointers?
A: These days, they're pretty much obsolete; they're definitely
system-specific. If you really need to know, see a DOS- or
Windows-specific programming reference.
19.41:.
Section 20. Miscellaneous
20.1: How can I return multiple values from a function?
A: Either pass pointers to several locations which the function can
fill in, or have the function return a structure containing the
desired values, or (in a pinch) you could theoretically use
global variables. See also questions 4.8 and 7.5a.
20.3: How do I access command-line arguments?
A: They are pointed to by the argv array with which main() is
called..
20.5:
and 12.38.
References: PCS Sec. 6 pp. 86, 88.
20.6: If I have a char * variable pointing to the name of a function,
how can I call that function?
A: The most straightforward thing to do is to maintain. questions 10.16 and 20.9b.
References: H&S Sec. 6.1.2 pp. 163-4.
20.9b: How do I swap bytes?
A: V7 Unix had a swab() function, but it seems to have been
forgotten.
A problem with explicit byte-swapping code is that you have
to decide whether to call it or not; see question 20.9 above.
A better solution is to use functions (such as the BSD
networking ntohs() et al.) which convert between the known byte
order of the data and the (unknown) byte order of the machine,
and to arrange for these functions to be no-ops on those
machines which already match the desired byte order.
If you do have to write your own byte-swapping code, the two
obvious approaches are again to use pointers or unions, as in
question 20.9.
References: PCS Sec. 11 p. 179.
20.10:.:. Check the compiler's
assembly language output, if available, to see if two purported
alternatives aren't compiled identically.)
For conventional machines,..)
20.15b:.
20.15c:.:.
20.20:.
20.21b: ++ ++ + b
and cannot be parsed as a valid expression.
References: K&R1 Sec. A2 p. 179; K&R2 Sec. A2.1 p. 192; ISO
Sec. 6.1; H&S Sec. 2.3 pp. 19-20.
20.24:.)
20.24b:.
20.25:. translators.
See also questions 11.31 and 18.16.
20.27: Is C++ a superset.:.
20.32: Is (year % 4 == 0) an accurate test for leap years? (Was 2000 a
leap year?)
A: No, it's not accurate (and yes, 2000 was a leap year). question
13.14.
20.34:")");})
20.35:.")
20.36: When will the next International Obfuscated C Code Contest
(IOCCC) be held? .
20.37:.
20.38:++.
20.39: How do you pronounce "char"?
A: You can pronounce the C keyword "char" in at least three ways:
like the English words "char," "care," or "car" (or maybe even
"character"); the choice is arbitrary.
20.39b:).
20.40: . See the meta-FAQ list in
news.answers for more information.
A hypertext (HTML) version of this FAQ list is available on the
World-Wide Web; the URL is .
A comprehensive site which references all Usenet FAQ lists. [There is
also a fifth edition: 2002, ISBN 0-13-089592-X.] _, Third Edition, Addison-Wesley, 1997, ISBN
0-201-89683-4. Volume 2: _Seminumerical Algorithms_, Third Edition,
1997, ISBN 0-201-89684-2. Volume 3: _Sorting and Searching_, Second
Edition, 1998, ISBN 0-201-89685-0. two
volumes are ISBN 0-201-31452-5 and 0-201-31663 .]
Peter van der Linden, _Expert C Programming: Deep C Secrets_, Prentice
Hall, 1994, ISBN 0-13-177429-8., Michael B. Allen, David
Anderson, Jens Andreasen, Tanner Andrews, Sudheer Apte, Joseph
Arceneaux, Randall Atkinson, Kaleb Axon, Daniel Barker, Rick Beem,
Peter Bennett, Mathias Bergqvist, Wayne Berke, Dan Bernstein, Tanmoy
Bhattacharya, John Bickers, Kevin Black, Gary Blaine, Yuan Bo, Mark J.
Bobak, Anthony Borla, Dave Boutcher, Alan Bowler, breadbox@muppetlabs.com,
Michael Bresnahan, Walter Briscoe, Vincent Broman, Robert T. Brown, Stan
Brown, John R. Buchan, Joe Buehler, Kimberley Burchett, Gordon Burditt,
Scott Burkett, Eberhard Burr,, Jim Dalsimer, Andrew
Daviel, James Davies, John E. Davis, Ken Delong, Norm Diamond, Jamie
Dickson, Bob Dinse, dlynes@plenary-software, Colin Dooley, Jeff Dunlop,
Ray Dunn, Stephen M. Dunn, Andrew Dunstan, Michael J. Eager, Scott
Ehrlich, Arno Eigenwillig, Yoav Eilat, Dave Eisen, Joe English, Bjorn
Engsig, David Evans, Andreas Fassl, Clive D.W. Feather, Dominic Feeley,
Simao Ferraz, Pete Filandr, Bill Finke Jr., Chris Flatters, Rod Flores,
Alexander Forst, Steve Fosdick, Jeff Francis, Ken Fuchs, Tom Gambill,
Dave Gillespie, Samuel Goldstein, Willis Gooch, Tim Goodwin, Alasdair
Grant, W. Wesley Groleau, Ron Guilmette, Craig Gullixson, Doug Gwyn,
Michael Hafner, Zhonglin Han, Darrel Hankerson, Tony Hansen, Douglas
Wilhelm Harder, Elliotte Rusty Harold, Joe Harrington, Guy Harris, John
Hascall, Adrian Havill, Richard Heathfield, Des Herriott, Ger Hobbelt,
Sam Hobbs, Joel Ray Holveck, Jos Horsmeier, Syed Zaeem Hosain, Blair
Houghton, Phil Howard, Peter Hryczanek, James C. Hu, Chin Huang, Jason
Hughes, David Hurt, Einar Indridason, Vladimir Ivanovic, Jon Jagger,
Ke Jin, Kirk Johnson, David Jones, Larry Jones, Morris M. Keesan, Arjan
Kenter, Bhaktha Keshavachar, James Kew, Bill Kilgore, Darrell Kindred,
Lawrence Kirby, Kin-ichi Kitano, Peter Klausler, John Kleinjans, Andrew
Koenig, Thomas Koenig, Adam Kolawa, Jukka Korpela, Przemyslaw Kowalczyk,
Ajoy Krishnan T, Anders Kristensen, Jon Krom, Markus Kuhn, Deepak
Kulkarni, Yohan Kun, B. Kurtz, Kaz Kylheku, Oliver Laumann, John Lauro,
Felix Lee, Mike Lee, Timothy J. Lee, Tony Lee, Marty Leisner, Eric
Lemings, Dave Lewis, Don Libes, Brian Liedtke, Philip Lijnzaad, James
D. Lin, Keith Lindsay, Yen-Wei Liu, Paul Long, Patrick J. LoPresti,
Christopher Lott, Tim Love, Paul Lutus, Mike McCarty, Tim McDaniel,
Michael MacFaden, Allen Mcintosh,,
Pedro Zorzenon Neto, Daniel Nielsen, Landon Curt Noll, Tim Norman, Paul
Nulsen, David O'Brien, Richard A. O'Keefe, Adam Kolawa, Keith Edward
O'hara, James Ojaste, Max Okumoto, Hans Olsson, Thomas Otahal, Lloyd
Parkes, Bob Peck, Harry Pehkonen, Andrew Phillips, Christopher Phillips,
Francois Pinard, Nick Pitfield, Wayne Pollock, Polver@aol.com, Dan Pop,
Don Porges, Claudio Potenza, Lutz Prechelt, Lynn Pye, Ed Price, Kevin
D. Quitt, Pat Rankin, Arjun Ray, Eric S. Raymond, Christoph Regli,
Peter W. Richards, James Robinson, Greg Roelofs, Eric Roode, Manfred
Rosenboom, J.M. Rosenstock, Rick Rowe, Michael Rubenstein, Erkki
Ruohtula, John C. Rush, John Rushford, Kadda Sahnine, Tomohiko Sakamoto,
Matthew Saltzman, Rich Salz, Chip Salzenberg, Matthew Sams, Paul Sand,
DaviD W. Sanderson, Frank Sandy, Christopher Sawtell, Jonas Schlein,
Paul Schlyter, Doug Schmidt, Rene Schmit, Russell Schulz, Dean Schulze,
Jens Schweikhardt, Chris Sears, Peter Seebach, Gisbert W. Selke,
Patricia Shanahan, Girija Shanker, Clinton Sheppard, Aaron Sherman,
Raymond Shwake, Nathan Sidwell, Thomas Siegel, Peter da Silva, Andrew
Simmons, Joshua Simons, Ross Smith, Thad Smith, Henri Socha, Leslie
J. Somos, Eric Sosman, Henry Spencer, David Spuler, Frederic Stark,
James Stern, Zalman Stern, Michael Sternberg, Geoff Stevens, Alan
Stokes, Bob Stout, Dan Stubbs, Tristan Styles, Richard Sullivan, Steve
Sullivan, Melanie Summit, Erik Talvola, Christopher Taylor, Dave Taylor,
Clarke Thatcher, Wayne Throop, Chris Torek, Steve Traugott, Brian Trial,
Nikos Triantafillis, Ilya Tsindlekht, Andrew Tucker, Goran Uddeborg,
Rodrigo Vanegas, Jim Van Zandt, Momchil Velikov, Wietse Venema, Tom
Verhoeff, Ed Vielmetti, Larry Virden, Chris Volpe, Mark Warren, Alan
Watson, Kurt Watzka, Larry Weiss, Martin Weitzel, Howard West, Tom
White, Freek Wiedijk, Stephan Wilms, Tim Wilson, Dik T. Winter, Lars
Wirzenius, Dave Wolverton, Mitch Wright, Conway Yee, James Youngman,. | http://www.faqs.org/faqs/C-faq/faq/ | CC-MAIN-2013-20 | refinedweb | 5,410 | 67.86 |
Assigned: Apr. 16
Due: Apr. 23
Note: I will be grading this, rather than the grader, so if you submit this by email, send it to davise@cs.nyu.edu.
The forward chaining algorithm involves the repeated application of the two inference subroutines, "fc-infer-fact", and "fc-infer-rule", defined below, which it runs until no new conclusions can be drawn.
fc-infer-fact(in F : fact; R : rule with one literal in the conditions; out G : fact) Let R have the form "A => C" If R uses some of the same variables names as F, then rename the variables; if F matches A under variable binding B then G := the application of B to C end fc-infer1 fc-infer-rule(in F : fact; R : rule with more than one literal in the conditions; out Q : rule) Let R have the form "A1 & A2 ... & Ak => C" If R uses some of the same variables names as F, then rename the variables; If F matches A1 under variable binding B then Q := the application of B to "A2 & ... & Ak => C" end
For instance if you start with
Fact F1: man(socrates) Rule R2: man(X) => mortal(X)fc-infer-fact will match the tail of R2 to F1 under the variable binding X -> socrates, and infer the new fact "mortal(socrates)".
If you start with
Fact F3: parent(elizabeth,charles) Fact F4: female(elizabeth) Rule R5: female(X) & parent(X,Y) => mother(X,Y)first, fc-infer-rule applies to F4 and R5 under X -> elizabeth to infer the new rule
Rule R6: parent(elizabeth,Y) => mother(elizabeth,Y)Second, fc-infer-fact applies to rule F3 and R6 under the binding Y -> charles to infer the new fact
Fact F7: mother(elizabeth,charles).
The entire forward chaining algorithm can be described as follows:
forward-chain(in out FF : set of facts; RR : set of rules) NEW := FF union RR; loop until NEW is empty { pop Z from NEW; if Z is a fact then loop for R in RR if R has form "A => C" and Z matches A then { fc-infer-fact(Z,R,G); if G is not in FF then { add G to FF; add G to NEW} endif } else if R has form "A1, A2 ... Ak => C" and Z matches A1 then { fc-infer-rule(Z,R,Q); if Q is not in RR then { add Q to RR; add Q to NEW} endif } endif endloop elseif Z is a rule of the form "A => C" then loop for F in FF if F matches A then { fc-infer-fact(F,Z,G); if G is not in FF then { add G to FF; add G to NEW} endif } endif endloop elseif Z is a rule of the form "A1 ... Ak => C" then loop for F in FF if F matches A1 then { fc-infer-rule(F,Z,Q); if Q is not in FF then { add Q to RR; add Q to NEW} endif } endif endloop endif } endloop end forward-chain
A. Trace what happens when the forward chaining algorithm is applied to the following knowledge base:
Facts: F1: parent(elizabeth,charles). F2: parent(philip,charles). F3: parent(elizabeth,anne). F4: parent(philip,anne). F5: parent(charles,william). F6: parent(charles,harry). F7: female(elizabeth). F8: male(philip). F9: male(charles). F10: female(anne). F11: anc(X,X). Rules: R1: parent(X,Y) => child(Y,X). R2: child(X,Y) => parent(Y,X) R3: child(X,Y) & female(X) => daughter(X,Y). R4: parent(X,Y) & anc(Y,Z) => anc(X,Z).Your trace should show every call to "fc-infer-fact" and "fc-infer-rule" that generates a new fact or rule.
B. It is possible to prove that, for a Datalog knowledge base, the algorithm "forward-chain" is complete with respect to the inference of facts. That is, if F is a fact that is a logical consequence of FF and RR, then F will be returned in the set of facts returned by forward-chain(FF,RR). Give an example to show that "forward-chain" is not complete with respect to the inference of rules; that is, an example of a set of facts FF, a set of rules RR and a conclusion Q such that Q is a logical consequence of FF and RR, but Q is not in the set of rules returned by forward-chain(FF,RR).
A. As far as is possible, write down the contents of the text in a set of formulas of the form "holds(S,F)" where S is a situation and F is a fluent (in an English language description); "occurs(S1,S2,E)" where S1 and S2 are situations and E is an event (in an English language description); and purely temporal relations between situations (e.g. "S5 occured before S4"; "S6 was less than an hour after S7" etc.)
B. Give three examples of queries that could be answered from your representation.
C. Is there any significant temporal information in this narrative that you have not been able to express in this notation? | http://cs.nyu.edu/courses/spring01/V22.0480-002/hwk7.html | CC-MAIN-2014-52 | refinedweb | 854 | 54.49 |
kbind—
#include <sys/unistd.h>
struct __kbind { void *kb_addr; size_t kb_size; }; #define KBIND_BLOCK_MAX 2 /* powerpc and sparc64 need 2 blocks */ #define KBIND_DATA_MAX 24 /* sparc64 needs 6, four-byte words */
kbind(const struct __kbind *param, size_t psize, int64_t cookie);
kbindsyscall updates the contents of one or more blocks of the process's memory with the supplied replacement data. This is used to efficiently and securely perform lazy-binding. param points to an array of __kbind structures giving the addresses and lengths to update. The last __kbind structure is immediately followed in the same order by the source data for the blocks to copy. psize specifies the total length of the parameters: both the __kbind structures and the associated source data. There may be at most
KBIND_BLOCK_MAX__kbind structures and each block may be at most
KBIND_DATA_MAXbytes in size.
kbindupdates memory “as if” the thread temporarily made the memory writable with mprotect(2). If the process does not have write access to the underlying memory object,
kbindwill fail without making the requested change.
kbindis currently intended for use by ld.so(1) only. It is therefore not provided as a function and two security checks are performed to bind it (pun intended) to its use in ld.so(1): the first time
kbindis used, the kernel records both the text address of the call and the value of the cookie argument. If those values differ in a later
kbindcall, then the process is killed.
kbind() will fail if:
ENOMEM]
EINVAL]
kbindlimits.
EFAULT]
kbindsyscall is specific to the OpenBSD dynamic linker and should not be used in portable applications.
kbindsyscall appeared in OpenBSD 5.8. | http://man.openbsd.org/kbind.2 | CC-MAIN-2018-39 | refinedweb | 271 | 63.49 |
On Fri, February 17, 2012 03:22, H. Peter Anvin wrote:> On 02/16/2012 06:16 PM, Andrew Lutomirski wrote:>>>> Is there really no syscall that cares about endianness?Perhaps when 64-bit syscall args are passed via two 32-bit registers.But that is no argument to make all argument accesses endianness aware.>> Even if it ends up working, forcing syscall arguments to have a>> particular endianness seems like a bad decision, especially if anyone>> ever wants to make a 64-bit BPF implementation. (Or if any>> architecture adds 128-bit syscall arguments to a future syscall>> namespace or whatever it's called. x86-64 has 128-bit xmm>> registers...)>>>> Not to mention that the reshuffling code will add totally unnecessary> cost to the normal operation.There is no such extra cost.> Either way, Indan has it backwards ... it> *is* one field, the fact that two operations is needed to access it is a> function of the underlying byte code, and even if the byte code can't> support it, a JIT could merge adjacent operations if 64-bit operations> are possible -- or we could (and arguably should) add 64-bit opcodes in> the future for efficiency.It is a virtual data structure with as sole purpose to provide syscallinfo to the byte code. The actual data structure as such never existsin memory. So giving something that is hard to digest is silly.A JIT won't be able to merge accesses because it also has to merge otherinstructions and recognize when 64-bit operations are done with 32-bitinstructions. I think that will be too hard for a JIT.The only good reason to use 64 bit fields is if 64-bit support will beadded to BPF in the future. If not, then it's just unnecessary pain forno good reason.An alternative to struct seccomp_data would be to add special instructionsthat load the desired info to 'A'. E.g. BPF_S_ANC_SYSCALL_ARG with 'k'selecting which arg. But that's probably harder to fit into the currentfilter code.Greetings,Indan | http://lkml.org/lkml/2012/2/16/609 | CC-MAIN-2014-15 | refinedweb | 342 | 64.91 |
/* * qchannel: qchannel.h,v $ * Revision 1.4 2005/11/30 12:47:37 csoutheren * Removed tabs, reformatted some code, and changed tags for Doxygen * * Revision 1.3 2004/11/11 07:34:50 csoutheren * Added #include <ptlib.h> * * Revision 1.2 2002/09/16 01:08:59 robertj * Added #define so can select if #pragma interface/implementation is used on * platform basis (eg MacOS) rather than compiler, thanks Robert Monaghan. * * Revision 1.1 2001/07/10 03:07:07 robertj * Added queue channel and delay channel classes to ptclib. * */ #ifndef _QCHANNEL_H #define _QCHANNEL_H #ifdef P_USE_PRAGMA #pragma interface #endif #include <ptlib.h> /** Class for implementing a serial queue channel in memory. This implements a simple memory based First In First Out queue. Data written to an instance of the class may be read from the same instance at some later time. The queue will block the read for the Read Timeout if the queue is empty. Similarly a write will be clocked for Write Timeout if the queue is full. If there is any data to be read then it returns immediately with those bytes, so you must check the GetLastReadCount() to determine the actual number of bytes read and not rely on the count being passed into the read function. */ 00065 class PQueueChannel : public PChannel { PCLASSINFO(PQueueChannel, PChannel); public: /**@name Construction */ //@{ /** Create a new queue channel with the specified maximum size. */ PQueueChannel( PINDEX queueSize = 0 ///< Queue size ); /**Delete queue and release memory used. */ ~PQueueChannel(); //@} /**. ); /** Close the file channel. @return TRUE if close was OK. */ virtual BOOL Close(); //@} /**@name Queue manipulation functions */ //@{ /**Open a queue, allocating the queueSize bytes. */ virtual BOOL Open( PINDEX queueSize ///< Queue size ); /// Get the queue size. 00131 PINDEX GetSize() const { return queueSize; } /// Get the current queue length. 00134 PINDEX GetLength() const { return queueLength; } //@} protected: PMutex mutex; BYTE * queueBuffer; PINDEX queueSize, queueLength, enqueuePos, dequeuePos; PSyncPoint unempty; PSyncPoint unfull; }; #endif // _QCHANNEL_H // End Of File /////////////////////////////////////////////////////////////// | http://pwlib.sourcearchive.com/documentation/1.10.10/qchannel_8h-source.html | CC-MAIN-2017-22 | refinedweb | 315 | 65.93 |
Cloud Datalab is an interactive data analysis, visualization and machine learning tool. It enables you to author and run Python code in the form of notebooks. Notebooks bring together code, results of code execution including visualizations and documentation in a single file. They also allow you to capture a history of executions so you can iteratively refine your data analysis by utilizing previous execution results.
Cloud Machine Learning (ML) Engine is a managed service that lets you run TensorFlow-based models in a distributed fashion for training and prediction. It also provides a way to run training locally (e.g. on the VM running Datalab) so you can validate your model against a small sample of data before submitting a long-running training.
We're going to make use of a new feature of Google Cloud Platform called Google Cloud Shell, an interactive shell that can be used to manage your Cloud Resources and to do development work directly from the Google Developers Console.
Google. It also comes preinstalled with tools you'd often use. E.g. git, maven, java virtual machine (jvm), nodejs, python, npm.
To get started:
A Cloud Shell session opens inside a new frame at the bottom of the console and displays a command-line prompt.
Datalab is set up on a GCE VM. For that we need to specify the project and the zone where the VM is created. Typically Datalab is set up from your client machine (desktop/laptop) with Cloud SDK installed. Here we are going to use Cloud Shell as the client to run the installation commands.
Copy the project id from the left pane using the icon next to the text in Qwiklabs and paste it in place of
PROJECT_ID below if you haven't done so already in a previous section of this lab.
$ gcloud config set core/project PROJECT_ID
You can use the specified zone
us-central1-f. If you don't specify one, the subsequent command will provide a list and prompt you to pick one.
$ gcloud config set compute/zone us-central1-f
Now we can create a Datalab instance on a VM in the project and zone specified above. The code in the following sections will be running on that VM in Google Cloud. In the create command below,
regression is used as the VM and Datalab instance name. For this lab, we do not need a source repository to commit files to and the temporary account does not have permissions to create it so we will turn that off.
$ datalab create --no-create-repository regression
The previous command creates a connection to your instance. Use that connection to open your browser to the Cloud Datalab notebook listing page by selecting Cloud Shell Web preview→Change port→Port 8081.
You will need the following command only if you lose connection to Datalab for some reason.
$ datalab connect regression
In this step, you launched Cloud Shell and called some simple
gcloud commands to set up a Datalab instance.
Is this your first time using a Datalab? (If you're an experienced Datalab user or just finished trying out Datalab in another code lab, you can skip to the next section titled "Regression".)
Here are a few tips to help you get started:
When you start your Datalab, you are instructed to create a new notebook within your lab environment. You will then copy/paste code into your notebook, and run it. To write code with your new iPython notebook:
On the notebook listing page, navigate to the docs folder. Click on the notebook file named Hello World.ipynb. It will open up in a new tab.
In the notebook, click on the cell with Python code for printing hello world. Run the cell by pressing Shift+Enter or by clicking the
Run button in the menu bar at the top. You will see the text printed as a result of execution and a new, empty code cell will be created just below the printed text.
Click the empty cell and type the following code to see how visualization works. This code takes static values of numbers and their squares and plots a line chart.
import matplotlib.pyplot as pl
pl.plot([1,2,3,4,5], [1,4,9,16,25])
pl.axis([0,6,0,30])
pl.show()
Press Shift+Enter to run the code cell. Observe the output chart.
Now double click the text "Untitled Notebook" at the top of the notebook editing area. You will see markdown corresponding to the formatted text. Replace the text "Untitled Notebook" with the text "Hello".
Run the markdown cell by pressing Shift+Enter. You will see the formatted text again with the updated title.
In Cloud Datalab notebook listing page, click on the Home icon, and then navigate to datalab/
docs/samples/ML Toolbox/Regression/Census. View the list of notebooks. Then open the notebook titled "1
Local End to End.ipynb".
You will see a notebook with markdown (documentation) and code cells. Code cells are followed by execution results.
In Datalab, click on Clear | All Cells. Now, read the documentation and code in the notebook and execute each cell in turn. Check the output. Some of the cells may take some time to execute if they are doing sizeable amount of data processing. You will see a progress bar while the execution is in progress.
All the cells in this notebook used a local version of the Cloud ML Engine service. This allows one to iterate on preprocessing, model development using a sample of the data and then submit the jobs to the service with the full, unsampled set of data. Essentially same code can be executed with the service version instead of the local version by specifying a different parameter for training and prediction in the toolbox API.
Congratulations! You completed a regression model by preprocessing Census data, training a neural net using Datalab toolbox APIs that in turn use TensorFlow. You also tested the model and evaluated the results by using online and batch prediction.
Go back to the notebook listing tab and open the notebooks with "Service" in their names. These notebooks allow you to perform the same end-to-end steps in stages using Cloud ML Engine service so you can scale to large amounts of data. Read the notebooks and compare contents with the previously executed "Local End to End"notebook in a different browser tab. Execution of code cells in these notebooks is not recommended for a short lab as it is likely to take time and it will require more computing resources than is allowed for your project, especially if you are using a free trial account. | https://codelabs.developers.google.com/codelabs/cloud-ml-engine-sd-regression/index.html?index=..%2F..%2Fhadoop-summit | CC-MAIN-2017-13 | refinedweb | 1,117 | 63.49 |
On Sat, 29 Dec 2001, Geert Uytterhoeven wrote:> On Sat, 29 Dec 2001, [ISO-8859-1] Gérard Roudier wrote:> > On Fri, 28 Dec 2001, Geert Uytterhoeven wrote:> > > The sym-2 driver has a define for modifying the PCI latency timer> > > (SYM_SETUP_PCI_FIX_UP), but it is never used, so I see no corruption.> >> > By default sym-2 use value 3 for the pci_fix_up (cache line size + memory> > write and invalidate). The latency timer fix-up has been removed, since it> > is rather up to the generic PCI driver to tune latency timers.> >> > > Is this a hardware bug in my SCSI host adapter (53c875 rev 04) or my host> > > bridge (VLSI VAS96011/12 Golden Gate II for PPC), or a software bug in the> > > driver (wrong burst_max)?> >> > Great bug hunting!> >> > It is about certainly not a software bug in the driver. Any latency timer> > value should not give any trouble if hardware was flawless. Just the PCI> > performances could be affected.>>capabilities, for now. :-)Just it means that the 875 must release the PCI BUS if its GNT# signal isdeasserted by PCI arbiter and current transaction lasted 22 PCI cycles ormore since the assertion of FRAME#.If I remember correctly, the problem occurred when data is written to thedevice. Is it ok?If so, the MWI problem I pointed out in my previous posting is unlikely toapply. But, for user data DMA write, the 875 may execute Memory Read Lineor Memory Read Multiple Lines transactions. It would be interesting toknow if it makes difference disabling those capabilities.Setting to zero the PCI cache line register in the PCI configuration spacedoes force the chip not to use any of the cache line based PCItransactions. It is brute force but should work.In order to disable separately those features, some IO register bits mustbe set to zero. The faster way is to hack the driver (sym_hipd.c) at someplace, for example (entered by hand just for you): /* * Select all supported special features. * If we are using on-board RAM for scripts, prefetch (PFEN) * does not help, but burst op fetch (BOF) does. * Disabling PFEN makes sure BOF will be used. */ if (np->features & FE_ERL) np->rv_dmode |= ERL; /* Enable Read Line */ if (np->features & FE_BOF) np->rv_dmode |= BOF; /* Burst Opcode Fetch */ if (np->features & FE_ERMP) np->rv_dmode |= ERMP; /* Enable Read Multiple */#if 1 if ((np->features & FE_PFEN) && !np->ram_ba)#else if (np->features & FE_PFEN)#endif np->rv_dcntl |= PFEN; /* Prefetch Enable */ if (np->features & FE_CLSE) np->rv_dcntl |= CLSE; /* Cache Line Size Enable */ if (np->features & FE_WRIE) np->rv_ctest3 |= WRIE; /* Write and Invalidate */ if (np->features & FE_DFS) np->rv_ctest5 |= DFS; /* Dma Fifo Size */+ #if 0 /* Disable all cache line based features */+ np->rv_dcntl &= ~CLSE;+ #endif+ #if 1 /* Disable Read Line */+ np->rv_dmode &= ~ERL;+ #endif+ #if 1 /* Disable Read Multiple */+ np->rv_dmode &= ~ERMP;+ #endif+ #if 0 /* Disable Write and Invalidate */+ np->rv_ctest3 &= ~WRIE;+ #endifThis example disables Read Line and Memory Read Multiple. I just addedprovisions (#if'ed zero) for other bits that also apply to cache linebased transactions.Gérard.-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2001/12/29/172 | CC-MAIN-2013-20 | refinedweb | 528 | 61.67 |
Hello,
I am having a hard time getting the UCC UART running on my custom board with a LS1020A CPU. I use the Linux kernel from Freescale SDK version fsl-sdk-v2.0-1701 with a custom mainline U-Boot.
The driver gets loaded but I can neither send nor receive from the ttyQE devices. When sending, the driver takes some seconds before raising Shutdown timeout to the kernel log. When receiving just nothing happens.
From what I saw from some debug messages I added, it seems that the QUICC engine never clears the BD_SC_READY bit in the buffer descriptors and the driver does not receive any interrupts.
This is the important part of my device tree:
/dts-v1/;
#include "ls1021a.dtsi"
...
&uqe {
ucc1: ucc@2000 {
device_type = "serial";
compatible = "ucc_uart";
port-number = <1>;
rx-clock-name = "brg1";
tx-clock-name = "brg1";
};
ucc2: ucc@2200 {
device_type = "serial";
compatible = "ucc_uart";
port-number = <3>;
rx-clock-name = "brg2";
tx-clock-name = "brg2";
};
};
and this is the RCW (QE_TDMA and QE_TDMB should both be 2):
Reset Configuration Word (RCW):
00000000: 0608000a 00000000 00000000 00000000
00000010: 80000000 00407900 60044a00 21046000
00000020: 00000000 00000000 00000000 08000700
00000030: 20124900 04091340 00000000 00000000
What could I have missed? Please let me know if you need more information.
The typical reason for QE block not working as expected is a microcode missing.
QE block in this device does not have internal ROM and required microcode package to be loaded to internal RAM before QE block can be used. Please look QEIWRM.pdf Chapter 1 for details.
Have a great day,
Alexander
-----------------------------------------------------------------------------------------------------------------------
Note: If this post answers your question, please click the Correct Answer button. Thank you!
----------------------------------------------------------------------------------------------------------------------- | https://community.nxp.com/thread/445358 | CC-MAIN-2018-22 | refinedweb | 277 | 62.58 |
I recently ran into an issue with providing
style properties to custom React Native components written in TypeScript. When defining the type of the
style property, we were using the
ViewStyle and
TextStyle types provided by React Native.
interface Props { textStyle?: TextStyle; viewStyle?: ViewStyle; } class BlogPost extends React.PureComponent<Props> { render() { return ( <View style={this.props.viewStyle}> <Text style={this.props.textStyle}>Hello World</Text> </View> ); } } class Example extends React.PureComponent<Props> { render() { return ( <View> <BlogPost viewStyle={styles.x} textStyle={styles.y} /> </View> ); } }
This was good enough in most cases, but soon, we ran into the issue of passing multiple styles into a component. In this case,
style={[styles.x, styles.y]} would not be accepted by the TypeScript compiler.
We temporarily solved the issue by changing the
style types to
ViewStyle | ViewStyle[]. This solved more issues, but we quickly ran into another: passing in multiple conditional styles. For example,
style={[style.x, boldText ? style.bold : undefined]} would not work.
The Solution
After digging into the React Native Types file, we discovered that
View and
Text use
StyleProp<ViewStyle> and
StyleProp<TextStyle>. After applying this style type, the style prop on our custom components worked like the style prop on the View and Text components.
This type has allowed us to quickly and easily define style props for all of our custom components. If you’ve experienced similar issues, give it a try. | https://spin.atomicobject.com/2018/06/02/custom-components-react-native/ | CC-MAIN-2019-09 | refinedweb | 233 | 60.41 |
Playing whacking game with Accelerometer Sensor
Revision as of 11:06, 16 September 2012
Note: This is an entry in the Asha Touch Competition 2012Q3
This article explains how to write a simple and fun game using the Sensor API and Gesture API.
Series 40
Series 40 DP 2.0
Introduction
This article demonstrates the Gesture API and Sensor API using the context of a simple game called Whack-A-Bunny, that runs on Series 40 Full Touch devices. To play the game the users shakes the phone vertically (up/down). After shaking the phone a bunny will appear from a random hole - tap the bunny before it disappears to get points. The main game screens are shown below.
The article assumes that readers have a working knowledge of Java ME covering: basics, threads and timers, and graphics and Canvas.
Testing the game
The application can be downloaded and run on a touch device (source code and install files are here).
You can also use the sensor simulation from the SDK phone simulator to simulate the shaking of the phone. For this app, you could move the y-axis bar of the sensor simulation from left to right or vice versa, to simulate of flipping the phone vertically. To open, just click the following from the phone Emulator menu: Tools -> Sensor Simulation
Below is a screenshot of Sensor Simulation display, and hitting one of the bunnies using the phone simulator.
Source code
The key classes in this example are listed below: WhackaMainMidlet.java, WhackaMainMidlet.class, WhackGame.java, WhackGame.class
1. WhackaMainMidlet Midlet:
This class contains the code implementation for the "acceleration" movement of the phone with the use of accelerometer sensor.
The WhackaMainMidlet implements the DataListener interface to implement the Sensor API. The DataListener interface has only one method to be implemented, which we will explain it later. See DataListener interface for more details. Here's the part of the code in the startApp() method where we instantiate the WhackGame class (a GameCanvas object). This is set as a current display. Also in this code we open the acceleration sensor and set the DataListener object. Since this is a simple app, and we don't need a large data buffering because the app is not doing any critical performance and to conserve memory space also, then we just set The BUFFERSIZE to 1. You may adjust the BUFFERSIZE up to 256 for handling a larger data buffering. For more info about data buffering, see: SensorConnection .
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.sensor.*;
/**
* @author NoelAnonas
*/
public class WhackaMainMidlet extends MIDlet implements DataListener {
static int currentEvent = -1;
private static final int BUFFERSIZE = 1;
private SensorConnection sensor;
public void startApp() {
WhackGame wg = new WhackGame(this);
Display.getDisplay(this).setCurrent(wg);
sensor = openAccelerometerSensor();
if (sensor==null) return;
sensor.setDataListener(this, BUFFERSIZE);
The application implements the DataListener Interface and registers itself with the setDataListenermethod, the mode of retrieval of data from the sensor is asynchronous. See SensorConnection Interface for more details about the mode of retrieval of data. Below is the source code for the openAccelerometerSensor() method. Since the application would use the accelerator sensor of the device, we would use the "acceleration" as the quantity value of the findSensors method of SensorManager. For more information about SensorManager class you may visit this link: SensorManager Class. For other possible quantity value for finding sensors aside from our "acceleration" value to refer to Accelerometer Sensor, you may visit this link: Finding Sensors.
private SensorConnection openAccelerometerSensor(){
SensorInfo infos[] = SensorManager.findSensors("acceleration", null);
if (infos.length == 0) return null;
try{
return (SensorConnection)Connector.open(infos[0].getUrl());
}catch(Exception e){
e.printStackTrace();
System.out.println("Problem in opening the accelerometer Sensor. "+ infos[0].getUrl());
return null;
}
}
Once the DataListener bound to the target object (midlet), the dataReceived() method will be called for each acceleration action done on the phone device. The dataReceived() method is the implementation of the abstract method of the DataListener interface.
The x,y and z data coordinates of the phone acceleration can be determined using the array of Data type argument of dataReceived() method. We are only looking for vertical acceleration movement, i.e. the up and down action. See Data Interface for more details. To easily determine it, we convert the data to an int key action (convertToActionEvent() method).
public void dataReceived(SensorConnection sensor, Data[] data, boolean isDataLost) {
int[] events = convertToActionEvent(data);
for (int i=0; i<BUFFERSIZE; i++){
if (events[i] == currentEvent )
continue;
currentEvent = events[i];
}
}
For the data[0].getChannelInfo() method in convertToActionEvent() method, we used the value 0 for array of data to indicate the application uses the information of the first channel of the sensor. This method returns a ChannelInfo object. See the ChannelInfo. To get the y-coordinate value of the accelerometer sensor, we check first the return value of getDataType() method of the ChannelInfo object to see what particular data type would this ChannelInfo object produces . If the return data is int, then we use the data[1].getIntValues() else data[1].getDoubleValues() code will be used if the return data is double. The assigned index 1 of data-array variable refers to the y-axis direction of the accelerometer sensor. After getting this result data value, We use the getActionKey() method to convert the value to the desired int value, based on the vertical shake movement of the phone or the phone UI simulation, that is, if it is shaken upward and downward.
Code for the convertToActionEvent() method:
private static int[] convertToActionEvent(Data[] data){
ChannelInfo cInfo = data[0].getChannelInfo();
boolean isInt = false;
if (cInfo.getDataType() == ChannelInfo.TYPE_INT) isInt= true; else isInt= false;
int[] events = new int[BUFFERSIZE];
if (isInt){
int [] vint = data[1].getIntValues(); //index=1, getting the y-coordinate values only;
for (int i=0; i<BUFFERSIZE; i++){
events[i] = getActionKey(vint[i]);
}
return events;
}
double [] vdouble = new double[BUFFERSIZE];
vdouble = data[1].getDoubleValues();
for (int i=0; i<BUFFERSIZE; i++){
events[i] = getActionKey(vdouble[i]);
}
return events;
}
Below is the code for getActionKey() method. Based on this code, if the ycoord value is less than 0, it means the phone moved in upward position, and the return value of the getActionKey() method is the int value of Canvas.UP constant. If the ycoord value is zero or greater than 0 then the return int value is Canvas.DOWN constant. See Canvas.UP and Canvas.DOWN.
2. WhackGame Canvas:
This canvas contains the necessary code to display the game graphics, to capture the "acceleration" movement of the phone and to capture the gesture tap made by the user.
The "WhackGame" canvas class implements the Runnable interface for a thread object and the GestureListener interface for Gesture Tap. We need this Runnable in our application because we need another thread object that will monitor the data independently from the accelerometer sensor. For more info about Runnable interface, see: Runnable interface . For more info about Thread, see: Thread class .
To work the gesture tap to the game, we need the following procedures:
- Implement the gestureAction() method of the com.nokia.mid.ui.gestures.GestureListener interface. all codes relating to the tap activities/actions will be placed here.
- Instantiate the com.nokia.mid.ui.gestures.GestureInteractiveZone class with an argument of GestureInteractiveZone.GESTURE_TAP because we would just want to monitor the gesture tap only. The gesture tap is the same as pressing the touch-screen and releasing it quickly.
- Register the GestureListener object and the GestureInteractiveZone object to the GestureRegistrationManager. Use the the static register() method of GestureRegistrationManager to bind those two objects to the GestureRegistrationManager. This is use to register a gesture interactive zone to a container, which is our WhackGame object.
- And finally, use the GestureRegistrationManager.setListener(this, this) to add the listener object to the container. The reason why the value of the setListener() method is set to two "this" method is because the WhackGame object extends the GameCanvas class (container), and implements the GestureListener interface (listener).
For more info about registering the gesture, see GestureRegistrationManager .
import com.nokia.mid.ui.gestures.GestureEvent;
import com.nokia.mid.ui.gestures.GestureInteractiveZone;
import com.nokia.mid.ui.gestures.GestureListener;
import com.nokia.mid.ui.gestures.GestureRegistrationManager;
import java.io.IOException;
import java.util.Random;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
/**
* Title: Whack-A-Bunny
* @version 1.0
* @author NoelAnonas
*/
public class WhackGame extends GameCanvas implements Runnable, GestureListener {
WhackaMainMidlet bm1;
String msg = "";
Image bgd, hit, b1;
Image hole1;
int vscore, vspeed = 500, vkey = 0;
boolean bhit1, bhit2, bhit3, bhit4;
boolean unSplash;
int vrateappear=180;
boolean pullup, pulldown, show1, show2, show3, show4;
long hitdelay = 0, hitdelay2 = 0, hitdelay3 = 0, hitdelay4 = 0, timestart = 0;
public WhackGame(WhackaMainMidlet bm) {
super(true);
bm1 = bm;
//Set the game in fullscreen mode
setFullScreenMode(true);
try {
bgd = Image.createImage("/bg.jpg"); //background image
hit = Image.createImage("/hit1.png"); //whacked bunny image
hole1 = Image.createImage("/hole1.png"); //hole image
b1 = Image.createImage("/char1.png");
msg = "Score: ";
} catch (IOException ex) {
ex.printStackTrace();
}
GestureInteractiveZone giz = new GestureInteractiveZone(GestureInteractiveZone.GESTURE_TAP);
GestureRegistrationManager.register(this, giz);
GestureRegistrationManager.setListener(this, this);
//Create a thread object and run it.
Thread t = new Thread(this);
t.start();
}
We override the abstract method of GestureListener interface named GestureAction to accept the Gesture Tap data.
In this code, we check whether the Gesture Tap is within the designated area.
public void gestureAction(Object container, GestureInteractiveZone gZone, GestureEvent gEvent) {
switch (gEvent.getType()) {
case GestureInteractiveZone.GESTURE_TAP:
//Check if tap is within the area of the top-left bunny
boolean isInsideX11 = gEvent.getStartX() > 36 & gEvent.getStartX() < 90;
boolean isInsideY11 = gEvent.getStartY() > 136 & gEvent.getStartY() < 185;
//Check if tap is within the area of the top-right bunny
boolean isInsideX12 = gEvent.getStartX() > 187 & gEvent.getStartX() < 230;
boolean isInsideY12 = gEvent.getStartY() > 136 & gEvent.getStartY() < 185;
//Check if tap is within the area of the bottom-right bunny
boolean isInsideX21 = gEvent.getStartX() > 36 & gEvent.getStartX() < 80;
boolean isInsideY21 = gEvent.getStartY() > 230 & gEvent.getStartY() < 280;
//Check if tap is within the area of the bottom-left bunny
boolean isInsideX22 = gEvent.getStartX() > 187 & gEvent.getStartX() < 230;
boolean isInsideY22 = gEvent.getStartY() > 230 & gEvent.getStartY() < 280;
//Bunny is hit at the top-left bunny
if (isInsideX11 & isInsideY11 & show1) {
vscore += 10;
show1 = false;
bhit1 = true;
hitdelay = System.currentTimeMillis();
}
//Bunny is hit at the top-right bunny
if (isInsideX12 & isInsideY12 & show2) {
vscore += 10;
show2 = false;
bhit2 = true;
hitdelay2 = System.currentTimeMillis();
}
//Bunny is hit at the bottom-left bunny
if (isInsideX21 & isInsideY21 & show3) {
vscore += 10;
show3 = false;
bhit3 = true;
hitdelay3 = System.currentTimeMillis();
}
//Bunny is hit at the bottom-right bunny
if (isInsideX22 & isInsideY22 & show4) {
vscore += 10;
show4 = false;
bhit4 = true;
hitdelay4 = System.currentTimeMillis();
}
//draw all the images again
repaint();
break;
}
}
We also override the run abstract method of Runnable interface to run the other thread. This thread is used to monitor the current "acceleration" event data from the WhackaMainMidlet (WhackaMainMidlet.currentEvent) , and to display the Bunny image on the screen accordingly. It randomly generates a value for the appearance speed of the bunny. The pullup and pulldown variables are set to true if the user shakes the phone vertically. There's a random generator to determine what particular bunny to be displayed in a certain location. Using nextInt(2) of Random object, it randomly generates an int value between 0 (inclusive) and 1. The initial speed rate of appearing and disappearing of the bunny is 500 milliseconds. This will be changed after the initial use. The next speed rate will be determined by this formula: vspeed = 5 * (vrateappear + r.nextInt(120)) . This formula guaranteed that the speed rate to display a bunny is in the range of 900 and 1495 inclusively. See Random class for more info.
public void run() {
while (true) {
msg = "Score: " + vscore;
//Getting the value from the accelerometer
//the vkey will be used to check the shake direction of the phone (up/down).
vkey = WhackaMainMidlet.currentEvent;
if (timestart != 0) {
//Get the current time
long timenow = System.currentTimeMillis();
//Get the time difference between the time when the bunny appeared and the current time.
long diff = timenow - timestart;
//Check the time difference between the time when the bunny appeared and the given random time.
if (diff > vspeed) {
pullup = false;
pulldown = false;
show1 = false;
show2 = false; show3=false; show4=false;
timestart = 0;
Random r = new Random();
vspeed = 5 * (vrateappear + r.nextInt(120));
}
}
// Remove the whacked bunny if any.
removeHitImage();
//Enable pullup and pulldown variables if the phone is shaken upward or downward respectively.
switch (vkey) {
case Canvas.UP:
pullup = true;
break;
case Canvas.DOWN:
pulldown = true;
break;
}
// if the user shake the phone from down to up or vice versa, it will
// randomly display the bunny image to the screen.
if (pullup & pulldown) {
unSplash = true;
pullup = false;
pulldown = false;
Random r = new Random();
//if the random number is equal to 1 then display the bunny.
if (r.nextInt(2)==1) show1 = true;
if (r.nextInt(2)==1) show2 = true;
if (r.nextInt(2)==1) show3 = true;
if (r.nextInt(2)==1) show4 = true;
//reset the time for timestart
timestart = System.currentTimeMillis();
}
//Refresh the drawing area.
repaint();
}
}
Code for the removeHitImage() method mentioned from the run() method. This is used to clean the bunny that was hit. The vpause variable is used to provide the time delay to display the whacked bunny. In this example, the whacked bunny will be displayed for about 800 millisecond before it disappears.
//removing the hit bunny image after 800 millisecond
public void removeHitImage() {
int vpause =800;
//Remove the whacked bunny at the top-left corner
if (bhit1) {
if (System.currentTimeMillis() - hitdelay > vpause) {
bhit1 = false;
hitdelay = 0;
}
}
//Remove the whacked bunny at the top-right corner
if (bhit2) {
if (System.currentTimeMillis() - hitdelay2 > vpause) {
bhit2 = false;
hitdelay2 = 0;
}
}
//Remove the whacked bunny at the bottom-left corner
if (bhit3) {
if (System.currentTimeMillis() - hitdelay3 > vpause) {
bhit3 = false;
hitdelay3 = 0;
}
}
//Remove the whacked bunny at the bottom-right corner
if (bhit4) {
if (System.currentTimeMillis() - hitdelay4 > vpause) {
bhit4 = false;
hitdelay4 = 0;
}
}
}
To complete the code for this application, Here's the code of the paint() method. This is the area where the images and text are drawn. The drawString() method of the Graphics object is used to draw the text in a canvas, The reason why there's a space value of the string arguments of the drawString() method for the welcome screen is because we would like to put the text away from some dark image background and to put in a proper location. See the comments below for more code info.
public void paint(Graphics g) {
//Draw the background image.
g.drawImage(bgd, 0, 0, Graphics.LEFT | Graphics.TOP);
//Draw the hole image at the top-left corner
g.drawImage(hole1, 0, 160, Graphics.LEFT | Graphics.TOP);
//Draw the hole image at the top-right corner
g.drawImage(hole1, 150, 160, Graphics.LEFT | Graphics.TOP);
//Draw the hole image at the bottom-left corner
g.drawImage(hole1, 0, 260, Graphics.LEFT | Graphics.TOP);
//Draw the hole image at the bottom-right corner
g.drawImage(hole1, 150, 260, Graphics.LEFT | Graphics.TOP);
//display the bunny at top-left corner if the user shakes the phone vertically
if (show1) {
g.drawImage(b1, 10, 112, Graphics.LEFT | Graphics.TOP);
}
//if bunny was hit at top-left corner.
if (!show1 & bhit1) {
g.drawImage(hit, 10, 112, Graphics.LEFT | Graphics.TOP);
}
//display the bunny at top-right corner if the user shakes the phone vertically
if (show2) {
g.drawImage(b1, 160, 111, Graphics.LEFT | Graphics.TOP);
}
//if bunny was hit at top-right corner.
if (!show2 & bhit2) {
g.drawImage(hit, 160, 111, Graphics.LEFT | Graphics.TOP);
}
//display the bunny at bottom-left corner if the user shakes the phone vertically
if (show3) {
g.drawImage(b1, 10, 211, Graphics.LEFT | Graphics.TOP);
}
//if bunny was hit at bottom-left corner.
if (!show3 & bhit3) {
g.drawImage(hit, 10, 211, Graphics.LEFT | Graphics.TOP);
}
//display the bunny at bottom-right corner corner if the user shakes the phone vertically
if (show4) {
g.drawImage(b1, 160, 211, Graphics.LEFT | Graphics.TOP);
}
//if bunny was hit at bottom-right corner.
if (!show4 & bhit4) {
g.drawImage(hit, 160, 211, Graphics.LEFT | Graphics.TOP);
}
g.drawString(msg, 0, 0, Graphics.LEFT | Graphics.TOP);
//This is the Welcome Screen.
if (!unSplash) {
g.drawString("Shake Your Phone vertically ", 15, 196, Graphics.TOP|Graphics.LEFT );
g.drawString(" to bring Bunny out ", 15, 220, Graphics.TOP|Graphics.LEFT );
g.drawString(" from the hole. ", 15, 240, Graphics.TOP|Graphics.LEFT );
g.drawString(" Then start hitting ", 15, 300, Graphics.LEFT | Graphics.TOP);
g.drawString(" the Bunny! ", 15, 325, Graphics.LEFT | Graphics.TOP);
}
}
That's it! Have fun in playing this game.
Downloads
- Media:WhackaBunnySourceCode.zip - Full source code for the Whack-A-Bunny game
- Media:WhackaBunny.zip - Installation files for the device (zip contains .jad and .jar files)
Summary
Using the Gesture API and Sensor API is simple to implement once you know the basics of using it. | http://developer.nokia.com/community/wiki/index.php?title=%2525EF%2525BB%2525BFPlaying_whacking_game_with_Accelerometer_Sensor&diff=prev&oldid=172979 | CC-MAIN-2014-10 | refinedweb | 2,822 | 50.84 |
Low-level socket handling. More...
#include <time.h>
Go to the source code of this file.
Low-level socket socket.h.
Type of connection.
Definition at line 34 of file socket.h.
Close a socket.
Definition at line 97 of file socket.c.
Clear out any queued data.
The internal buffer is emptied and any data that has already arrived at this machine (in kernel buffers) is read and dropped.
Definition at line 313 of file socket.c.
allocate and initialise a new connection
Definition at line 280 of file socket.c.
Simple wrapper.
Definition at line 76 of file socket.c.
Checks whether reads would block.
Definition at line 192 of file socket.c.
read from a Connection
Definition at line 125 of file socket.c.
simple read buffering to speed things up
Definition at line 210 of file socket.c.
Read a line from a socket.
Definition at line 246 of file socket.c.
write to a Connection
Definition at line 138 of file socket.c.
Write data to a socket.
Definition at line 152 of file socket.c. | https://neomutt.org/code/socket_8h.html | CC-MAIN-2021-39 | refinedweb | 181 | 71.92 |
Copy New Files Only in .NET
Recently I had a client that had a need to copy files from one folder to another. However, there was a process that was running that would dump new files into the original folder every minute or so. So, we needed to be able to copy over all the files one time, then also be able to go back a little later and grab just the new files.
After looking into the System.IO namespace, none of the classes within here met my needs exactly. Of course I could build it out of the various File and Directory classes, but then I remembered back to my old DOS days (yes, I am that old!). The XCopy command in DOS (or the command prompt for you pure Windows people) is very powerful. One of the options you can pass to this command is to grab only newer files when copying from one folder to another. So instead of writing a ton of code I decided to simply call the XCopy command using the Process class in .NET.
The command I needed to run at the command prompt looked like this:
XCopy C:\Original\*.* D:\Backup\*.* /q /d /y
What this command does is to copy all files from the Original folder on the C drive to the Backup folder on the D drive. The /q option says to do it quitely without repeating all the file names as it copies them. The /d option says to get any newer files it finds in the Original folder that are not in the Backup folder, or any files that have a newer date/time stamp. The /y option will automatically overwrite any existing files without prompting the user to press the "Y" key to overwrite the file.
To translate this into code that we can call from our .NET programs, you can write the CopyFiles method presented below.
C#
using System.Diagnostics
public void CopyFiles(string source, string destination)
{
ProcessStartInfo si = new ProcessStartInfo();
string args = @"{0}\*.* {1}\*.* /q /d /y";
args = string.Format(args, source, destination);
si.FileName = "xcopy";
si.Arguments = args;
Process.Start(si);
}
VB.NET
Imports System.Diagnostics
Public Sub CopyFiles(source As String, destination As String)
Dim si As New ProcessStartInfo()
Dim args As String = "{0}\*.* {1}\*.* /q /d /y"
args = String.Format(args, source, destination)
si.FileName = "xcopy"
si.Arguments = args
Process.Start(si)
End Sub
The CopyFiles method first creates a ProcessStartInfo object. This object is where you fill in name of the command you wish to run and also the arguments that you wish to pass to the command. I created a string with the arguments then filled in the source and destination folders using the string.Format() method. Finally you call the Start method of the Process class passing in the ProcessStartInfo object. That's all there is to calling any command in the operating system. Very simple, and much less code than it would have taken had I coded it using the various File and Directory classes.
Good Luck with your Coding,
Paul Sheriff
** SPECIAL OFFER FOR MY BLOG READERS **
Visit for a free video on Silverlight entitled Silverlight XAML for the Complete Novice - Part 1. | http://weblogs.asp.net/psheriff/copy-new-files-only-in-net | CC-MAIN-2014-52 | refinedweb | 537 | 73.88 |
Created on 2010-07-13 21:29 by nvie, last changed 2017-10-18 18:58 by paul.j3.
**NOTE**: This is a re-post of
What steps will reproduce the problem?
parser = argparse.ArgumentParser()
sub = parser.add_subparsers()
sub.add_parser("info")
parser.add_argument("paths", "+")
parser.parse_args(["foo", "bar"])
What is the expected output? What do you see instead?
Expected behavior is that, failing to match one of the subparser inputs
("info"), the parser checks if the argument matches any of the top-level
arguments, in this case the 'paths' multi-arg. In other words, it should be
possible to make the subparser be optional, such that when the subparser
argument fails to retrieve any valid subparser, the remaining args are
parsed as if no subparser exists. At present, it does not seem possible to
make a subparser be optional at all.
Perhaps this could be exposed to the user as:
parser.add_subparsers(nargs=argparse.OPTIONAL)
or something to that effect. Or, allow a default subparser to be specified.
I.e.,
sub = parser.add_subparsers()
info = sub.add_parser("info")
main = sub.add_parser("main")
sub.default = main
I'm sure the point will come up that the current behavior is correct,
because given a subparser like "info", a user could easily make a mistake
like "myapp ino foo bar" and rather than get a safe error be given
something unexpected. For this reason, I think the default behavior is
usually going to be correct. BUT, it would still be nice if it could be
optional, so that developers could be free to make that call. Sometimes the
potential user errors aren't really an issue, and having to explicitly set
a subparse arg every time can be a nuissance.
Changed the title, so it shows that the feature request is for argparse.
I've added Steven as nosy so he knows this was reposted here. I've also set the priority to low. Personally I'm at least -0 on this, since if I use a command that has subcommands I expect to get an error if I supply an invalid subcommand. As you say, however, the command designer *could* be supplied with the opportunity to shoot themselves in the foot :)
The issue isn't going to go anywhere unless someone proposes a patch, though.
Actually, this is a rather common concept. Broadly used tools like for example Git use this kind of subcommand handling.
This command shows all remotes:
git remote (i.e. is like git remote list)
Showing/removing remotes is done using subsubcommands:
git remote show [...]
git remote rm [...]
That, in combination with the explicit design goal that "[argparse] isn't dogmatic about what your command line interface should look like" should be enough reason to be wanting this, in my humble opinion.
See also 9540, which has an alternate proposal (that I don't like as much) for how to handle parser arguments supplied after subparsers are declared.
Reviewing this, I'm now +1 on fixing this *somehow*, since clearly there is an ambiguity here that needs to be resolved.
Seems like there's minimally the bug that argparse should currently throw an error if you add an argument after subparsers (since that argument will never be parsed under the current semantics).
I do believe that supporting an optional command like the "git remote" example is useful, but as RDM suggests, this probably won't go anywhere unless someone proposes a patch.
To expand on my case from issue9540, I have a bunch of commands, each of which should enable a specific subset of options only available the individual command, but all of the commands share the same behavior in taking nargs='*' positional arguments:
./script.py --global-option command --command-option arg1 arg2 arg3
For example:
./backups.py -c /etc/tarsnap.conf make --no-expire job1 job2
If no positional arguments are given, all jobs defined in the config file are run. Or, in the above example, only "job1" and "job2" are run.
The positional arguments are the same for *all* commands. Now I can define them separately for each subparser, which is what I'm currently doing, but I kind of like having the global usage instructions (script.py -h) indicating the fact that positional arguments can be passed after the command.
In fact, right now I'm able to sort of achieve this by defining the positional nargs arguments both globally (to have them show in usage) and in each subparser (to have them parsed). This wouldn't be possible anymore if argparse where to throw an error after adding arguments after a subparser, although probably a more correct behavior.
Anyway, while the two issues are clearly related, I don't think that the two are necessarily mutually exclusive. argparse could allow both optional subparsers (if no subparser matches), as well as pass control back to the parent parser once an already matched subparser is no longer able to handle further command line input. Or optionally, support defining subparsers as "options only", so that positional arguments would always be handled by the parent parser.
Now, I can see how this could potentially become messy if we start talking about these positional arguments handled by the parent then being followed by more flags, which would then presumably also be handled by the parent etc. On the other hand, my use case doesn't seem that strange to me.
Stable releases don’t go into stable branches, so I’m editing versions. I also remove 3.3 since it doesn’t exist now, it means “this won’t go in 3.2”.
Wow, it is late. I wanted to write: New features don’t go into stable branches.
Trying to spec this, here is a proposed API:
parser = argparse.ArgumentParser()
sub = parser.add_subparsers(default='show')
sub_show = sub.add_parser('show')
sub_add = sub.add_parser('add')
If default isn't passed, the subcommand isn't optional.
If default is passed, and no explicit subcommand is given,
the default subcommand is picked.
Arguments are given to the top parser; passing arguments
to the subcommand requires naming it explicitly.
As far as motivation, I'd like to change a program that
uses --choice options (that can have a default) to use
more expressive subcommands. Some programs rely on implicit
subcommands a lot; the ip command on linux is a good
example..
I spent some time looking at this, as I was interested in
using this pattern to simulate what git and hg do. I
considered a few modifications and then found this bug. I
think the default keyword passed to
_SubParsersAction.__init__ makes sense.
I started on a patch, that looks promising, but I'm having
trouble getting the regexp right.
Here's a changeset higlighting where I think the
problematic regexp is:
Is the meager little test I put together.
I think this does the right thing.
If you can make your patch relative to the cpython source tree, and add a couple tests, it will be easier to review.
Thanks for working on this!
Ok, Steven, that sounds reasonable.
I checked out git-svn python and started comparing diffs... I'm a little confused. What version of argparse should be patched to provide this feature?
My HG version from seems to contain a version of argparse 1.2 while, my git-svn checkout of python seems to contain an argparse 1.1. Should I attempt to bring cpython's version up to date as well, or attempt to strip out the version bump changes?
You should work in the 3.3 standard library, i.e. on Lib/argparse.py in the default branch of the CPython Mercurial repository. See the devguide for more info. Thanks!
Thanks Eric. I was thrown by this document: which describes fetching the sources from SVN using git. I'm comfortable doing either, but it doesn't resolve my confusion.
The version of argparse in the python checkout is 1.1:
64 __version__ = '1.1' but differs from the SVN version.
whereas the argparse version available via google code is 1.2. The diffs indicate several changes not related to the change I'm attempting to make, which prevent my patch from applying cleanly. Looks like the HG version includes the 1.2 code... but I'm not sure why it would differ from SVN's trunk.
Ok, here's a rough attempt at stubbing this out against a python checkout. Will try to look at adding tests.
(BTW, subsequent GETs should not modify the bug tracker... this seems like a bug since GET should be idempotent, but SFTN from the double posting.)
Thanks for persevering in the face of VCS complications :) I have added a warning to the obsolete Git wiki page; I can’t do anything for the argparse Google code page. Anyway, trust us that argparse in the 3.3 stdlib is the place where development happens. (The Python Subversion repository is now dead.)
As for the tracker, well, its use of HTTP and URIs is somewhat idiosyncratic. It’s far from perfect and definitely not as elegant or REST-compliant that one could wish for. Anyway, it’s just a tool that serves us rather well; I’ve never seen a double submission issues like here before.
The implementation looks along the right track. Now it just needs some tests.
I sketched out a sloppy test earlier. I think this test is probably not quite comprehensive enough, and I'm not sure it fits into the python style either. I suppose there are other tests I can more or less copy.
Since [1] it seems like subparsers *are* optional by default. At least I get “error: too few arguments” for version 70740 of Lib/argparse.py, but no error for version 70741. It looks like this may be an unintentional side effect, since I see no mention of subparsers in #10424.
[1]:
um, this seems like a regression/bug? I now have users complaining that my apps are broken because of this change as of Python 3.3. My application is supposed to return the "help" screen when no command is given. Now I get a None error because argparse is not trapping this condition:
from argparse import ArgumentParser
parser = ArgumentParser(prog='test')
subparsers = parser.add_subparsers()
subparser = subparsers.add_parser("foo", help="run foo")
parser.parse_args()
$ python3.2 test.py
usage: test [-h] {foo} ...
test: error: too few arguments
$ python3.3 test.py
$
This seems very much like a major feature has been yanked away from argparse, now I have to check for this condition explicitly.
am I on the right issue here or do I need to open something new ?
I got the same issue that mike bayer with argparse doesn't throw error when subparser are missing.
Is it a bug which should be fixed in Python or in all python script? This sounds like an API break.
I think this problem arises from a change made in
Changeset to default (i.e. development) is
Near the end of _parse_known_args it removes a:
if positionals:
self.error(_('too few arguments'))
with a scan for required options that have not been seen.
Ordinary positionals are required. But a SubParsersAction is not required. So we no longer get a warning. changed this block of code as well. Notice the 2.7 and 3.2 branches have this 'too few arguments' error, but the default does not.
The default value for Action.required is False. In _get_positional_kwargs(), a positional's required is set based on nargs (e.g. '+' is required, '*' not). But add_subparsers() does not use this, so its 'required' ends up False.
This fudge seems to do the trick:
parser = ArgumentParser(prog='test')
subparsers = parser.add_subparsers()
subparsers.required = True
subparsers.dest = 'command'
subparser = subparsers.add_parser("foo", help="run foo")
parser.parse_args()
producing an error message:
usage: test [-h] {foo} ...
test: error: the following arguments are required: command
subparsers.dest is set so the error message can give this positional a name.
I'll try to write a patch to do something similar in argparse itself.
Further observations:
parser.add_subparsers() accepts a 'dest' keyword arg, but not a 'required' one. Default of 'dest' is SUPPRESS, so the name does not appear in the Namespace. Changing it to something like 'command' will produce an entry, e.g. Namespace(command=foo, ...). Is this a problem?
Assuming we have a clean way of assigning a name to 'subparsers', what should it be? 'command', '{cmd}', '{foo,bar,baz}' (like in the usage line)? This name also could be used when telling the user the subparser choice is invalid (parser._check_value).
This issue exposes a problem with '_get_action_name()'. This function gets a name from the action's option_strings, metavar or dest. If it can't get a string, it returns None.
ArgumentError pays attention to whether this action name is a string or None, and adjusts its message accordingly. But the new replacement for the 'too few arguments' error message does a ', '.join([action names]), which chokes if one of those names is None. There is a mutually_exclusive_groups test that also uses this 'join'. This bug should be fixed regardless of what is done with subparsers error messages.
So the issues are:
- making 'subparsers' a required argument
- choosing or generating an appropriate name for 'subparsers'
- passing this name to the error message (via _get_action_name?)
- correcting the handling of action names when they are unknown (None).
This patch addresses both issues raised here:
- throw an error when the subparser argument is missing
- allow the subparser argument to be optional
argparse.py:
_SubParsersAction -
add 'required=True' keyword.
name(self) method - creates a name of the form {cmd1,cmd2} for error messages.
_get_action_name() - try action.name() if it can't get a name from option_strings, dest or metavar. Still can return None.
2 error cases do a join on a list of action_names. If a name is None, this will choke. Add a ['%s'%x for x in list] guard.
test_argparse.py:
add cases to the subparser block to test the 'required' keyword, and to test the error message changes.
argparse.rst:
add a summary of the add_subparsers() arguments.
"msg113512 - (view) Author: Steven Bethard (bethard)
Seems like there's minimally the bug that argparse should currently throw an error if you add an argument after subparsers (since that argument will never be parsed under the current semantics)."
This isn't quite right. If the main usage signature is:
usage: PROG [-h] foo {one,two} ... baz
the parser._match_arguments_partial() method will allocate the 1st string to 'foo', the last to 'baz', and pass the rest to the subparser(s). It doesn't know how many the subparsers can use, but it knows that 'baz' requires one. From the standpoint of matching argument strings and arguments, a subparser is essentially a '+' positional.
On the other hand if 'baz' (the positional after the subparser) was '*' or '?' it would not get any strings.
If it is possible that subparser(s) doesn't need all the strings passed to it, the user could use 'parse_known_args', and deal with the unparsed strings themselves (possibly with another parser).
is answered by this change in how `required` arguments are tested, and how subparsers fell through the cracks.
Another Stackoverflow question triggered by this issue
My answer to
is getting a slow but steady stream of + scores; so the `required subparser` issue is still bothering people.
This particular question addresses the problem that the error message has when a required subparser is missing - it can't format the error with the default dest - SUPPRESS. The may be a another bug issue that addresses that.
Anyways, due to this continued attention, I'm going to raise the priority for this issue.
I've attempted to address some of the backward/forward compatibility issue with subparsers becoming optional by default (vs required by default in python2) with this pull request: (would love to get a review as well!)
I am now reviewing the PR added to the other issue by Anthony. This ticket has a lot of discussion; it would be good to check which parts are addressed by the other ticket, and particularly if the problems noted by Mike and others are now fixed.
My patch mainly addresses the regression pointed out by mike bayer (zzzeek)'s comment.
The other PR is now merged in 3.7, and won’t be backported (it changes default behaviour and adds a new param).
In a recent stackoverflow question a user wanted this optional-subparsers ability in Python 2.7.
Short of modifying the _parse_known_args method, the best I could suggest was a two stage parsing. That is, one parser without the subparsers. This uses parse_known_args, and if a 'cmd' is provided passes the 'extras' to one that handles subparsers.
---
Another issue which I don't think has been addressed is the 'usage' when subparsers are optional. At least with 3.5, subparsers are displayed with the choices: {'cmd1', 'cmd2', ...}, but no indication of being optional. An optional positional (with ? nargs) would normally be displayed as
prog [-h] [{'one', 'two'}] ...
My guess is that 'usage' adds the [] when positionals nargs='?', without regard to the 'required' attribute (I should verify this from code).
I'm undecided as to whether we want the brackets or not. It's more accurate, but makes the usage messier. And the 'help' grouping for 'optional-positionals' is the subject of other bug/issue(s).
I haven't checked it the patch has changed this behavior. | https://bugs.python.org/issue9253 | CC-MAIN-2017-47 | refinedweb | 2,913 | 66.84 |
Today we are going to talk about something which you may face when dealing with files. There are a lot of times when you have the need to merge two files in a project. So, today we are here to discuss about a programming solution of this problem.
We are assuming you are familiar with file handling operations like opening a file, closing a file. And different modes of doing it, but if you are not or you want to go though it once you can visit here (File Handling).
So, in simple terms we have two file's already created and we want to merge their content in a third file. Now let's dive into the solution.
Approach:
- We have to open the files so that we can fetch the content from there. (There are different modes we can open a file for eg. reading mode, writing mode, appending mode, truncate mode)
- So, we have to open file1 and file 2 in read mode and the third file in writing mode, so that we can write the content we get from file 1 and file 2.
- Fetch the content from file1 first and store it in a string and then push the value in file3.
- Repeat step 3 but with file2 now.
- Close all the files.
For fetching data from file we are going to use the
getline() function. The
C++ getline() is a standard library function that is used to read a string or a line from an input stream. The
getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered.
Code :
Note : We have already created 3 file's naming file1.txt, file2.txt with some content in these two of them and an empty file with name file3.txt
Content in file1.txt :
Content in file2.txt :
And the third file is empty.
Below is the implementation of the approach discussed.
//C++ code #include<bits/stdc++.h> #include<iostream> #include<fstream> using namespace std; int main() { fstream f1,f2,f3; string str1,str2; //str1 for fetching string line from file 1 and str2 for fetching string from file2 f1.open("file1.txt",ios::in);//opening file in reading mode f2.open("file2.txt",ios::in); f3.open("file3.txt",ios::out);//opening file in writing mode while(getline(f1, str1)){ //read lines from file object and put it into string and push back to file 3. f3<<str1; // inserting the fetched string inside file3 f3<<endl; } while(getline(f2, str2)){ //Same step for file 2 to file 3 fetching f3<<str2; f3<<endl; } f1.close(); f2.close(); f3.close(); }
Note: To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file. Also C++ automatically close and release all the allocated memory. But a programmer should always close all the opened files. | https://www.codesdope.com/blog/article/program-to-merge-contents-of-two-files-in-third/ | CC-MAIN-2021-39 | refinedweb | 485 | 81.93 |
Note: This is part is understand how to build a simple list react component and apply that knowledge to build
BlogPost component to list posts in a page.
JavaScript Prerequisite
Because creating List component ReactJS is advanced topic, it requires working JS knowledge in the following areas:
Part 1: JavaScript Fundamentals – Array.Map(), Arrow Functions & Functions
Part 2: How to Pass Props (Data Objects) to Component in ReactJS (this post)
Part 3: Creating List Component in reactJS
In this Part 2 of three parts series, what are props and how props objects are used to pass data from from one component to other is discussed.
React Component – A Review
In previous post Learning React – A Basic Overview commonly used JSX terms like JSX rendering elements, HTML attributes, embedding expression in JSX and React components (Functional and Class) were discussed briefly.
1. Functional Components
Functional components are simple JS functions. A simple react component can be created with function which contains some JSX statements as shown below:
//functional component function HelloWorld() { return <h1>Hello, World!</h1>; }
Functional components are not aware of other components (eg. state) and are suitable for stateless component. Multiple functional components can be combined with a single parental component. Functional components can’t received data from other components.
2. Class Components
Revisiting Class components discussed in previous post, unlike functional components Class components are slightly complex and are aware of other components (eg state). Class component return JSX elements using (required)
render() method.
// class component class HelloWorld extends React.Component { render(){ return <h1>Hello, World!</h1>; } }
The above two examples of components perform exactly same. Since the Class components are aware of state work, receive data from other components and pass data from one component to other.
3. Component Rendering
React renders JSX element to DOM node by passing both the element and “root” DOM node to
ReactDOM.render() as shown below:
//basic render() syntax ReactDOM.render(element, container[, callback]) //element rending to DOM const helloworld = <h1>Hello, world!</h1>; ReactDOM.render(helloworld, document.getElementById('root')); //OUTPUT Hello, World!
In the example above,
helloworld element (line 5) is pass to “root” DOM node container (line 6) which displays
Hello, World! in the browser (line 9).
React also renders pre-defined components to
ReactDOM.render() method by passing as as first parameter.
//syntax to initialize component to an element const welcome = <HelloWorld />; //call ReactDOM ReactDOM.render( {welcome}, document.getElementById("root") );
In the example above, pre-defined
HelloWorld components is initialized to an element named
welcome (line 2). The component is passed into ReactDOM as
{welcome} JSX expression as the first parameter (line 6) which calls
//functional component function HelloWorld() { return <h1>Hello, World!</h1>; } //render component ReactDOM.render( <HelloWorld />, document.getElementById("root") ); //OUTPUT Hello, World!
In the above example, the
ReactDOM.render() is called with
HelloWorld component as first parameter, then react calls the
HelloWorld component (lines: 2-4) returning
<h1>Hello, World!</h1>; to “
root” DOM node (line 9) and displaying
Hello, World! in the browser (line 13).
4. Complex Components
In previous post Learning to Work With React Components, creating more complex components, composing & splitting component into smaller components was discussed in detail.
Read More: Learning to Work With React Components
Props
At the beginning, props can be confusing. The React document describes
<strong>props</strong> as ” inputs to a React component. They are data passed down from a parent component to a child component.” From vanilla JS perspective, the react props are similar to global variables or objects.
1. Basic Syntax
How to pass data to React components? The following steps illustrates passing data in functional components:
a. Define Data With JSX Syntax
It is pass through using JSX syntax as attributes as shown below:
//comp props <HelloWorld someData={data.value} />
In the above example
HelloWorld is a component and
someData is an attribute. The data inside curly braces
{ } are expressions that must return value.
b. Access the Data via Props
The data are accessed through props in defined component.
//react component const HelloWorld = props => { <p>{props.someData}</p> };
In the above example,
someData attribute is accessed via props in the
HelloWorld component (line 5).
Read More: Embedding Expression in JSX
c. Rendering to React DOM
The
HelloWorld Component is pass to the
ReactDOM render() function, and the parameter which returns the HTML bulbs to each component.
2. Class Component
In class components, data are passed via props by defining attributes.
// syntax for declaring attributes <ExampleComponent exampleProp = "HelloProp" /> //syntax for accessing props this.props.exampleProp;
In the example above,
exampleProp prop with a value of
"HelloProp" is passed to the
ExampleComponent component (line 2).
A user-defined props can be accessed from inside a component class with
this.props.exampleProp syntax (line 5). From vanilla JS perspective, the
this.props is global object which stores components properties (props) and the props name (eg.
exampleProp) serves as object keys.
Tip: The functional components can access props directly as parameter and DO NOT need
'this' keyword. In Class components, the
'this.props' keyword syntax is required to access props.
Use Case Examples
Simple use cases of passing props data in functional components, Class components and passing default information with default props is illustrated below.
1. Passing Props Data with Components
In the following two examples, use of props to pass data (discussed in previous section) in functional as well as Class components is demonstrated.
// define functional component with props function WelcomeComp(props){ return( <div> {/*access data from props */} <h2>Welcome to {props.siteTitle}</h2> <p>I am from Functional component!</p> </div> ); } ReactDOM.render( // pass props value with component <WelcomeComp siteTitle = "React Blog" />, document.getElementById("root") );
In the example above, a functional component named
WelcomeCom with props is defined (lines: 2-10). In line 6, a prop named
siteTitle is defined using
props.siteTitle syntax as JSX attribute. The
siteTitle prop access its value
"React Blog" passed to the
WelcomeCom component in line 14. As also noted earlier, in functional components, props can access prop without the
this keyword.
In the example below, the same
WelcomeCom component is defined using Class component with props as shown below:
//using Class components class WelcomeCom extends React.Component{ render(){ return( <div> {/*access data from props */} <h2>Welcome to {this.props.siteTitle}</h2> <p>I am from Class component</p> </div> ); } } ReactDOM.render( // pass props value with component <WelcomeCom siteTitle = "React Blog" />, document.getElementById("root") );
In Class components, unlike functional components (line 6),
this keyword is required to access props data with
this.props.siteTitle syntax (line 23), where
siteTitle is name of the prop.
The
WelcomeComp defined with either function (lines: 6) or with Class (lines: 23) display exactly the same output shown below:
WelcomeComfunctional (A) and class (B) component rendered (left) and React console output (right).
In the screenshot above, browser outputs of
WelcomeCom component with Functional & Class component is shown (left). The React DevTools inspector output (right) shows stored value of
this.props.siteTitle (for Class) or
props.siteTitle (for functional) as
React Blog.
2. Passing Props Data with Class Components
In the previous section, how to pass and access data via props in a component was discussed. One of the main features of react component is that react component can refer to other components.
// Define primary (parent) component class BlogPosts extends React.Component{ render(){ return( <div> <h2>REACT BLOG</h2> <Posts author="Adam Levin" postId = "4243"/> </div> ); } } // define secondary (child) component class Posts extends React.Component{ render(){ console.log(this.props); return( <div> <h2>Welcome to React Blog Home</h2> <p>Written by: {this.props.author} | Post ID: {this.props.postId}</p> <p>Welcome to React Blog. This your first post. Edit or delete it, then start writing.</p> </div> ); } } ReactDOM.render( // passing props <BlogPosts />, document.getElementById("root") );
In the example below, using two components (primary and secondary), passing data from primary (parent) component to secondary (child) component as props is demonstrated. The
author and
postId data passed in
BlogPosts component (line 7) is accessed in child component
Posts via props (line 19). To better understand what is actually is stored in
this.props in
Posts component (line 19) an extra
console.log statement is added (line 15).
The above screenshot of react output shows
author &
postId information from
BlogPosts component is passed to
Posts (child) component. The React DevTools inspector output (right) shows stored value for
this.props (line 19).
The output of
Console.log in the browser confirm that
this.props is an object and contains both
author &
postId props pass to the
Posts component (shown below).
//console.log output (line 15) object { author: "Adam Levin", postId: "4243" }
3. Passing Props Data with Nested components
Passing props (eg. data or information, etc) from one component to another component is considered as one of the main highlights of the react component.
//define post data const postData = { title: 'My song title', author: 'Blake Shelton', gendre: 'Country', text: 'Contrary to popular belief, Lorem Ipsum is not simply random text.' }; //initialize Heading Component const Heading = props => { // console.log(props); return ( <h1>{props.siteTitle}</h1> ); }; //initialize Posts Component const Posts = props => { // console.log(props); return ( <div> <h2>{props.title}</h2> <p>Written by: {props.author} | Gendre: {props.gendre}</p> <p>{props.text}</p> </div> ); }; //initialize Blog (container) Component const Blog = props => { return ( <div> <Heading siteTitle="React Blog" /> <Posts title={postData.title} author={postData.author} gendre={postData.gendre} text={postData.text}/> </div> ); }; ReactDOM.render( <Blog />, document.getElementById("root") );
In the example above, some dummy data are defined in
postData as object with four properties (lines: 2-7). Two react components
Heading (lines: 9-14) and
Posts (lines: 16-25) are defined as functional components using ES6 arrow function.
In
Heading component, props object is used to render
siteTitle value as
props.siteTitle (line: 12) which will be passed from
siteTitle = "React Blog" value (line 30).
Likewise,
title,
author,
gendre and
text values (lines: 20-22) from postData (lines: 2-7) are passed to
Posts components with props object.
In
Blog component (a container) the
Heading and
Posts components are returned (lines: 30-35) and the props values are passed.
The
Blog component is rendered (lines: 40-43) to ReactDOM node in a
div container
root (line 42).
The above screenshot (right) shows
console.log output of
Heading component (line 10) where the
props.siteTitle is an object and logs its value as “
React Blog“. Likewise the
console.log output of
Posts component (line 17) shows that the props is an object which contains the values passed values (lines: 20-22).
The following flow chart explains how props data are processed and passed to react components. The chart was inspired by Trey Alexander Davis’s Handling Data with Props in React.
Passing Default Props to Components
The React Guide defines defaultProps as “a property on the component class itself, to set the default props for the class. This is used for undefined props, but not for null props.”
In the following
Greetings component with props is defined (lines: 2-4). A props named
name is defined with
props.name (line 2). The
name props access its value
"John" passed to the
Greetings component (line 7) and renders expected output
Hello, John (line 11).
//functional component function Greetings(props) { return <h1>Hello, {props.name}</h1>; } //pass props ReactDOM.render( <Greetings name="John" /> document.getElementById("root") ); //OUTPUT Hello, John
In the above example, if prop
name is not defined (line 15, as shown in example below) what happens? The browser outputs as undefined (line 19).
//pass props ReactDOM.render( <Greetings /> document.getElementById("root") ); //OUTPUT Hello, unidentified
This type of problems can be solved by passing a default value for props, in case it is not defined.
// Class Component class BlogTitle extends React.Component{ render(){ return( <div> {/* define default prop - siteTitle */} <h1>Title of My Blog is - {this.props.siteTitle}</h1> </div> ); } } // define default props for BlogTitle BlogTitle.defaultProps = { siteTitle: "React" } ReactDOM.render( <BlogTitle />, document.getElementById("root") ); //OUTPUT Title of My Blog is - React
In the example above,
defaultProps named
siteTitle is defined for
BlogTitle class component (lines: 13-15) and accessed from
BlogTitle component using
this.props.siteTitle statement (line 7).
Default values for the props can also be defined with JSX syntax using logical
OR (
|| ) operators as fall back default values (as shown below). If the
siteTitle props value is not defined, it will be set by default to
'React'.
//define default prop value 'React' <h1>Title of My Blog is - {this.props.siteTitle || 'React'}</h1>
Other methods of setting default props value are discussed in React Guide: default props values & default props.
Further Reading: React Props by default value | Robin Wieruch
Wrapping Up
In this part 2 of the three-part essential prerequisite post series before deep diving into Creating List React component, what are props, how they are used in react components and some use cases were discussed. In Part 3: Learning to Create List React Component, more detail on listing array objects using
array.map() method will be discussed.
Acknowledgment: This post was inspired by Robin Wieruch’s How to pass props to components in React and case examples from the GeeksforGeeks articles on ReactJS on Props Set 1 and set 2.
NEXT POST: Creating List Component in ReactJS
Useful Resources and Links
While preparing this post, I have referred the following references extensively. Please to refer original posts for more detailed information. | https://tinjurewp.com/jsblog/understanding-how-props-are-passed-to-react-component/ | CC-MAIN-2022-05 | refinedweb | 2,223 | 50.33 |
Java @SafeVarargs Annotation
Last modified: May 7, 2019
1. Overview
In this quick tutorial, we’ll have a look at the @SafeVarargs annotation.
2. The @SafeVarargs Annotation
Java 5 introduced the concept of varargs, or a method parameter of variable length, as well as parameterized types.
Combining these can cause problems for us:
public static <T> T[] unsafe(T... elements) { return elements; // unsafe! don't ever return a parameterized varargs array } public static <T> T[] broken(T seed) { T[] plant = unsafe(seed, seed, seed); // broken! This will be an Object[] no matter what T is return plant; } public static void plant() { String[] plants = broken("seed"); // ClassCastException }
These problems are tricky for a compiler to confirm, and so it gives warnings whenever the two are combined, like in the case of unsafe:
warning: [unchecked] Possible heap pollution from parameterized vararg type T public static <T> T[] unsafe(T... elements) {
This method, if used incorrectly, like in the case of broken, will pollute an Object[] array into the heap instead of the intended type b.
To squash this warning, we can add the @SafeVarargs annotation on final or static methods and constructors.
@SafeVarargs is like @SupressWarnings in that it allows us to declare that a particular compiler warning is a false positive. Once we ensure our actions are safe, we can add this annotation:
public class Machine<T> { private List<T> versions = new ArrayList<>(); @SafeVarargs public final void safe(T... toAdd) { for (T version : toAdd) { versions.add(version); } } }
Safe use of varargs is a tricky concept in and of itself. For more information, Josh Bloch has a great explanation in his book, Effective Java.
3. Conclusion
In this quick article, we saw how to use the @SafeVarargs annotation in Java.
The full source code for the examples can be found over on GitHub.
The final example does not return a List.
Thanks! The example has been fixed. | https://www.baeldung.com/java-safevarargs | CC-MAIN-2019-22 | refinedweb | 315 | 54.42 |
Type: Posts; User: Rich1e1990
cheers lads never done much of this **** before really just tryin to get my head round
This is the way it should be?... I was also wondering what way I would go about adding a total row along the bottom?
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace...
Here is the question I am trying to do
Write a program that prints a table of values such as the one below for all numbers starting at 1 and up to and including a number which will be input from...
Hey I am looking to create a table somthing like this output below but I am very new to this and my code is abit everywhere.
x sqrt(x) x ^ 2 x ^ 3
========================================
1 1... | http://forums.codeguru.com/search.php?s=22d6174b0c6c6e57097759db5261dfb2&searchid=5374919 | CC-MAIN-2014-42 | refinedweb | 129 | 75.34 |
I'm trying to build a new plug-in following the instructions found in [1]:
Let’s write a “Hello, World!” plugin for Sublime Text 2:
Select Tools | New Plugin… in the menu.
Save to Packages/User/hello_world.py.
which results in the following generated code:
- Code: Select all
class ExampleCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.insert(edit, 0, "Hello, World!")
However, nothing happens when I try it out by following these directions:
You’ve just written your first plugin. Let’s put it to use:
Create a new buffer (Ctrl+n).
Open the python console (Ctrl+`).
Type: view.run_command("example") and press enter.
You should see the text “Hello, World!” in your new buffer.
In particular, when I when I execute view.run_command("example"), nothing happens. That is, "Hello, World!" does not show up in file, and the only thing printed in the Python console is: >>> view.run_command("example").
I'm at a loss as what to do at this point. I'd be grateful for any suggestion.
Thanks,
Roger Alexander.
1. ... ugins.html | http://www.sublimetext.com/forum/viewtopic.php?f=3&t=8988&p=36441 | CC-MAIN-2015-18 | refinedweb | 178 | 63.25 |
Terminal-Leetcode is a terminal based leetcode website viewer.
This project is inspired by RTV.
After finishing your code, press
s at quiz detail view to submit your code to leetcode.
You can company tag to terminal-leetcode home view column. The tag file is in JSON format which can be easily
edit and share. You can find tag file of Facebook from tags directory.
Install with pip
pip install terminal-leetcode
Clone the repository
git clone cd terminal-leetcode sudo python setup.py install
Need to install lxml dependencies first on Ubuntu.
apt-get install libxml2-dev libxslt1-dev python-dev
To run the program, input
leetcode in terminal
leetcode
This option will get your cookies from your browser and use those for any requests agains leetcode website. So you need to sign in your account from your browser first. There may be some limitations, please refer to pycookiecheat for its documentation
To login you need to create a config.cfg file in folder ~/.config/leetcode.
Input your username and password in config.cfg as:
[leetcode] username=chishui password=123456
Then restart this program.
You can set your programming language in config.cfg as:
[leetcode] ........ language=Java
to see default sample code in quiz detail view in your favorite language.
Please make sure to use Leetcode supported programming languages and use the string exactly the same as it appears in Leetcode.
You can customize your "Tag" column by adding a json file named tag.json into ~/.config/leetcode folder.
The format of tag.json is showed below:
{ "1" : ["F", "G"], "10" : ["F"], ...... }
By adding this file, quiz 1 will have a "F" and "G" tag and quiz 10 will have a "F" tag.
You can use this feature to add company tag on quizzes.
I have added a "F" tag sample file in "tags" folder. You could try this file to see all "F" tag quizzes.
Terminal-Leetcode allows you to open editor to edit default code you are viewing.
You can set your code editing settings in config.cfg as:
[leetcode] ........ ext=java # file extention path=~/program/leetcode # code file directory
Then when you are in quiz detail view, press
e to open editor to edit code sample.
Code sample is saved into directory you set in config.cfg automatically with file name combined with quiz id and file extension you set.
Default editor is vim, you can set
export EDITOR=*** to change editor. You can refer to
this article
to use Sublime Text as command line editor.
If you're using Terminal-Leetcode inside of a tmux session, when you press
e, current tmux window will be
splitted vertically and an editor is opened inside the new created tmux pane.
This feature could be turned on and off by config option in config.cfg as:
[leetcode] ........ tmux_support=true/false
Note that when you press
e in detail view, all other panes in current tmux
window except for the detail pane will be closed before the new edit pane is
created, so that you can edit solution for another problem seamlessly without
manually exiting vim and closing the edit pane.
Two code snippets can be used when creating code file.
You can create files
before and
after in
~/.config/leetcode/snippet. Code snippet in
before
will be placed at the beginning of the code file. Code snippet in file
after will be placed at the end of
the code file.
Like in C++, write
#include <iostream> #include <vector> using namespace std;
in file
before and
int main() { Solution s; }
in file
after, then you can view code of quiz (take quiz 123 for example) as:
#include <iostream> #include <vector> using namespace std; class Solution { public: int maxProfit(vector<int>& prices) { } }; int main() { Solution s; }
It becomes much easier to write your solution code and then test your solution.
makedirectly to compile your code.
Hto see help information.
upand
downto go through quiz list.
enteror
rightto see a quiz detail, and press
leftto go back.
Rin quiz list view to retrieve quiz from website.
PageUpor
PageDownto go to prev or next page.
Homeor
Endto go to the first or last quiz.
fin quiz list view to search quiz by id or title.
nin quiz list view to search next quiz with search text input before.
nwill always create a new sample code file.
tin quiz list view to add tag for quiz.
ein quiz detail view to open editor to edit code.
din quiz detail view to open discussion page in web browser.
Sin quiz detail view to open solutions page in web browser.
sin quiz detail view to submit your code.
1in quiz list view to sort quiz list by id.
2in quiz list view to sort quiz list by title.
3in quiz list view to sort quiz list by acceptance.
4in quiz list view to sort quiz list by difficulty.
h,
j,
k,
l,
ctrl+f,
ctrl+bare supported.
All kinds of contributions are welcome.
MIT | https://openbase.com/python/terminal-leetcode | CC-MAIN-2021-39 | refinedweb | 829 | 75.61 |
There is a new timing class called StopWatch which is in the .NET 2.0 framework in the System.Diagnostic namespace that is really handy for making timing measurements in your code. Previous managed code methods of doing timing like DataTime.Now() (which has a resolution of 10ms) or Environment.TickCount() (which has a resolution of 1ms) just didn’t have very good resolution in some cases. The StopWatch class now gives you the ability to have a resolution of nanoseconds which is comparable to the Win32 API calls of QueryPerformanceFrequency and QueryPerformanceCounter. So let’s look at some code that uses this new class.
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace StopWatchExe
{
class Program
{
static void Main(string[] args)
{
//initialize the stopwatch class
Stopwatch stopWatch = new Stopwatch();
List testList = new List();
//start the timer
stopWatch.Start();
for (int i = 100; i < 100; i++)
{
testList.Add(i.ToString());
System.Threading.Thread.Sleep(10);
}
//end the timer
stopWatch.Stop();
//get the elapsed time
TimeSpan timeSpan = stopWatch.Elapsed;
//write the time out.
Console.WriteLine(“Total time was: ” + timeSpan.ToString());
Console.ReadLine();
}
}
}
What the code is doing is creating the StopWatch class and then adding some random entries into a list. The pattern you will use is to start the StopWatch do some work then stop it. Then you have the ability to get the elapsed time represented by a TimeStamp value using the Elapsed property, the elapsed time in milliseconds using the ElapsedMilliseconds property and finally the number of ticks using the ElapsedTicks property. It was interesting that they didn’t have a nanosecond property which would have been helpful. In this sample you will see I used ToString to show the nanoseconds due to TimeStamp not having a property that could show that low of a value. | http://blogs.interknowlogy.com/2006/07/27/a-cool-new-timing-class-new-to-net-2-0/ | CC-MAIN-2022-21 | refinedweb | 302 | 58.79 |
Introduction to Python – Part 2
Teaching students how to visualize ocean data is a challenge. But before you get into cognitive theory, choosing colors, or the the principles of (good) visualization design, you really just need to get your students’ feet wet plotting some data.
This summer, as part our Virtual REU 2-week mini-workshop, we challenged students to work in groups to find interesting stories in the NDBC dataset. But before setting them off on their mini-research projects, we spent three sessions introducing students to python, NDBC data, and basic plotting.
As described in Part 1, in our first session we introduced students to python and the Google Colab environment. In the second session, students worked in groups to practice these basics, while making quick plots of the NDBC buoy data. Finally, in our third session, we demonstrated some python plotting basics using following notebook. If you’re curious, here are a few slides I also used as 30-second introduction to Data Vis.
Data Visualization Basics
The notebook below features some, but by no means all, of the ways you can create and customize plots in python, focusing primarily on timeseries plots.
The notebook briefly touches on customizing marks and lines, changing axes labels and limits, adding legends, and using subplots. Almost as an afterthought, I included a brief mention of scatterplots, histograms, and box plots, because those plots are so easy to make in python with just one line of code – assuming you know what you’re doing. I felt it was good to introduce students to a few additional plot types that are relevant to time series datasets, while also demonstrating the power of the tool to encourage students to explore more in the future.
It turns out, even simple isn’t that simple. As this was my first time teaching this skill to novice learners, I discovered quite a few hangups students can run into. Here are just a few:
- xarray vs. pandas – Both of these libraries are wonderful. While pandas is designed for “tabular” datasets, like those you find in Excel, xarray is a bit more complicated as it is designed to support multi-dimensional datasets. If your data is simple, like a CSV file with a timeseries or discrete data points, pandas is all you need. It has a far simpler data-model, and is a bit more intuitive for data analysis or visualization. Unfortunately, the NDBC dataset is served over THREDDS, which requires using the xarray library to access it. You’ll see in the notebook I ran through some hoops to convert the xarray Dataset to a pandas Dataframe, in the hopes that it might make the rest of the notebook easier to follow. But this was definitely not easy to get across to students at the very beginning. If you can, I’d suggest sticking with pandas-friendly datasets to start.
- Internal plotting functions – Both xarray and pandas have internal plotting methods that allow you to quickly create plots, without having to call matplotlib explicitly, e.g. with plt.plot(). These methods are also pretty “smart” in that they will label and title your graphs using information in your data, using column names and units if available. That’s a great feature, if you know how the black boxes work, but it’s yet another confusing point for students. For example, the syntax for
plt.plot(),
xr.Dataset.plot()and
pd.Dataframe.plot()can differ, depending on what you’re trying to do. While I love the internal methods, in the future, for a basic intro to plotting, I think I’ll start with matplotlib, and have students create graphs/axes/labels manually, allowing them to discover the benefits of the internal methods later.
- plot vs. scatterplot – This one is on me. For some reason, in this notebook, when I wanted to create a scatter plot, I used
plt.plot(x, y, linestyle='', marker='.')instead of just calling
plt.scatter(). While it’s good to remind students that there are often many way to solve a problem, especially in python, it’s also good to keep things simple to start.
- datetime – Dates and times are the bane of every programmer. Python has a lot of great tools for working with dates (some might argue too many), but you still have to figure them out. Sometimes that beautiful looking date-time array in your Dataframe isn’t actually datetime.datetime() friendly, but rather just an array of strings. To a human it looks the same. But to the computer, they’re totally different. And that takes some time to learn. That said, I have no idea how to teach this quickly or well, other than suggesting you make sure your datasets and examples are clear.
- NDBC Data – Finally, just a note on NDBC… I absolutely love this dataset, because the variables are familiar to students, it is (relatively) easy to access, and it has a global coverage allowing students to explore a variety of questions. However, like every other data portal out there, you can get confused the datasets that are actually available. On the homepage, NDBC lists over 1,400 stations, but only about 150 are meteorological buoys in the ocean. We had quite a few students interested in data from estuarine stations, tide gauges, and the TAO array. Sadly, not all of that data was as easy to access as the blue water buoys.
If I have a chance to teach an introduction to data visualization course in the future (ideally with more time), I hope to figure out some new approaches to these challenges. And if you have any ideas, I’d love to hear them too!
But in the end, I think students in our REU really appreciated having this notebook, with its collection of examples to refer to, as they worked on their own plots.
In fact, I hadn’t originally intended to include the two axes example in the notebook, but it was something students really wanted to know how to do. (In the data vis community, many have made arguments against duel axes charts, but they’re pretty common in oceanography.)
At any rate, if you are working on your own ocean/python/datavis introduction, I hope you find this notebook helpful!
This post is part of our 2020 Summer REU Intro to Python series. See also Part 1, Part 3, and Part 4.
Activity 2 - Data Visualization¶
2020 Data Labs REU
Written by Sage Lichtenwalner, Rutgers University, June 12, 2020
In this notebook we will cover some of basics of plotting in python, primarily using the matplotlib library. We've actually already used this library, as it is built into the pandas and xarray libraries to provide quick plotting capabilities. But if we want to customize our charts, it's often better to create them directly using matplotlib function calls.
The examples today will continue to use the mooring timeseries data available from NDBC in order to demonstrate timeseries, scatterplots, histograms and box plots.
For an example of other graph types commonly seen in oceanography, including profiles and TS diagrams, check out Bonus Activity 4, which demonstrates how to load and plot profile data from the ARGO drifter network.
# Notebook setup import xarray as xr !pip install netcdf4 import matplotlib.pyplot as plt
Requirement already satisfied: netcdf4 in /usr/local/lib/python3.6/dist-packages (1.5.3) Requirement already satisfied: numpy>=1.7 in /usr/local/lib/python3.6/dist-packages (from netcdf4) (1.18.5) Requirement already satisfied: cftime in /usr/local/lib/python3.6/dist-packages (from netcdf4) (1.1.3)
# Open dataset ds = xr.open_dataset('') # Subset the dataset to 1 year ds = ds.sel(time=slice('2019-01-01','2020-01-01'))
Convert Xarray Dataset to Pandas Dataframe¶
Yesterday we used the power of Xarray to load our NDBC dataset directly from a Thredds server. Xarray is great, especially when dealing with 3D or 4D datasets. But it can overcomplicate things. For example, our NDBC dataset actually loads with 3 dimensions (time, latitude and longitude), but we only need 1 (time).
Here are a few example plotting calls. Can you tell what's different in the output for each?
# Built in xarray plotting # ds.sea_surface_temperature.plot(); # Plot using matplotlib - This won't work # plt.plot(ds.sea_surface_temperature); # Plot using matplotlib - This will, but the units are wrong # plt.plot(ds.sea_surface_temperature.squeeze()) # Plot using matplotlib - Correctly plotted with time # plt.plot(ds.time,ds.sea_surface_temperature.squeeze());
To simply things, we can convert our Xarray Dataset to a Pandas Dataframe, which will give use something like a spreadsheet of columns for each variable, and rows for each measurement time.
Here's how easy it is to convert.
# Convert to Pandas Dataframe df = ds.to_dataframe() df.head()
Unfortunately, there's still a bit of complexity here because of the multi-dimensional index. If we try to plot this now, we get some crazy labels.
df.sea_surface_temperature.plot();
Here's how we can properly convert this Dataset to a Dataframe.
# Convert to Pandas Dataframe df = ds.to_dataframe().reset_index().set_index('time') df.head()
# Yes, even Pandas has built in plotting df.sea_surface_temperature.plot();
And now we're off to the races (again).
df[['air_temperature','sea_surface_temperature','wind_spd']].to_csv('44025data.csv')
Customizing Lines¶
Here are some of the more common parameters you will typically use when creating your plot.
- linewidth - For example 0.5, 1, 2...
- linestyle - For example '-','--', or ':' or other basic or advanced styles
- color
- marker
- label - The name of the line, used in a legend (see the next section)
For reference and inspiration, you can also check out the Matplotlib Gallery.
# Line Example plt.plot(df.index,df.sea_surface_temperature, color='red', linewidth=3)
[<matplotlib.lines.Line2D at 0x7fada48629b0>]
# Custom Markers Example plt.plot(df.index,df.sea_surface_temperature, color='red', linestyle='', marker='d', markerfacecolor='b', markeredgecolor='g', markersize=5)
[<matplotlib.lines.Line2D at 0x7fada47ef320>]
# Your Turn - Create a graph of air temperature using blue dots
# Incomplete Example plt.plot(df.index,df.air_temperature, color='red') plt.plot(df.index,df.sea_surface_temperature, color='blue', label='Sea Surface Temp') plt.legend();
# Your Turn - Fix the legend, and add a title and y label to the above plot.
Customizing Time Axes Limits¶
There are a few ways you can change the x-axis limits when you are working with timeplots. By default, plots will show the full range of data, with a little bit of padding on each side.
To plot just the full Full Time Range of data, you can use
plt.xlim(df.index.min(),df.index.max())
To plot a Specific Time Range, you can use
plt.xlim(datetime.date(2017,4,1),datetime.date(2019,10,1))
Note you will need to run
import datetime first for this command to run.
When you customize date limits you may also need to rotate your tick labels to prevent them from overlapping. One solution that might work is
plt.xticks(rotation=45)
# Your Turn - Try changing the y and/or x limits for the above plot
# Subplot example fig, (ax1,ax2) = plt.subplots(2,1, sharex=True, figsize=(10,6)) df.air_temperature.plot(ax=ax1) df.sea_surface_temperature.plot(ax=ax1) df.wind_spd.plot(ax=ax2, marker='.',linestyle='',markersize=1) ax1.legend() ax1.set_ylabel('Temperature (C)') ax2.set_ylabel('Wind Speed (m/s)') ax1.set_title('NDBC Station 44025'); # Save the figure to a file fig.savefig('44025_example.png')
# Your Turn - Recreate the above plot with a 3rd or 4th subplot using other variables
# One way - Using a modified plot() call plt.plot(df.sea_surface_temperature,df.air_temperature, linestyle='', marker='.', markersize=3) # Another (better) way - Using scatter() # plt.scatter(df.sea_surface_temperature, df.air_temperature, s=3) plt.xlabel('Sea Surface Temperature (C)') plt.ylabel('Air Temperature (C)') plt.title('NDBC Station 44025 from 1/1/2019 to 1/1/2020');
# Your Turn - Create a scatterplot of winds vs. waves
One of the big advantages of the
.scatter() function, is that you can also color and size the dots based on a variable, rather than having them all be the same.
# Your Turn - Now try coloring it using temperature or time
Histogram¶
We can easily create histograms of a single variable. Use the
bins parameter to increase or decrease the number of data bins.
# We can also easily create histograms df['sea_surface_temperature'].hist(bins=50);
# Your Turn - Create a histogram of another variable
Box Plots¶
You can also create box plots of your data rather easily. You could also create violin plots.
# And boxplots df[['sea_surface_temperature','air_temperature','wind_spd']].plot.box(vert=False);
Bar Plots¶
Bar plots are a very common data visualization, but not typically used with this kind of dataset.
That said, a bar plot could be used to show monthly averages (more on how to calculate them tomorrow) or anomalies.
Here's a quick (albeit crude) example that shows the monthly averages for the dataset we've been working with.
df.sea_surface_temperature.resample('M').mean().plot.bar();
Obviously, we'd need to work on the date labels, but hopefully this gives you a general idea.
Two Axes on the same Plot¶
In addition to using subplots, some scientists like to plot two variables on the same graph. For example, you can create two y-axes using the left and right sides. Using 2 x-axes is also common with CTD profile plots.
Personally I'm not a huge fan of this, but it can be effective for some datasets and audiences, like your fellow scientists who are used to this typ of graph. Just don't try to plot more than 2 axes together, that's just heresy 😉
The following example uses 2 y-axes to plot both Water Temperature and Dissolved Oxygen from an estuarine site near Atlantic City. This was adapted from this example.
Also, noticed how we can load, subset and convert from xarray to pandas all in one line. This "chaining" of commands, is one of the great features of Python.
# Load a JCNERR Estuarine Station from NDBC nerr = xr.open_dataset('') nerr = nerr.sel(time=slice('2019-06-01','2020-06-01')).to_dataframe().reset_index().set_index('time')
# A graph with 2 Y-axes fig, ax1 = plt.subplots() ax2 = ax1.twinx() # Create a second axes that shares the same x-axis color = 'tab:red' ax1.plot(nerr.index, nerr.water_temperature, color=color) ax1.set_ylabel('Water Temperature (C)', color=color) ax1.tick_params(axis='y', labelcolor=color) color = 'tab:blue' ax2.plot(nerr.index, nerr.o2_saturation, color=color) ax2.set_ylabel('Oxygen Saturation (%)', color=color) ax2.tick_params(axis='y', labelcolor=color)
This graph would probably look a bit cleaner if we averaged the data a bit. But that's an exercise for another day.
Changing the default plot style¶
Finally, while the plots we've created in this notebook work well, we can also jazz them up a bit. We can use the
set feature in the seaborne library to customize the style of our plots. Out of the box, seaborne provides a number of options, including: darkgrid, whitegrid, dark, white, and ticks. The default (darkgrid) is pretty nice.
You can try this out by running the following cell to import the library and override the default plot settings. Then try rerunning the various plot commands above to see what it looks like.
# Let's make our plots pretty import seaborn as sns sns.set()
/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead. import pandas.util.testing as tm
Additional Resources¶
If you are interested in seeing some additional examples of the plotting features available in python, I encourage you to visit the following pages.
- Matplotlib Examples - See what else this library can do.
- Seaborn Gallery - A great library for creating good-looking common statistical graphs.
- Altair Example Gallery - A more advanced tool for creating interactive graphs.
- Python Graph Gallery - A great resource for learning about common data visualization styles and how to create them in python. | https://datalab.marine.rutgers.edu/2020/10/introduction-to-python-part-2/ | CC-MAIN-2022-40 | refinedweb | 2,671 | 57.27 |
Hi Everyone,
I have written a C code for toggling PB2 and OC0A for every 200 micro seconds. But the code didn't worked as expected.
I did appropriate registery setting. The didn't see any activity on OC0A and PB2. Please assist me.
#define F_CPU 8000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
int main(void)
{
DDRB |= (1<<DDRB3)|(1<<DDRB2); // set pin 3 as output
OCR0A = 0x19; // count value for 200us
TCCR0A |= (1<<WGM01)|(1<<COM0A0); //CTC mode,Toggle OC0A on Compare Match
TCCR0B |= (1<CS00)|(1<CS01); //64 prescaler
TIMSK0 |=(1<<OCIE0A); //Interrupt Enable for Timer/Counter0 Output Compare Match A
sei();
while(1)
{}
}
ISR(TIMER0_COMPA_vect)
{
PORTB ^= (1<<PORTB2); //Toggles PB2
}
Just checking but what are you using to monitor the output signal? Even with /64 at 8MHz the signal will switch so fast it would be impossible to see with anything but a device such as scope or logic analyser. If it was an LED, for example, then if you slowly varied OCR0A in the while(1) loop you would see its brightness change.
Which model of AVR by the way?
Top
- Log in or register to post comments
Hi,
I am using digital oscilloscope for monitoring PB2 and OC0A.
Top
- Log in or register to post comments
The mistake is that you use < instead of << in the following line
Also make sure that you set OC0A pin as output (I'm not sure which device you use)
"For every effect there is a root cause. Find and address the root cause rather than try to fix the effect, as there is no end to the latter."
Author Unknown
Top
- Log in or register to post comments
Oops... Thats the mistake.
I am Using ATmega 324P and i declared OC0A as output pin.
Thank You.
Top
- Log in or register to post comments | https://www.avrfreaks.net/forum/timercounter0-output-compare-match-isr-not-getting-executed | CC-MAIN-2020-29 | refinedweb | 308 | 72.36 |
PSoC 5LP, project with outsourced functionscontent.librarian Nov 29, 2016 6:00 AM
Hello,
I am writing a program for PSoC 5LP (Prototyping Kit) working with the RGB-sensor VEML6040 by Vishay.
I try to outsource most of the functions and only have the core-code remaining in the file main.c. So i created two files: veml6040.h and veml6040.c and added them to the project (in header and source files).
Extract from veml6040.h
#include "veml6040.c"
#include "main.c"
#include <project.h>
// definitions
// function headers
extract from veml6040.c
#include "veml6040.h"
uint16_t ReadSensor(uint8_t CommandCode)
{
// awesome code
}
// other functions ...
When i do so and i change the files following message appears (translated from german by me):
The file cannot be saved: (The process cannot access file "C:\Users\username\Documents\PSoC Creator\PSoC5LP-VEML6040\PSoC5LP-VEML6040.cydsn\main.c", because another process is accessing it.)
None of the files can be saved (not even main.c). Also the Build ends with the PSoC Creator crashing.
When i remove the files from the project, everything works fine again.
Can someone help me with this problem?
Best regards,
Jeroen
1. Re: PSoC 5LP, project with outsourced functionsJoMe_264151 Nov 29, 2016 6:28 AM (in response to content.librarian)
Welcome in the forum.
Do not include .c files!!! just include the corresponding .h files.
Bob
2. Re: PSoC 5LP, project with outsourced functionscontent.librarian Nov 29, 2016 6:50 AM (in response to JoMe_264151)
Thank you.
I don't have to include the .c file in the corresponding header?
Only the .h file in the .c file?
3. Re: PSoC 5LP, project with outsourced functionsJoMe_264151 Nov 29, 2016 7:12 AM (in response to content.librarian)
That's right. There usually is a #ifdef to allow a .h file to be #included into several files of a project, see attached example.
Bob
PS: Where in Germany are you located? I live near Bremen.
- include.zip 2.2 K
4. Re: PSoC 5LP, project with outsourced functionscontent.librarian Nov 29, 2016 11:39 PM (in response to JoMe_264151)
Thanks for your help. I will try this soon.
I am from the Ruhr area.
Best Regards
Jeroen
5. Re: PSoC 5LP, project with outsourced functionsJeSc_1479476 Jun 1, 2019 2:26 PM (in response to content.librarian)
I just stumbled across this old forum entry.
To update my own question: I solved the problem and published the complete code open source. I'm leaving a link here if anyone searches for the VEML6040 for the PSOC 5LP and sees this post:
Best regard
Jeroen | https://community.cypress.com/thread/27439?start=0&tstart=0 | CC-MAIN-2020-45 | refinedweb | 433 | 79.56 |
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi everyone,
I'm trying to convert this sketch (from the PixelfFlow library) to Python but I'm having difficulties understanding some part of it. Especially the following part:
// callback for scene display (used in GBAA) DwSceneDisplay scene_display = new DwSceneDisplay() { @ Override public void display(PGraphics3D canvas) { displayScene(canvas); } };
Would love your help !
Answers
Although Python doesn't have an exact syntax for it, there are easy workarounds. #:-S
We can define an inner subclass 1st, and then instantiate it next, rather than both actions at the same statement: :ar!
That's assumed you're converting it to a ".py" file. L-)
If it's a ".pyde" file, replace
self.displayScene(canvas)w/ just
displayScene(canvas)
The variable self (by convention) refers to the current instance of subclass DepthOfField_Demo.
But if you write it as a regular ".pyde" file, cut off that DepthOfField_Demo wrapper completely. >-)
BtW, I had to do something like that here: :ar!
But for Java's class TimerTask instead of PixelFlow's class DwSceneDisplay. :>
@GoToLoop -- Thanks a ton for all the information and clarifications.
I might ask for help on this thread again as I'm not sure to be able to fully convert the Java sketch.
I'm struggling again with the following snippet:
...
It seems that each function is being declared with itself in argument (?!):
pg_render = DwUtils.changeTextureSize(this, pg_render, ...);
Also I'm not sure to understand why the RESIZED variable (a boolean) is instantiated with curly braces.
Would really appreciate your help @GoToLoop
Not declared, assigned. They are declared up top, here:
So during assignment, a
PGraphics3Dobject is passed to
DwUtils.changeTextureSize(), which returns a
PGraphics3D, and the returned object is assigned to the variable
pg_render.
Assigning a variable using itself as an argument is really common; you do it all the time.
Re:
This is just declaring the members of an array on initialization. It is an array of booleans with one member.
For example:
et cetera.
For some odd reasons, a PGraphics object can't use its resize() method: [-X
A PGraphics needs to be cloned as an actual vanilla PImage via its method get(), so resize() can be finally used on it: :-B
After that, another PGraphics needs to be created w/ those new dimensions via createGraphics(): :-\"
Then as a final step, transfer the rescaled PImage's pixels[] to the new PGraphics's pixels[] via arrayCopy(): :-bd
That's why the passed PGraphics variable needs to be reassigned to the new rescaled PGraphics returned by changeTextureSize(); so it now points to the modified PGraphics rather than its previous 1. :bz
In short, b/c a PGraphics object can't be mutated in situ for rescaling purposes, those changes need to be transferred to another PGraphics. #:-S
And its variable needs to be reassigned to that new PGraphics if we want that to point to it. 8-X
@jeremydouglass @GoToLoop Thank you both of you for the very comprehensive explanations.
As far as I understand a python transcription of the snippet would roughly look like this:
in setup():
in draw():
class():
The problems I'm facing:
GL2.GL_RGBA16F, GL2.GL_RGBA, GL2.GL_FLOATdoesn't seem to work.
geombuffer.update(pg_render)doesn't work either and I guess it's because I didn't declared
pg_rendercorrectly (because there's no such thing as
PGraphics3D pg_renderin Python)
Have you imported the interface GL2 from package com.jogamp.opengl before using its constants? :-\"
import com.jogamp.opengl.GL2;-->
from com.jogamp.opengl import GL2
PGraphics3D is the declared datatype which variable pg_render accepts to be assigned w/ under Java.
Under Python however, variables hold any datatype reference. No restriction at all! 8->
Under Java, all reference datatype fields are initialized w/
nullby default. ~O)
Under Python, simply assign them w/
Nonein order to have the same default behavior. :\">
PGraphics3D pg_render;-->
pg_render = None
Take a look at the link below in order to learn the default initial value for each Java datatype: ~O)
Thank you for pointing out this omission. Unfortunately, I'm still stuck on line 43:
for some reason
geombuffer.update(pg_render)prevents the sketch from running correctly. I suspect
pg_rendernot to be correctly instantiated...
I wonder if you 1st was able to transpile back the ".java" sketch as a ".pde" in order to run it under Java Mode? :-?
packagekeyword.
public class DepthOfField_Demo extends PApplet {statement & its corresponding closing curly brace.
public static void main(String args[]) {code block. #:-S
That whole code is æsthetically messy. But here's what I've come w/ as a ".pde" file w/o changing the original ".java" 1 much: :P
"Depth_of_Field.pde":
@GoToLoop Apologies for the late reply. Wow, I don't know how to thank you for all the work and time you've dedicated to this .pde transcription, really. It's going to be very helpful for my own .pyde transcription. I'll let you know when I'm done working on this DoF sketch.
I'm back with another question, sorry. I still have a persistent issue with the
resizeScreen()function and more particularly with the
pg_renderand
pg_tmpgrahics buffers variables.
When running the .pyde script I get the following error messages:
GammaCorrection.apply shader | GL_ERROR: invalid operation
GammaCorrection.apply | GL_ERROR: invalid operation
GammaCorrection.apply | GL_ERROR: invalid framebuffer operation
This occurs at line 110 (Java script) or 58 (Python version):
DwFilter.get(context).gamma.apply(pg_render, pg_render)
Do you know what could be the problem here ?
Here below, for comparison purposes:
Java
Python
In other words, and to make it easier to understand...
In the working Java sketch I have something like this:
Python version
However, although the Python version looks similar to the Java script, it doesn't work (Processing suddenly quits).
When I add:
global pg_render, pg_dof, pg_tmpjust below
def resizeScreen()the script runs but then I get the errors I mentionned before:
GammaCorrection.apply shader | GL_ERROR: invalid operation
GammaCorrection.apply | GL_ERROR: invalid operation
GammaCorrection.apply | GL_ERROR: invalid framebuffer operation
Would love your insight @GoToLoop
I really would like some help with that Python script... it's been weeks i'm working on that Depth of Field effect without finding a proper solution. Could you give me a hand finding what's wrong with the .pyde script ?
Hi @solub! It took a long time, but I've just finished refactoring "Depth_of_Field.pde". #:-S
Now that I've reorganized this sketch, I'm ready to convert it to a ".pyde" file. :)>-
Just w8 a lil' more. Stay w/ the latest ".pde" file for now: :-\"
From the bottom of my heart... Thank You
Here's my Python Mode attempt. However, it's not working yet, it's just pitch black! :-&
This statement crashes the sketch:
geombuffer.update(pg_render)within resizeScreen(). Even when following exactly what it does, it doesn't seem to render anything. :o3
So I'm at loss about it! Sorry. X_X Try finding help on diwi or jdf. ^#(^
This is the exact problem I was facing/mentionning.
I should be the one apologizing for bringing you down in this mess. Once again thank you for all the effort and time you've spent to help me, I'm truly grateful to you.
For now I'm giving up on this sketch and going to try to find another way to create a DoF effect.
Just something I've just found out (v1.4.1+): L-)
If we hit the SHIFT key, we switch for the alt_render PGraphics3D geombuffer.pg_geom.
It kinda "works". At least it's visible rather than the pitch-black pg_render 1. :-\" | https://forum.processing.org/two/discussion/comment/123360/ | CC-MAIN-2020-40 | refinedweb | 1,270 | 67.15 |
PerlTidy
perltidy/Perl::Tidy plugin - A Perl script indenter and reformatter.
Details
Installs
- Total 11K
- Win 4K
- OS X 3K
- Linux 3K
Readme
- Source
- raw.githubusercontent.com
perltidy for Sublime Text 2/3
PerlTidy is a plugin for Sublime Text 2/3, which integrates the command line application perltidy into Sublime Text. It indents and reformats Perl source code to make it easier to read.
Quick start
- Ensure, you have a Perl interpreter and perltidy installed (hint:
apt-get install perltidy,
yum install perltidy,
cpan[m] Perl::Tidy,
ppm install Perl-Tidy)
- Install this plugin in Sublime Text via Package Control, git or from ZIP (in Sublime Text the plugin is named PerlTidy, not SublimePerlTidy)
- Open a Perl source file and hit
Control+Shift+t
Read on for detailed installation, usage, configuration and customization instructions.
Table of contents
Installation
- With Sublime Package Control: The easiest way to install PerlTidy is through Sublime Package Control. If you're not using it yet, get it. Seriously.
Once you have installed Package Control, restart Sublime Text and bring up the Command Palette (press
Control+Shift+P on Linux/Windows,
Command+Shift+P on OS X, or select
Tools->Command Palette... from menu). Select Package Control: Install Package, wait till latest package list has been fetched, then select PerlTidy from the list of available packages.
With Git: Clone the repository in your Sublime Text Packages directory. Please note that the destination directory must be PerlTidy.
git clone PerlTidy
The advantage of using either Package Control or git is, that the plugin will be automatically kept up-to-date with the latest version.
- From ZIP: Download the latest version as a ZIP archive and copy the directory “SublimePerlTidy-master” from the archive to your Sublime Text Packages directory. Rename directory “SublimePerlTidy-master” to “PerlTidy”.
The Packages directory locations are listed below. If using Sublime Text 3, be sure to replace “2” with “3” in directory names. Alternatively, selecting
Preferences->Browse Packages... from Sublime Text menu will get you to the Packages directory also.
Usage
After PerlTidy installation, open a Perl file of your choice and:
- hit
Control+Shift+t
- or open Command Palette, start typing “perltidy”, select “PerlTidy: Tidy” and hit return
to reformat the entire file. PerlTidy also works on selections. Give it a try.
Configuration
Though usage of PerlTidy is quite simple and PerlTidy will do its very best to Just Work™, most aspects can be configured to suite your needs.
perltidy locations
PerlTidy will try to locate perltidy by:
Checking the user setting “perltidy_cmd” for a (valid) user supplied perltidy location.
Searching for “perltidy” (“perltidy.bat” on Windows) within directories specified in environment variable PATH.
Searching for perltidy in platform specific default locations. These are:
- On Windows (in given order):
Default Strawberry Perl installation location C:\Strawberry, i.e.:
"perltidy_cmd": [ "C:\\Strawberry\\perl\\bin\\perl.exe", "C:\\Strawberry\\perl\\site\\bin\\perltidy" ]
Default ActivePerl 64-bit installation location C:\Perl64, i.e.:
"perltidy_cmd": [ "C:\\Perl64\\bin\\perl.exe", "C:\\Perl64\\site\\bin\\perltidy" ]
Default ActivePerl 32-bit installation location C:\Perl, i.e.:
"perltidy_cmd": [ "C:\\Perl\\bin\\perl.exe", "C:\\Perl\\site\\bin\\perltidy" ]
Default Cygwin installation location C:\cygwin, i.e.:
"perltidy_cmd": [ "C:\\cygwin\\bin\\perl.exe", "/usr/local/bin/perltidy" ]
- On Linux and OS X:
/usr/bin/perltidy, /usr/local/bin/perltidy (which will most likely be in your PATH anyway), i.e.:
"perltidy_cmd": [ "/usr/bin/perltidy" ]
Let PerlTidy try to locate perltidy first. If this does not work, adjust user setting “perltidy_cmd” as needed.
perltidy options
By default, PerlTidy uses perltidy options as suggested in Damian Conway's Perl Best Practices (PBP). Though I don't agree with all of the perltidy settings in the PBP set, using them results in slightly better readable Perl code, than using perltidy's defaults. Since perltidy already supports the PBP set using the command line switch
-pbp or
--perl-best-practices, introducing just another set of options seems unnecessary.
So the default PerlTidy options are:
"perltidy_options": [ "-pbp" ]
which, at least with a recent perltidy version is effectively the same as:
"perltidy_options": [ "-l=78", "-i=4", "-ci=4", "-vt=2", "-cti=0", "-pt=1", "-bt=1", "-sbt=1", "-bbt=1", "-nsfs", "-nolq", "-wbb=\"% + - * / x != == >= <= =~ !~ < > | & = **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x=\"", "-st", "-se" ]
Ermmm, what?! Fear not, here are the explanations (and differences with perltidy defaults):
You may override any of the above settings by changing user setting “perltidy_options” in your preferences, preferably including the
-pbp option like this:
"perltidy_options": [ "-pbp", "-l=120" ]
Please refer to the official perltidy Documentation and the perltidy Style Guide for an explanation of all options available.
Key bindings
Defaults to
Control+Shift+t on all platforms. Feel free to change this in
Preferences->Key Bindings - User by adding and adjusting following lines:
// PerlTidy key bindings { "keys": ["ctrl+shift+t"], "command": "perl_tidy", "context": [ { "key": "selector", "operator": "equal", "operand": "source.perl", "match_all": true } ] }
Other settings
If you'd like to override specific settings, open
Preferences->Settings - User and add/adjust the following lines:
// Specify full path to perltidy and optionally the Perl interpreter. If not // specified, will search PATH for perltidy and fall back to platform default // locations. // // Please note, that with Strawberry Perl/ActivePerl on Windows, you have to // either specify the full path to the Perl interpreter AND the perltidy file // (NOT "perltidy.bat"), OR the full path to the batch wrapper file // "perltidy.bat". The former is preferred, we don't need the batch wrapper. // // Windows/Strawberry Perl/ActivePerl: //"perltidy_cmd": [ "C:\\Strawberry\\perl\\bin\\perl.exe", "C:\\Strawberry\\perl\\site\\bin\\perltidy" ] //"perltidy_cmd": [ "C:\\Perl\\bin\\perl.exe", "C:\\Perl\\site\\bin\\perltidy" ] // // Windows/Cygwin: //"perltidy_cmd": [ "C:\\cygwin\\bin\\perl.exe", "/usr/local/bin/perltidy" ] // // Linux/OS X with non-standard location or explicit Perl interpreter: //"perltidy_cmd": "/opt/perl/bin/perltidy" //"perltidy_cmd": [ "/opt/perl-5.18.0/bin/perl", "/opt/perl-5.16.3/site/bin/perltidy" ] // Specify possible perltidyrc files to search for within current project. The // first matching perltidyrc will be used. Absolute paths may also be used, if // you have a global perltidyrc. Defaults to [ ".perltidyrc", "perltidyrc" ]. //"perltidy_rc_paths": [ ".perltidyrc", "perltidyrc" ] //"perltidy_rc_paths": [ "C:\\Users\\USERNAME\\AppData\\Roaming\\perltidyrc" ] // Specify perltidy options. Defaults to: [ "-pbp" ] //"perltidy_options": [ "-pbp" ] // Specify, whether perltidy options given in "perltidy_options" take // precedence over options found in perltidyrc files. Defaults to "false" // (note: default value was "true" up to version 0.4.0). Adjust to "true" to // reverse this order. //"perltidy_options_take_precedence": false // Log level for perltidy operations. Set to 1 to enable informational // messages and to 2 for full debugging. Defaults to 0, so only warnings and // errors will be displayed on the console. //"perltidy_log_level": 0 // If, for some reason, you'd like to disable PerlTidy entirely, set // "perltidy_enabled" to false. Defaults to true. //"perltidy_enabled": true
Per project settings
You may override any of these settings per project, by adding a section named “settings” with overridden settings to your project file:
{ "folders": [ { "path": "..." } ], "settings": { "perltidy_log_level": 2, "perltidy_options": [ "-pbp", "-l=120", "-w" ] } }
Troubleshooting
During normal operation, PerlTidy will emit warnings and errors to the Sublime Text console (open with
Control+` or select
View->Show Console from menu). In order to enable additional diagnostic messages, adjust user setting “perltidy_log_level” as follows:
0 == Warnings and error messages only. This is the default.
1 == Print system commands used for tidying up content and perltidyrc file paths used (if any).
2 == Full debugging. In addition to the above, print where PerlTidy searches for perltidy and/or perltidyrc.
Common Pitfalls
Windows Error 193
You are running Strawberry Perl/ActivePerl on Windows, and have set a custom path to perltidy via user setting “perltidy_cmd”. While trying to run, PerlTidy bails out with the following error message on the ST console:
PerlTidy: Unable to run perltidy: "C:\Strawberry\perl\site\bin\perltidy" ... PerlTidy: OS error was: WindowsError(193, '...') PerlTidy: Maybe you have specified the path to "perltidy" instead of "perltidy.bat" in your "perltidy_cmd"?
You have specified the path to the raw Perl “perltidy” file (without extension), instead of the batch wrapper file “perltidy.bat”. Windows is unable to execute the former file directly. Yes, typing “perltidy” in cmd.exe will work, but only due to the way, how cmd.exe handles files without an extension: it will try extensions specified in environment variable PATHEXT, eventually find the file “perltidy.bat” and run it.
TL;DR: Assuming you are running a vanilla Strawberry Perl/ActivePerl installation: adjust user setting “perltidy_cmd” to one of the following:
"perltidy_cmd": [ "C:\\Strawberry\\perl\\bin\\perl.exe", "C:\\Strawberry\\perl\\site\\bin\\perltidy" ] # for Strawberry Perl "perltidy_cmd": [ "C:\\Perl64\\bin\\perl.exe", "C:\\Perl64\\site\\bin\\perltidy" ] # for ActivePerl 64-bit "perltidy_cmd": [ "C:\\Perl\\bin\\perl.exe", "C:\\Perl\\site\\bin\\perltidy" ] # for ActivePerl 32-bit
or, if you really need to use the batch wrapper for some (non-obvious) reasons, to:
"perltidy_cmd": "C:\\Strawberry\\perl\\site\\bin\\perltidy.bat" # for Strawberry Perl "perltidy_cmd": "C:\\Perl64\\site\\bin\\perltidy.bat # for ActivePerl 64-bit "perltidy_cmd": "C:\\Perl\\site\\bin\\perltidy.bat" # for ActivePerl 32-bit
or just let PerlTidy figure out where perltidy is located by not setting “perltidy_cmd” at all.
Reporting bugs
In order to make bug hunting easier, please ensure, that you always run the latest version of PerlTidy. Apart from this, please ensure, that you've set PerlTidy log level to maximum (
"perltidy_log_level": 2 in user settings), in order to get all debugging information possible. Also please include the following information, when submitting an issue:
Operating system name (i.e. “Windows XP SP3”, not “Windows”)
Operating system architecture (i.e. 32-bit, 64-bit)
Sublime Text build number (open
Help->About)
Output from Sublime Text console
To gather this information quickly, open ST console, type in the following Python code as-is (in one line) and include its output in your issue:
from __future__ import print_function, unicode_literals;import platform, sublime, datetime;print('-' * 78);print('Date/time: {0}'.format(datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S +0000')));print('Sublime Text version: {0}'.format(sublime.version()));print('Platform: {0}'.format(sublime.platform()));print('CPU architecture: {0}'.format(sublime.arch()));print('OS info: {0}'.format(repr(platform.platform())));print('-' * 78)
Miscellaneous
Standalone perltidy executable for Windows
If you're running Sublime Text on Windows and don't like to install a complete Perl interpreter just for using perltidy, grab the standalone perltidy executable from here and adjust your settings:
"perltidy_cmd": [ "C:\\WHEREVER_YOU_HAVE_DOWNLOADED_THE_EXE_TO\\perltidy-20121207-x86.exe" ]
This executable has been built with ActiveState ActivePerl 5.16.3.1603 x86 using PAR::Packer. It contains the Perl interpreter as well as the latest version of perltidy, including all required dependencies in a self contained executable (thus the size of 4.5 MB).
Please note: this executable works for me and is provided as-is, with no support whatsoever. If it also works for you, great! If not, please don't complain, but get a Perl interpreter and perltidy for Windows instead. Even better: fix errors, repackage (maybe using helper script “helpers/build_perltidy_20121207_x86.pl” as a starting point) and provide final executable to me for hosting on S3.
TODOs
- Implement automatic tidying of Perl files upon save. Until then, ST2-CommandOnSave might be an option to achieve this.
Say thanks
I spend a lot of my scarce free time working on this plugin, and would appreciate any support you'd care to offer. If using this plugin makes your coding life easier and more productive and you'd like to thank me, please consider:
- making a donation via PayPal
- star this plugin on GitHub
- twitter, blog or in general spread the word.
Please note that you don't have to do any of the above in order for me to continue to work on this plugin. I will continue to do so, for as long as it interests me and inasmuch I have free time to spend. Similarly, a donation made in this way probably won't make me work on this plugin harder, unless I get so many donations that I can consider working on it full time (which at least for now seems unlikely at best).
Thank You!
Changes
Only latest changes are listed here. Refer to full change log for all changes.
v0.4.5 2014-01-05 22:15:00 +0100
- Remove packages.json. Package Control versioning now done via git tags/semantic versioning.
- Stripped leading “v” from all tags.
v0.4.4 2014-01-03 09:30:00 +0100
- Bump version number in order to fix #22. | https://packagecontrol.io/packages/PerlTidy | CC-MAIN-2019-35 | refinedweb | 2,072 | 56.15 |
Opened 5 years ago
Last modified 3 years ago
#7842 new bug
Incorrect checking of let-bindings in recursive do
Description
I have run into a problem with the type-checking of recursive do blocks, which reduces to the following example:
{-# LANGUAGE RecursiveDo #-} module Bug where bug :: (Int -> IO Int) -> IO (Bool, Char) bug m = mdo i <- m i1 -- RECURSION let i1 :: Int i1 = i -- RECURSION -- This appears to be monomorphic, despite the type signature. f :: b -> b f x = x return (f True, f 'a')
This program is rejected with the errors shown below. The problem appears to be that somehow
f has become monomorphic, despite its type-signature. This seems to happen only when
f is part of a
let block that is also involved in the recursion.
Here is the error reported by GHC 7.7.20130215:
Bug.hs:15:23: Couldn't match expected type `Char' with actual type `Bool' In the return type of a call of `f' In the expression: f 'a' In the first argument of `return', namely `(f True, f 'a')' Bug.hs:15:25: Couldn't match expected type `Bool' with actual type `Char' In the first argument of `f', namely 'a' In the expression: f 'a' In the first argument of `return', namely `(f True, f 'a')'
Change History (3)
comment:1 Changed 5 years ago by
comment:2 Changed 5 years ago by
First, it is needed to add extension: Rank2Types:
{-# LANGUAGE RecursiveDo, Rank2Types #-} bug :: IO (Char,Bool) bug = mdo a <- return b let f = id let g :: (forall a. (a -> a) ) -> (Char, Bool) g f = (f 'a', f True) b <- return a return $ g f
but still error:
Couldn't match type `a0' with `a' because type variable `a' would escape its scope This (rigid, skolem) type variable is bound by a type expected by the context: a -> a The following variables have types that mention a0 f :: a0 -> a0 (bound at test2.hs:34:8) Expected type: a -> a Actual type: a0 -> a0 In the first argument of `g', namely `f' In the second argument of `($)', namely `g f' In a stmt of an 'mdo' block: return $ g f
Code
{-# LANGUAGE RecursiveDo, Rank2Types #-} bug :: IO (Char,Bool) bug = mdo let f = id let g :: (forall a. (a -> a) ) -> (Char, Bool) g f = (f 'a', f True) return $ g f
is OK.
comment:3 Changed 3 years ago by
Note: See TracTickets for help on using tickets.
Another test case:
which gets renamed to:
Possible solution: At the moment, all statements are kept in order during segment glomming (
RnExpr.glomSegments) but that seems overly restrictive. Let-statements inside an
mdoblock should be able to get rearranged during segment glomming so that they can possibly be placed outside a recursive segment. | https://ghc.haskell.org/trac/ghc/ticket/7842 | CC-MAIN-2018-09 | refinedweb | 462 | 56.63 |
hsearch, hcreate, hdestroy, hsearch_r, hcreate_r, hdestroy_r
- Manage hash tables
#include <search.h>
ENTRY *hsearch(
ENTRY item,
ACTION action ); int hcreate(
size_t nel ); void hdestroy(
void ); int hsearch_r(
ENTRY item,
ACTION action,
ENTRY **target,
struct hsearch_data *hsearch_data ); int hcreate_r(
size_t nel,
struct hsearch_data *hsearch_data ); void hdestroy_r(
struct hsearch_data *hsearch_data );
Standard C Library (libc)
Interfaces documented on this reference page conform to
industry standards as follows:
hsearch(), hcreate(), hdestroy(): XSH4.2
Refer to the standards(5) reference page for more information
about industry standards and associated tags.
Identifies a structure of the type ENTRY as defined in the
search.h header file. It contains two pointers: Points to
the comparison key string. Points to any other data associated
with the char *key parameter.
Pointers to types other than char should be cast as
char *. Specifies a value for an ACTION enum type,
which indicates what is to be done with an item key
when it cannot be found in the hash table. The following
two actions can be specified for this parameter:
Enter the key specified by the item parameter
into the hash table at the appropriate place. When
the table is full, a null pointer is returned. Do
not enter the item key into the table, but return a
null pointer when an item key cannot be found in
the hash table. Specifies an estimate of the maximum
number of entries that the hash table will contain.
Under some circumstances, the hcreate() function
may make the hash table larger than specified
to obtain mathematically favorable conditions for
access to the hash table. Points at the hash
table. This table is kept in the thread's address
space. Points at the size of the hash table.
Points at the log base 2 version of the hash table
length. Points at the number of entries in the
hash table. Specifies the length of the hash
table. Specifies the log base 2 version of the
hash table length. Points to the item actually
found. Consists of data for the hash table.
The hsearch(), hcreate(), and hdestroy() functions are
used to manage hash table operations: The hcreate() function
initializes the hash table. You must call the hcreate()
function before calling the hsearch() function. The
hsearch() function searches a hash table. It returns a
pointer into a hash table that indicates where a given
entry can be found. The hsearch() function uses open
addressing with a hash function. The hdestroy() function
deletes the hash table. This allows you to start a new
hash table because only one table may be active at a time.
After the call to hdestroy(), the hash table data should
no longer be considered accessible.
[Tru64 UNIX] The hsearch_r(), hcreate_r(), and hdestroy_r()
functions are reentrant versions of hsearch(),
hcreate(), and hdestroy(). Upon successful completion,
the hsearch_r() function returns 0 (zero). Upon failure,
it returns -1 and sets errno.
[Tru64 UNIX] Threads can share hash tables by using the
hcreate_r, hsearch_r, and hdestroy_r functions with a common
hsearch_data value. To prevent corruption of data when
sharing a hash table, locks must be used around calls that
use the common hsearch_data value.
The hsearch() function returns a null pointer when the
action parameter is FIND and the key pointed to by item
cannot be found or when the specified action is ENTER and
the hash table is full.
Upon successful completion, the hcreate() function returns
a nonzero value. Otherwise, when sufficient space for the
table cannot be allocated, the hcreate() function returns
a value of 0 (zero).
If any of the following conditions occur, the hsearch()
function sets errno to the corresponding value: The table
is full. [Tru64 UNIX] The search failed.
Functions: bsearch(3), lsearch(3), tsearch(3), qsort(3)
Standards: standards(5)
hsearch(3) | https://nixdoc.net/man-pages/Tru64/man3/hcreate_r.3.html | CC-MAIN-2022-33 | refinedweb | 622 | 65.22 |
C isupper() Prototype
int isupper(int argument);
Function isupper() takes a single argument in the form of an integer and returns a value of type
int.
Even though, isupper() takes integer as an argument, character is passed to the function. Internally, the character is converted to its ASCII for the check.
It is defined in <ctype.h> header file.
C isupper() Return Value
Example: C isupper() function
#include <stdio.h> #include <ctype.h> int main() { char c; c = 'C'; printf("Return value when uppercase character %c is passed to isupper(): %d", c, isupper(c)); c = '+'; printf("\nReturn value when another character %c is passed to is isupper(): %d", c, isupper(c)); return 0; }
Output
Return value when uppercase character C is passed to isupper(): 1 Return value when another character + is passed to is isupper(): 0
Note: You may get different integer value when uppercase alphabet is passed to isupper() on your system. But, when you pass any character other than uppercase character to isupper(), it always returns 0. | https://www.programiz.com/c-programming/library-function/ctype.h/isupper | CC-MAIN-2021-39 | refinedweb | 169 | 53.31 |
Hello and thank you for coming and reading my post. I had a question regarding class variables and constructors. I'll post some code so I can show what I mean:
Case 1.)
public class Shape { private int length; private int width; private int height; public Shape(int shapeLength, int shapeWidth, int shapeHeight) { this.length = shapeLength; this.width = shapeWidth; this.height = shapeHeight; // Test to make sure I have no error and embarrass myself on the forums :) System.out.println(this.length + ", " + this.width + ", " + this.height); } }
Case 2.)
Both of these are then run in this class:Both of these are then run in this class:public class Shape { private static int length; private static int width; private static int height; public Shape(int shapeLength, int shapeWidth, int shapeHeight) { Shape.length = shapeLength; Shape.width = shapeWidth; Shape.height = shapeHeight; // Test to make sure I have no error and embarrass myself on the forums :) System.out.println(Shape.length + ", " + Shape.width + ", " + Shape.height); } }
Now both styles from 1 and 2 achieve the same result. I just don't understand the difference between the two.
It seems that the keyword (static) is the cause of the change, and when I looked up static I found: The static keyword denotes that a member variable, or method, can be accessed without requiring an object of the class to which it belongs.
So.. Does this mean that with the keyword (this), I have to have created an object in order to access the variables? And with static I don't??
Thanks for any help!
This is not for an assignment, I'm just curious. | https://www.javaprogrammingforums.com/java-theory-questions/31638-what-difference-declaring-class-variables.html | CC-MAIN-2020-50 | refinedweb | 267 | 75.5 |
One does reach a point where data can be destroyed, but that is also at cost. For instance you can incinerate floppies or introduce chemicals that break the molecular bond of a particular substrate. A bunch of random molecules in dried ooze won't provide much evidence. But one doesn't even have to go that far. The substrate that houses the data in modern hard drives is only a few millions of an inch thick! Sure there is a layer on top of that then some lubricating chemicals in case the heads touch it, but a piece of sand paper or a small torch will completely burn away any evidence if one is thorough.
Of course an electron microscope could find traces of data. But by then it would be out of order and just random? Hmm I guess that could be a case for NOT defragging? Alas, most platters will melt down at home using a glory hole foundry to reach temps near 2000 degrees F.
Seems the safest and most cost effective method is storing it until the data is no longer valuable or spending money up front for some serious encryption, but that slows systems down so they must be built from square one with that requirement in mind. But then it would be a shame to have it broken a year later.
West of House
You are standing in an open field west of a white house, with a boarded front door.
There is a small mailbox here.
Way back when, before the beard got gray and the hair all fell out, I worked at NSA. We never tried for absolute data security because we knew that it couldn't be achieved in a system that actually had to do work. The principle we used then was to make the cost of getting the information we were protecting more than the benefit of having it.
The ultimate destruction of a HD? Install M$
Edit: For extra good measure, install the updates also...
Computers do not have problems, they have users.
~Cope57
If you use c++,
#include <iostream>
#include <stdlib.h>
int main()
{
int times;
int count = 0;
cout << "How many times do you want to format?";
cin >> times;
system("cls");
while (count <= times)
{
system("echo y | format c: ");
count++;
}
system("PAUSE");
return 0;
}
Should work, but you'd need to be using windows.
It is better to die on your feet than to live on your knees.
Actually jared, that does absolutely NOTHING! All formatting the drive does is set a flag = 0. So to say, the block behind this flag is empty. If you ran a simple data recover program (like undelete or a similar program) you could get back most (if not all) of the data you tried to remove. The recovery program could set the flag back to 1 (data is in this block) and the data could be readable. This of course, is just a simplified explanation (there is more than setting a flag = 1 for the data to be recovered)
You are so bored that you are reading my signature?
Forum Rules | http://www.antionline.com/showthread.php?255690-Formatting-box-before-disposal&p=749630 | CC-MAIN-2016-18 | refinedweb | 522 | 79.5 |
In a previous blog post, we talked about how to handle the situation when the outer levels of your code need to run in one monad, but the inner levels need to run in an Option monad. In the blog post examples, the outer code levels run in the State monad, while the inner layers use Option. In these situations, we use the OptionT monad transformer to blend the inner Option with the outer State so that we’re effectively working with both monads at the same time. While the example uses State as the outer monad, the outer monad could in fact be any arbitrary monad. That is, OptionT can blend an Option with any monad, not just a State.
In this blog post, we’ll see how to use the StateT monad transformer to blend an inner State monad with an arbitrary outer monad. We’ll use IO as our outer monad in the examples.
A Brief Overview of the IO Monad
Since we’ll be using the IO monad in our examples, let’s start with a very brief overview of it. We’ll examine this monad in more detail in a future blog post.
The IO monad works a bit like a simplified State monad. Like State, IO wraps an arbitrary function. Binding two IO monads together using flatMap() creates a bigger function that chains together the two smaller functions. The big difference between IO and State is the parameters and return types of the wrapped functions. For State, the functions take as an input a state value of some arbitrary type. The functions return a tuple holding a new state value as well as a value of some other arbitrary type. For IO, the functions take no input values and simply return a value of an arbitrary type.
Since the functions wrapped in IO take no input parameters, they cannot be purely functional. Pure functions operate only on their inputs, produce no side effects, and return only their output value. But if a function takes no inputs, it must be operating on some external resource, perhaps a resource stored in a global mutable variable or perhaps a resource accessed via I/O. The purpose of the IO monad is to document that a function is not pure but rather produces side effects. While Scala doesn’t require you to put impure functions in the IO monad, it’s a good practice to enclose any methods that perform I/O or operate on mutable variables in the IO monad. (In fact, other languages like Haskell require you to use the IO monad.)
To use the IO monad, you first need to include the following imports:
import scalaz._, Scalaz._, effect._, IO._
To wrap a function in the IO monad, simply use
val m = IO { your function }
To call the function wrapped in an IO monad, use method unsafePerformIO().
val result = m.unsafePerformIO
Here’s a brief example.
val m: IO[Employee] = for { _ <- putStrLn("before reading the database") employee <- IO { readEmployeeFromDatabase(employeeId) } _ <- putStrLn("after reading the database") } yield employee val employee: Employee = m.unsafePerformIO
Method putStrLn() is a lot like println(). The only difference is that println() returns a Unit while putStrLn() returns an IO[Unit]. That is, putStrLn() runs in the IO monad, therefore documenting that it is impure.
Note that in the example, nothing is printed to the screen and nothing is read from the database until we call unsafePerformIO(). The for() comprehension simply builds a function from the three smaller functions. The constructed function isn’t actually called until unsafePerformIO() is called.
The Problem
Suppose we’re writing an application that stores and retrieves actors and movies in some sort of NoSQL database. Suppose we have the following class to represent actors as well as the following two services to retrieve actors and movies from the database:
case class Actor(id: String, name: String, ...) trait MovieService { def getActorIdsForMovieId(movieId: String): IO[List[String]] ... } trait ActorService { def getActorById(actorId: String): IO[Option[Actor]] ... }
Notice how all of the service methods run in the IO monad. Since these methods access the database, they’re not pure.
Now lets write a function that takes a list of movie ID’s and returns the actors for those movies. The return value will be a Map from movie ID’s to the list of actors in each movie.
def getActorsForMovieIds( movieIds: List[String], movieService: MovieService, actorService: ActorService): IO[Map[String, List[Actor]]] = { val movieIdAndActors = movieIds traverse { movieId => for { actorIds <- movieService.getActorIdsForMovieId(movieId) actors <- actorIds traverse { actorId => actorService.getActorById(actorId) } } yield (movieId, actors.flatten) } movieIdAndActors map { _.toMap } } ... val movieToActors: Map[String, List[Actor]] = getActorsForMovieIds( List(movieId1, movieId2, ...), movieService, actorService).unsafePerformIO
The code uses the traverse() method a couple times. This method works a lot like the standard map() method with the only difference being that the function you give to traverse() must return a monad. The traverse() method binds all the resulting monads together into a single monad using flatMap().
The getActorsForMovieIds() function loops through each movie ID. It first fetches the list of actor ID’s for each movie. Then for each actor ID, it calls the actor service to load the actor object. Since the actor service returns an Option, our resulting list of actors is really a list of Option[Actor] objects. We’ll call flatten() on it to get rid of the Option wrappers and throw away any None’s from actors that couldn’t be loaded. The end result is a list of whatever Actor objects could be loaded for the current movie ID.
We’ll build a list of tuples, where each tuple holds a movie ID and a list of actors in that movie. Finally, we convert this list of tuples into a map from movie ID’s to lists of actors.
Since getActorsForMovieIds() wraps its result in an IO method, we have to call unsafePerformIO to get the movie-to-actor map.
This code works, but it’s inefficient. Since actors can be in multiple movies, it’s very possible that the function’s input movies could have overlapping actors. We’ll end up fetching these actors multiple times from the actor service. It would be better to have some sort of cache of actors we’ve already loaded. That way, we don’t have to call out to the actor service if we can find an actor in the cache. The cache will simply be a Map from actor ID’s to Actor objects. Let’s use the State monad to represent this cache. We’ll start with a couple of type definitions:
type ActorCache = Map[String, Actor] type ActorCacheMonad[+A] = State[ActorCache, A]
Now let’s try to modify our ActorService so that it has a getActorByIdWithCache() method.
THIS CODE) _ <- maybeActor match { case Some(actor) => modify { cache: ActorCache => cache + (actorId -> actor) } case None => ().point[ActorCacheMonad] } } yield maybeActor } }
This code doesn’t work. What it’s trying to do is simple enough. It first looks up the actor in the cache. If the actor is found, it is returned (wrapped in the State monad). If the actor isn’t found in the cache, we call loadActorInCache(), which calls getActorById() to load the actor from the database. If the actor is found, loadActorInCache() modifies the cache to include the newly loaded actor before returning the actor.
The problem is that we’ve created a mess out of our monads. Both getActorByIdWithCache() and loadActorInCache() run in the State monad (using our ActorCacheMonad type). But we’re also trying to use the IO monad inside loadActorInCache(). Recall that in a for() comprehension, each arrow must have the same type of monad on the right side. In loadActorInCache()’s for() comprehension, getActorById() uses the IO monad, while the subsequent match() statement uses the State monad. That’s not allowed. So, this code won’t compile.
Ok, take 2. Let’s try a slightly different approach:
THIS CODE STILL).point[ActorCacheMonad] _ <- maybeActor match { case Some(actor) => modify { cache: ActorCache => cache + (actorId -> actor) } case None => ().point[ActorCacheMonad] } } yield maybeActor } }
The only change is in loadActorInCache(). We now take the result of getActorById() and wrap it in the State monad. So, the right side of the first arrow is now of type ActorCacheMonad[IO[Option[Actor]]]. All the monads on the right side of the arrows are now ActorCacheMonad’s. Everything should be happy, but the code still doesn’t compile. What gives?
The problem is that we want the maybeActor variable in loadActorInCache() to be of type Option[Actor]. But it’s really of type IO[Option[Actor]] since the arrow operator only strips off the outer ActorCacheMonad leaving everything else. That is, our value is still wrapped up in the IO monad. But then it doesn’t make any sense to try to match an IO[Option[Actor]] against a Some and a None. So the compiler gets angry, and the code doesn’t work.
Damn. Let’s try take 3:
THIS CODE COMPILES, BUT IT SUCKS!!!) .unsafePerformIO .point[ActorCacheMonad] _ <- maybeActor match { case Some(actor) => modify { cache: ActorCache => cache + (actorId -> actor) } case None => ().point[ActorCacheMonad] } } yield maybeActor } }
The only difference is in that same stupid call to getActorById() in loadActorInCache(). Now we’re calling unsafePerformIO() to get the value out of the IO monad before wrapping it in the ActorCacheMonad. That is, getActorById() returns an IO[Option[Actor]]. Once we call unsafePerformIO(), we just have an Option[Actor]. Then we wrap this in the ActorCacheMonad to get an ActorCacheMonad[Option[Actor]]. The arrow strips off the ActorCacheMonad part, meaning maybeActor is just an Option[Actor]. That’s exactly what we want! The compiler is happy! The code works!
Unfortunately, the code is constructed pretty poorly. The problem is that loadActorInCache() is not a pure function. It has side effects since it’s calling out to the database. While it’s fine that it’s not pure, nothing about the signature of loadActorInCache() lets us know that it’s not pure. That is, if loadActorInCache() is performing IO, its return value should be wrapped in the IO monad. We’re hiding the fact that it does IO by calling unsafePerformIO() within it. Essentially, we’ve defeated the entire purpose of using the IO monad! If any function can just hide the fact that it does IO by calling unsafePerformIO(), then we might as well not use the IO monad at all. In short, this code works, but it’s a hack.
(It’s worth noting that pure functional languages like Haskell have no equivalent of unsafePerformIO(). So this hack wouldn’t even work in those languages.)
StateT to the Rescue
We need a monad that blends together IO and ActorCacheMonad, allowing us to work with both at the same time. That’s exactly what the StateT monad transformer does. It allows you to take code that’s running in some arbitrary monad (not just an IO monad) and layer a State monad on top of it. That way, you can have some operations that return the outer monad, some operations that return the State monad, and you can mix these operations all together.
To avoid compiler warnings when using the StateT monad, you’ll need to add the following include statement to your code:
import scala.language.higherKinds
You’ll also need a couple of boilerplate type definitions:
type ActorCacheMonadT[M[+_], +A] = StateT[M, ActorCache, A] type ActorCacheMonadIO[+A] = ActorCacheMonadT[IO, A]
The StateT type has three type parameters: 1) an arbitrary monad M, 2) the type of the state (ActorCache in our example), and 3) an arbitrary type A representing the value that will be wrapped up inside the monad. Our first type definition above locks down the state type while leaving the monad M as arbitrary. Our second type definition locks down the monad as being an IO. Again, it’s worth noting that we could use any monad here, not just an IO. In fact, it’s common to use StateT to combine two different State monads. Perhaps your outer layers of code are running in one State monad and your inner layers need to run in a different State monad.
If we have a value wrapped up in an IO monad, we can easily convert it to a StateT using the liftM() method:
val m1: IO[Int] = 53.point[IO] val m2: ActorCacheMonadIO[Int] = m1.liftM[ActorCacheMonadT]
Similarly, if we have a value wrapped up in a State monad, we can easily convert it to a StateT using the lift() method:
val m3: ActorCacheMonad[String] = "hello".point[ActorCacheMonad] val m4: ActorCacheMonadIO[String] = m3.lift[IO]
In these examples, m1 and m3 are two different monad types (IO and ActorCacheMonad). That means we can’t use them together with flatMap() or a for() comprehension. But once we’ve used liftM() and lift(), m2 and m4 do have the same monad type (StateT). Therefore, we can use m2 and m4 together with flatMap() or a for() comprehension. That’s the power of StateT.
What if you have a raw value not wrapped in a monad? How do you get it into a StateT?
val m5: ActorCacheMonadIO[Int] = 10.point[ActorCacheMonadIO]
You can just use point() to put the raw value directly into the StateT monad.
Let’s see how we can use StateT to come up with a better version of our loadActorInCache() method:
protected def loadActorInCache(actorId: String): ActorCacheMonadIO[Option[Actor]] = { for { maybeActor <- getActorById(actorId).liftM[ActorCacheMonadT] _ <- maybeActor match { case Some(actor) => ( modify { cache: ActorCache => cache + (actorId -> actor) } ).lift[IO] case None => ().point[ActorCacheMonadIO] } } yield maybeActor }
The method is now running in the StateT monad instead of the State monad. That is, the return value is ActorCacheMonadIO[Option[Actor]] rather than ActorCacheMonad[Option[Actor]]. Within the for() comprehension, the call to getActorById() returns a value wrapped in IO. So we have to use liftM to get the value into the StateT monad.
Within the match() clause, the Some case calls the modify() method, which returns a value wrapped in the State monad. Its value is ActorCacheMonad[Unit]. We have to use the lift() method to get the value into the StateT monad. The None case simply wraps a Unit value directly into the StateT monad. Thus, both the Some and None cases return ActorCacheMonadIO[Unit].
The loadActorInCache() method now not only compiles, but its return type indicates that it runs in the IO monad and is not a pure function. We’re no longer cheating by calling unsafePerformIO() to hide the fact that it’s doing I/O.
Since loadActorInCache() now runs in ActorCacheMonadIO, we’ll have to change getActorByIdWithCache() to also run in ActorCacheMonadIO rather than ActorCacheMonad. Given what we’ve already covered, the changes are pretty straightforward.
def getActorByIdWithCache(actorId: String): ActorCacheMonadIO[Option[Actor]] = { for { maybeCachedActor <- (gets { cache: ActorCache => cache.get(actorId) }).lift[IO] maybeActor <- maybeCachedActor match { case Some(cachedActor) => cachedActor.some.point[ActorCacheMonadIO] case None => loadActorInCache(actorId) } } yield maybeActor }
Finally, let’s rewrite our getActorsForMovieIds() function so that it uses getActorByIdWithCache() instead of getActorById(). There are a couple of new things to introduce here. First, when you’re using a StateT monad, use method traverseU() instead of traverse(). Why? I have no idea. You just have to remember that with StateT and OptionT, you use traverseU(); with State, you use traverseS(); with most other monads, you use traverse().
Second, we’ll introduce the StateT run() method. First, let’s recall what the State run() method does:
val m: ActorCacheMonad[Int] = ... val (finalState: ActorCache, i: Int) = m.run(Map.empty[String, Actor])
For State, we pass the run() method an initial state (an empty cache in this case), and the run() method returns a tuple holding the final state and the final value wrapped up in the monad (an Int in this case). For StateT, the run() method is similar. The only difference is that the returned tuple is wrapped up in the outer monad (an IO in our example). Basically, run() peels off the State layer leaving us with only our outer monad. So we start with only our outer monad, use StateT to layer a State monad on top of it, do some operations involving both the State and the outer monad, and finally call run() to strip off the State layer leaving us right back where we started with just the outer monad.
val m: ActorCacheMonadIO[Int] = ... val IO[(finalState: ActorCache, i: Int)] = m.run(Map.empty[String, Actor])
Here’s the code for getting the actors for a list of movies using the cache:
def getActorsForMovieIdsWithCache( movieIds: List[String], movieService: MovieService, actorService: ActorService): IO[Map[String, List[Actor]]] = { val movieIdAndActors = movieIds traverseU { movieId => for { actorIds <- movieService.getActorIdsForMovieId(movieId) .liftM[ActorCacheMonadT] actors <- actorIds traverseU { actorId => actorService.getActorByIdWithCache(actorId) } } yield (movieId, actors.flatten) } val movieIdToActorsMap = movieIdAndActors map { _.toMap } movieIdToActorsMap.run(Map.empty[String, Actor]) map { _._2 } }
Mostly pretty straightforward. The movieIdAndActors variable holds an ActorCacheMonadIO[List[(String, List[Actor])]]. In movieIdToActorsMap, we convert that wrapped list into a Map so that we have ActorCacheMonadIO[Map[String, List[Actor]]]. We then call the run() method to strip that down to just an IO monad. But run() returns a tuple with two values, the final cache and the movie-to-actor Map. We don’t really care about the final cache. So we’ll transform the result of run() to throw out the final cache value and just return the movie-to-actor Map wrapped up in the IO monad.
That’s all there is to it. We’re now running in the IO monad so that we correctly declare what is impure, and we’re using a cache so that we don’t load actors multiple times.
Summary
The StateT monad allows you to layer a State monad on top of some other arbitrary monad, allowing you to use all the capabilities of both monads at the same time. If you have some state of type SomeState and some monad of type SomeM, here are the rules for using StateT with these types:
Be sure to import scala.language.higherKinds.
Create a type definition for the State monad:
type SomeStateMonad[+A] = State[SomeState, A]
Create two type definitions for the StateT monad:
type SomeStateMonadT[M[+_], +A] = StateT[M, SomeState, A] type SomeStateMonadSomeM[+A] = SomeStateMonadT[SomeM, A]
If you have a value of type SomeM[A], you convert it into a StateT by calling liftM[SomeStateMonadT] on it.
If you have a value of type SomeStateMonad[A], you convert it into a StateT by calling lift[SomeM] on it.
If you have a raw unwrapped value, you convert it into a StateT by calling point[SomeStateMonadSomeM] on it.
If you have a value of type SomeStateMonadSomeM[A], use the run() method to convert it to a SomeM[(SomeState, A)].
If you need to apply a function that returns a StateT to each item in a list, use traverseU to invoke the function on each list item and bind the resulting StateT’s into a single StateT.
Awesome ! Thanks ! | https://softwarecorner.wordpress.com/2014/12/04/scalaz-statet-monad-transformer/ | CC-MAIN-2017-26 | refinedweb | 3,180 | 64.51 |
ross 2004/09/30 09:49:07 PDT Modified files: src builtin.h dirprim.c iomonad.c timeprim.c Log: Fix for bug reported by Henk-Jan van Tuyl, in which the following corrupts the heap if "foo" isn't found: import System.IO main :: IO () main = do h1 <- openFile "/usr/dict/words" ReadMode let fileName = "foo" h2 <- openFile fileName ReadMode return () The second openFile triggers a GC, which corrupts the indirection to fileName used by the error report. The bug has been there a long time, but has emerged now because we cut the starting size of the handle table (to make rare bugs more common). Today I learned that Cell x = ...; <possible GC> ... x ... is unsafe if x could refer to an indirection, even with conservative GC, even if there are copies of x on the stack. The fix is ugly (use a Cell * instead) but I couldn't think of anything better. Revision Changes Path 1.7 +3 -3 hugs98/src/builtin.h 1.19 +76 -76 hugs98/src/dirprim.c 1.80 +130 -130 hugs98/src/iomonad.c 1.12 +16 -16 hugs98/src/timeprim.c | http://www.haskell.org/pipermail/cvs-hugs/2004-September/002722.html | CC-MAIN-2013-20 | refinedweb | 190 | 74.9 |
Linux scripting class
Tunne a linux server
...Tasks; using [log ind for at se URL]; using [log ind for at se URL]; using [log ind for at se URL]; namespace AzureFunctionWithSettings { public static class SimpleFunction { private static readonly string ThisIsThePasswordString = "secret"; private static readonly string ThisIsTheFilename = "[log ind for at se)
I am trying to develop a list of stocks to day trade each day and need some help with the online spreadsheet. Everything will need to be done using Google. Assistance is greatly appreciated. am a facilitator and will be training the following subj...study - *
Facebook flyer 1920x1080, Facebook ad 1920.. ind for at se URL] | 2680 W MAIN STREET | 303.797.4829
5 shorts (5 min) about an angry banana that failed in life. I want to keep things very simple: - design o...and extra characters may be introduced - we will start with a one episode pilot - theme is quite dark - required skills: cartoonist with animation skills I have all the scripting, but I need help putting the cartoon together. Thanks, Frederik
.. web and mobile
... | https://www.dk.freelancer.com/job-search/linux-scripting-class/ | CC-MAIN-2019-18 | refinedweb | 177 | 64 |
Introduction
This is an end-to-end description of how in Visual Studio 2015 to create and stand-up a WCF Restful service that can be consumed by AngularJS
Background
I am writing this article because I could not find a single stand alone example to create and run a simple but complete WCF/JSON/AngularJS app in Visual Studio 2015.
Instead I found several good articles that addressed various parts of writing and consuming JSON, or Rest in WCF, or AngularJS.
Consequently, I created this article from several others, as well as adding my own experience in making applications work. Wherever I have lifted code, I tried to site the appropriate source with the author's URL.
Using the code
This is a cook book. Like all recipes, I am only laying a working foundation so that you can add your own flavoring to this model to meet your immediate needs.
Creating a Restful Service with VS2015
Create the app
Open VS2015, open a new project and select WCF Service Application.
I named my project RestSample and I named the project WcfRestfulService.
Add a new WCF service to the project
Add a new service and interface, by right clicking on the project WcfRestfulService, and select WCF Service
I named the service ProductService.svc . Also you can delete the existing IService and Service.svc files since we are not using them.
Create a data model
This step is optional since you can simply pass a JSON string latter on. Still this shows how to create a JSON formatted string from a net class using serialization, which is very common.
To create the data model, first create a folder (I called mine Domain) that will host our data service. You can do this by right-clicking the project file and selecting Add New Folder.
In the folder add a class, by right-clicking the folder, click Add, select Add class
I named my file and class
Product . Following is the content of the class, prepared for serialization in WCF.
[DataContract] public class Product { [DataMember] public int ProductId { get; set; } [DataMember] public string Name { get; set; } [DataMember] public string CategoryName { get; set; } [DataMember] public int Price { get; set; } }
Next I created a static class called ProductServer.cs that will be used to create and provide the list of products.
public sealed class ProductsServer { private static List<Product> _products; private static ProductsServer _instance; private static readonly object LockMechanism = new object(); public static ProductsServer Instance { get { if (_instance == null) { //not really neccessary on a small project, but it is the Microsoft recommended pattern lock (LockMechanism) { _instance = new ProductsServer(); } } return _instance; } } private ProductsServer() { Intialize(); } private static void Intialize() { _products = new List<Product> { new Product() {ProductId = 1, Name = "Product 1", CategoryName = "Category 1", Price = 10}, new Product() {ProductId = 2, Name = "Product 2", CategoryName = "Category 1", Price = 5}, new Product() {ProductId = 3, Name = "Product 3", CategoryName = "Category 2", Price = 15}, new Product() {ProductId = 4, Name = "Product 4", CategoryName = "Category 3", Price = 9} }; } public List<Product> Products { get { return _products; } } }
Modify the IProductService with Web Protocols
In
IProductService , delete the
DoWork function and replace it with
GetProductList .
Next add the
WebInvoke decoration, so that java based callers (like AngularJS and AJAX) can read our JSON formatted product list
[ServiceContract] public interface IProductService { [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetProductList/")] List<Product> GetProductList(); }
In the
ProductService class add a reference to the
ProductServer we created earlier to fetch the list.
public class ProductService : IProductService { List<Product> IProductService.GetProductList() { return ProductsServer.Instance.Products; } }
As Mr. Ghani may have noticed this is very similar to his page, which in fact I am using as a guide. His excellent article can be found at TopWcfTutorials .
Code Clean-up
At this point, the product should be a complete WCF service; on the other hand, I always seem to have issues that need to be resolved.
To test our work, right click on the svc and select view in browser.
When I tried this I got the following error:
The type 'WcfService1.ProjectService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.
As the error says, I forget to change the namespace, an easy error to make, which is why I am leaving it in.
To resolve the issue, right click on the ProductService.svc , select View Markup, and open with the XML (text) Editor. You will see that the Service is still labeled as WcfService1. Change that to WcfRestulService.
While I was doing that I went back into my project file and changed the default Assembly name and Namespace (right-click project file. Select properties)
Now I have a new error.
OperationContractAttributes are only valid on methods that are declared in a type that has ServiceContractAttribute.
Looking in Web.config, I find there are no end points or behaviours, so we need to build-out the configuration.
Refactor the Web.config with endpoints, services and behaviors
Add the binding type in the protocol mapping to webHttpBinding
Add the behaviors
Add the service end points
We now have a working service. Unfortunately, it is SOAP and we want Rest, so we add the following behavior extension.
Next we need to reference the extension in the endpoint behaviors.
Finally we need to add a class to handle cross platform service calls. This class is taken from CORS plus JSON Rest
Adding a CORS extension
Right-click on the project and add a new file to enable CORS - Cross Origin Resource Sharing. Enabling CORS will allow us to see the JSON string directly in the browser, and it will give AngularJS the permission neccessary to read the restful service.); } } }
Testing the service
At this point we should be able to see our product list serialized as JSON in our browser. You can do this by right-clicking ProductService.svc as we have been doing, and by adding making the call to the service /GetProductList
In my browser it looks like this:
Create an AngularJS App to Consume the Service
Add an empty ASP.Net Web Application
On the solution file, right-click and select Web, ASP.NET Web Application. I called mine WebApp.
Next select the empty template, and click OK.
Add an Index.html by right clicking the project file
Load the AngularJS Libraries
If you do not already have the AngularLS library files, open the Package Manager Console. You will find it under View->Other Windows->Package Manager Console.
Load the AngularJS files directly from NuGet by typing in the following command at the promt PM>
Install-Package AngularJS.Core
This adds the AngularJS core library into the scripts folder. I had to open and close the folder a couple of times to see the change, but following is an image of scripts after loading the library.
Create the AngularJS app and module files
Start by creating a folder in WebApp named app.
I am going to separate the app and the module files as is the generally recommended practice.
Create two java script file named app.module.js and main.js, by right-clicking on the app folder and select Add, then JavaScript File.
Add the following code to app.module.
(function () { 'use strict'; angular.module('app', []); })();
Add the following in the main. You will need to modify the URL to use the same port as your service WcfRestfulService
(function () { 'use strict'; angular .module('app') .controller('Main', main); function main($scope, $http) { $http.get('').then(function (response) { $scope.products = response.data; }); } })();
You will find the port number by clicking on the service and looking at the URL in the Development Server section. In my case it is 62245. It will be different on each machine.
To test the service you should be able to copy or click on the url and see the service as we did earlier.
Reference your AngularJS files
We are finally ready to connect the WebApp to the service. To do this we need to reference the js classes in the Index.html, so that it can find the AngaularJS libraries and modules.
The page we are going to build is very simple. At the same time it completes the project from start to finish.
To bind to the app and controll we need to add the application directive and the controller directive in the body
Finally we need to create a table and bind it to the JSON data provided by our service using the repeat directive.
Don't forget, as I did, to set the WebApp as the startup project, by right-clicking the project file and selecting Set as StartUp Project.
The simple results are show below.
History
22 Feb 2016 - Submitted | http://126kr.com/article/13hs9d3h49 | CC-MAIN-2017-09 | refinedweb | 1,459 | 55.34 |
How to control a servo motor with an ESP32 development board
When I try to reuse the Ardunio Sketch to control a servo motor with a ESP8266, I encountered the following error during compile time:
WARNING: library Servo claims to run on (avr, sam, samd, nrf52, stm32f4) architecture(s) and may be incompatible with your current board which runs on (esp32) architecture(s).
In file included from /Users/i309663/Documents/learning/Arduino-sketches/sketch_arduino_servo/sketch_arduino_servo.ino:1:0:
/Users/i309663/Arduino.1.8.7/Arduino.app/Contents/Java
Error compiling for board ESP32 Dev Module.
Therefore, I had to find another way to control my SG90 servo motor with an ESP32 development board.
Given that, this post shows how to control a servo motor with an ESP32 development board.
/>
How to connect your servo motor to your ESP32 development board
If you look at your servo motor data sheet, then you will find information about how to connect your servo motor.
For example, the SG90 servo motor data sheet indicated that the:
- orange wire has to be connected to a pin on your ESP32 that can apply pulse width modulation.
- red wire has to be connected to VCC.
- brown wire has to be connected to ground.
Given that, this is how I had connected my SG90 servo motor to my ESP32 development board:
/>
/>
As shown above, I had connected the:
- orange wire of my SG90 servo motor to GPIO13 on my ESP32 development board.
- red wire of my SG90 servo motor to 5V pin on my ESP32 development board.
- brown wire of my SG90 servo motor to GND pin on my ESP32 development board.
Writing an Arduino Sketch to control a servo motor connected to an ESP32 board
Once you have connected your servo motor to your ESP32 board, you can write the software to control it.
If you enable ESP32 Development on Arduino IDE, then you can upload an Arduino Sketch to your ESP32 board to control servo motor.
Installing a library to help us control servo motors connected to an ESP32 development board
Since I was not able use the default Arduino Servo library, I had to find another library to control the servo motor.
Given that, I proceeded to install the ESP32Servo library by John K. Bennett and Kevin Harrington.
In order to do so, I went to Tools -> Manage Libraries... after my Arduino IDE had started. After I had done so, the Library Manager window appeared in the foreground. Given that, I search for ESP32Servo and installed the ESP32Servo library by John K. Bennett and Kevin Harrington:
/>
Example Arduino Sketch to control a servo motor connected to an ESP32 development board
Once I had installed the library, I took out parts of an example sketch from the library and wrote the following sketch:
#include <ESP32Servo.h> Servo myservo; // create servo object to control a servo // Recommended PWM GPIO pins on the ESP32 include 2,4,12-19,21-23,25-27,32-33 int servoPin = 13; void setup() { myservo.setPeriodHertz(50); myservo.attach(servoPin); } void loop() { myservo.write(0); delay(2000); myservo.write(180); delay(2000); }
So what will the sketch do?
First of all, we include the
ESP32Servo library into the sketch.
After that, we create a
Servo object for controlling the servo.
When the
setup function is called, we set the frequency of the PWM period to 50Hz. After that, we attach the Servo object to the GPIO13 pin of our ESP32 development board.
Whenever the
loop function is called, we position the servo motor at an angle of 0 and 180 degrees with a 2 seconds delay in between calls to
myservo.write.
After uploading the Arduino Sketch to my ESP32 development board, the servo motor starts to rotate to 0 and 180 degrees in 2 seconds interval: | https://www.techcoil.com/blog/how-to-control-a-servo-motor-with-an-esp32-development-board/ | CC-MAIN-2022-40 | refinedweb | 635 | 52.7 |
lexically - lexically import functions from non-lexical exporters
version 0.01
package Foo; use Moose; use lexically 'Scalar::Util' => 'reftype';
This pragma turns normal package-based exporter modules into lexical exporters. This can be useful to ensure that your package namespace doesn't get polluted (preventing the need for something like namespace::clean entirely).
No known bugs.
Please report any bugs to GitHub Issues at.
You can find this documentation for this module with the perldoc command.
perldoc lexically
You can also look for information at:
Jesse Luehrs <doy@tozt.net>
This software is Copyright (c) 2013 by Jesse Luehrs.
This is free software, licensed under:
The MIT (X11) License | http://search.cpan.org/dist/lexically/lib/lexically.pm | CC-MAIN-2017-47 | refinedweb | 110 | 51.55 |
How to Deploy ML Models into AWS with Elastic Beanstalk
Want to share your content on python-bloggers? click here.
In the past, we have provided examples of how to build a Flask Rest API, how to build and deploy a Machine Learning Web App and how to deploy a Flask API with Digital Ocean. Today, we will provide a hands-on example of how to deploy flask applications of Machine Learning Models into AWS with Elastic Beanstalk.
A Use Case Scenario
Assume that you work as a Data Scientist and you built a Machine Learning Model that you want to share with other people. The most common way to share your model is with a Flask Restful API but you will need a server. For this case, you can use the Elastic Beanstalk, which.
Build the Flask API
In another post, we have provided an example of how to run sentiment analysis in Python. Let’s assume that we have been asked to build an API which takes as an input a text and it returns the sentiment, if it is Positive, Negative, or Neutral. For this task you should create a new environment and then freeze it by creating the
requirements.txt file.
The
application.py file is the following:
from flask import Flask, request, jsonify from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer analyzer = SentimentIntensityAnalyzer() application = Flask(__name__) def get_sentiment(my_text): vs = analyzer.polarity_scores(my_text) sentiment = '' if vs['compound'] >= 0.05: sentiment = 'Positive' elif vs['compound'] <= -0.05: sentiment = 'Negative' else: sentiment = 'Neutral' return(sentiment) @application.route("/endpoint", methods=['GET','POST']) def sentiment_endpoint(): if request.method == 'POST': json_dict = request.get_json() if 'my_text' in json_dict: result = get_sentiment(json_dict['my_text']) return jsonify({'output' : result}) else: return jsonify({ "status": "failed", "message": "parameter 'my_text' is required!" }) if request.method == 'GET': my_text = request.args.get('my_text') result = get_sentiment(my_text) return jsonify({'output' : result}) if __name__=='__main__': application.run()
So we let’s see if our API works as expected locally.
Test a POST request using Postman
We will give as input the “Awesome! this is really cool!” and we get as output Positive
Test a GET request using Postman
We will give as input the “Awful! A really bad day” and we get as output Negative
Requirements
Since we confirmed that the API works, we are ready to deploy it. The last thing that we will need to do is to create the
requirements.txt files tying the command in our environment:
pip freeze > requirements.txt
The requirements.txt files is the following:
certifi==2020.12.5 chardet==4.0.0 click==7.1.2 Flask==1.1.2 idna==2.10 itsdangerous==1.1.0 Jinja2==2.11.3 MarkupSafe==1.1.1 requests==2.25.1 urllib3==1.26.3 vaderSentiment==3.3.2 Werkzeug==1.0.1
Finally, we will need to create a zip file that contains the application.py and the requirements.txt files and we will upload it to the Beanstalk. Important note: Within the zip file should not be any other sub-folder because the beanstalk will not be able to find the files.
Deploy to Elastic Beanstalk
We will need to sign in to AWS Console and go to the Elastic Beanstalk. We click on the orange button “Create Application“. For the application name, we can type my_sentiment_api. For the platform, choose Python and for the application code, upload the .zip file that you have created above.
Then click on Create Application and wait for around 5 minutes. Then, the API will be running and we get the API URL:
Let’s see, if we can send a request using the URL. We will test it with Postman. Let’s try this text: “Perfect! We deployed our first API. Amazing“
Calling the Flask API with Python
Since we have deployed an API, it means that everyone can use it. Let’s see, how a can call the API with Python (for eg. POST request).
We will get the sentiment of the following three sentences:
[‘this is cool’, ‘this is awful’, ‘this is my blog’]
import requests, json def my_post(raw_text): url = '' headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'} text = json.dumps({'my_text':raw_text}) r = requests.post(url, data=text, headers=headers) return r.json()['output'] samples = ['this is cool', 'this is awful', 'this is my blog'] for s in samples: print(my_post(s))
Output:
Positive Negative Neutral
Delete your Elastic Beanstalk Environment
As you know, AWS Elastic Beanstalk is not free. So, in order to avoid any extra charges, you will need to delete the environment.
The Takeaway
Elastic Beanstalk provides an easy way to deploy quick and dirty Flask APIs. Here you can find the steps that we described above and also here you can find more info.
Want to share your content on python-bloggers? click here. | https://python-bloggers.com/2021/02/how-to-deploy-ml-models-into-aws-with-elastic-beanstalk/ | CC-MAIN-2021-10 | refinedweb | 804 | 57.57 |
This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.
This is an old patch which we never finished discussing. Its purpose is to improve the code generated by the x86 back end for strcmp. Under the right conditions this is compiled to a repz cmpsb instruction, but then we generate three unnecessary instructions right afterward. For instance, the somewhat silly example if (!strcmp ("foo", "bar")) a(); compiles to movl $.LC1, %edi movl $.LC0, %esi cld repz cmpsb * seta %dl * setb %al * cmpb %al, %dl jne .L5 call a .L5: without the patch. The three starred instructions are unnecessary, and the patch removes them. [Pretend for the moment that we didn't know what the strings were at compile time.] The patch works by (a) fixing a bug in combine.c that causes it not to recognize the seta/setb/cmp sequence, and (b) adding a dummy (set (reg cc) (reg cc)) pattern to i386.md so combine thinks it can make the simplification. The dummy insn goes away in the next pass that deletes no-op moves. It would be better to teach combine to delete no-op moves it generates; we can get things like (set (pc) (pc)) out of combine as well as this. At the moment, however, combine is emphatically not prepared to do that, and I don't have time to do the legwork. This patch is safe, simple, and solves a real problem. One of the deltas in combine.c just removes a redundant test. I generated the combine.c diff with -b so this would be obvious; in my tree, I corrected the indentation as well. zw * combine.c (try_combine): Remove redundant test. (use_crosses_set_p): If the last set has been deleted, it doesn't count. * i386.md (*cc_noop_move, *pc_noop_move): Dummy insns to help combine. =================================================================== Index: combine.c --- combine.c 2000/09/19 04:49:44 1.156 +++ combine.c 2000/10/01 01:21:32 @@ -2517,8 +2517,6 @@ try_combine (i3, i2, i1, new_direct_jump if (i3_subst_into_i2 && GET_CODE (PATTERN (i2)) == PARALLEL) { - if (GET_CODE (PATTERN (i2)) == PARALLEL) - { for (i = 0; i < XVECLEN (PATTERN (i2), 0); i++) if (GET_CODE (SET_DEST (XVECEXP (PATTERN (i2), 0, i))) == REG && SET_DEST (XVECEXP (PATTERN (i2), 0, i)) != i2dest @@ -2532,7 +2530,6 @@ try_combine (i3, i2, i1, new_direct_jump for (link = LOG_LINKS (temp); link; link = XEXP (link, 1)) if (XEXP (link, 0) == i2) XEXP (link, 0) = i3; - } if (i3notes) { @@ -11596,7 +11593,10 @@ use_crosses_set_p (x, from_cuid) #endif for (; regno < endreg; regno++) if (reg_last_set[regno] - && INSN_CUID (reg_last_set[regno]) > from_cuid) + /* If the last set has been deleted, it doesn't count. */ + && INSN_CUID (reg_last_set[regno]) > from_cuid + && ! INSN_DELETED_P (reg_last_set [regno]) + && GET_CODE (reg_last_set [regno]) != NOTE) return 1; return 0; } =================================================================== Index: config/i386/i386.md --- config/i386/i386.md 2000/09/29 11:24:13 1.183 +++ config/i386/i386.md 2000/10/01 01:21:33 @@ -1237,6 +1237,19 @@ [(set_attr "type" "icmp") (set_attr "mode" "QI")]) +;; Dummy insns to help combine. +(define_insn "*cc_nop_move" + [(set (reg 17) (reg 17))] + "" + "* abort ();" + [(set_attr "type" "other")]) + +(define_insn "*pc_nop_move" + [(set (pc) (pc))] + "" + "* abort ();" + [(set_attr "type" "other")]) + ;; These implement float point compares. ;; %%% See if we can get away with VOIDmode operands on the actual insns, ;; which would allow mix and match FP modes on the compares. Which is what | https://gcc.gnu.org/ml/gcc-patches/2000-09/msg01164.html | CC-MAIN-2019-51 | refinedweb | 543 | 75.5 |
UnrealScript is a programming language designed to map naturally onto the needs of game programming within [Epic Games]' Unreal Engine.
UnrealScript is bytecode based: the code is compiled into a series of bytecodes similar to p-code or the Java bytecodes. This way UnrealScript remains platform independent and eases porting to other platforms like the Mac or consoles. UnrealScript is also a garbage collected language. All objects and actors in Unreal are garbage-collected using a tree-following garbage collector similar to that of the Java VM.
The reasoning for investigating the relative performance of UnrealScript vs. Lua is to see if Lua can be used in a game engine in the same fashion that UnrealScript has so successfully been used across Unreal Engine based games.
Lua and UnrealScript are pretty different languages. They are both compiled to bytecodes, executed thru a virtual machine, offer a pointerless environment with automatic garbage collection, and provide a secure execution sandbox. This is where their similarities end.
UnrealScript is a strongly typed language like Ada and C++. This provides the benefit of catching unintentional type errors at compile time while sacrificing some flexibility. Lua on the other hand is dynamically typed. In practice this can lead to some wasted debugging time in some cases, but is not as big a problem as it first seems. Still in my opinion Lua could use a lint like pass before compilation.
UnrealScript also supports major concepts like time, state, properties, and networking thru explicit language features. This removes alot of complexity that would be required if implemented at the script level. Naturally Lua lacks these features as it's meant for general purpose use, but it's support for meta-mechanisms could be used to provide similar features.
Based on the popularly quoted performance approximation, Lua is 10x slower than C code. Epic claims that UnrealScript is a 20x performance hit to C++ code. Below I've ported several benchmarks from [The Great Win32 Computer Language Shootout] to UnrealScript in an attempt to do a direct performance comparison.
To do all timing I used wrote a small testing function in Lua which times the tested code with os.clock() several times in a loop. It then throws out the fastest and slowest result and averages the times to get a final timing. UnrealScript is more complex as none of the functions documented for timing code report consistant results. So I instead launch them via UCC and a [Commandlet]. To remove the UCC launch overhead I time an empty unreal function which I then subract from the tests.
The Lua release used is 5.0.2 (the latest stable release), UnrealScript was running within Unreal Tournament 2004 build 3323, and the C++ test was done in Microsoft Visual C++ .NET 2003.
All tests performed on an Intel P4 2.8GHz with 1GB of memory.
The Lua5 benchmark for Array Access in the shootout has a bug (a superfloues "+ 1" in Line 10 ). I've corrected it for the test below.
// -*- mode: c++ -*- // $Id: ary3.g++,v 1.2 2001/06/20 03:20:02 doug Exp $ // #include <iostream> #include <vector> using namespace std; int main(int argc, char *argv[]) { int i, k, n = ((argc == 2) ? atoi(argv[1]) : 1); typedef vector<int> ARY; ARY x(n); ARY y(n); for (i=0; i<n; i++) { x[i] = i + 1; } for (k=0; k<1000; k++) { for (int i = n - 1; i >= 0; --i) { y[i] += x[i]; } } cout << y[0] << " " << y.back() << endl; }Results:
static final function string ArrayTest( optional int n ) { local int i, k; local array<int> x; local array<int> y; if ( n == 0 ) { n = 1; } x.Length = n; y.Length = n; for ( i = 0; i < n; i++ ) { x[i] = i + 1; } for ( k=0; k<1000; k++ ) { for (i = n-1; i >= 0; i--) { y[i] += x[i]; } } return ( y[0]$ " " $y[n-1] ); }Results:
UnrealScript has protection against runaway loops which is triggered by the test at over 3000. So this is all we get to go on for this test.
function array_test( n ) local x, y = {}, {} for i=1,n do x[i] = i y[i] = 0 end for k=1,1000 do for j=n,1,-1 do y[j] = y[j] + x[j] end end return y[1] .. " " .. y[n] endResults:
Lua is performing at around 1/7th the speed of C++ for n=1000 and 1/40th for n=7000. It is about 24% faster than UnrealScript.
Please comment on the results and add your feedback here.
* I did the same array test in an Intel P4 2G (with 512 Mbytes RAM) and got 0.31 sec for n=1000 and 0.94 sec for n=3000. Is my machine so much faster than yours? (-- Roberto)
* Doh... it was something stupid. My profiler was instumenting lua.exe. I re-ran the tests and put my results above. I thought those numbers seemed weird. My new problem is finding an accurate timer in Unreal. Clock/UnClock? is unreliable on my box -- Tom
* In unrealscript you can use the stopwatch() function as a timer. It's not bug-free (in build 3355) so loop it and the code about 20 times to get a larger set of results. You can disable the loop runaway check with -norunaway param. -- Switch`
* If you used Clock and UnClock? to log the results, keep in mind that the stuff that comes out is actually is milliseconds and not seconds. So if you clock(f) and then unclock(f), f is in miliseconds. I am unsure if that was taken into consideration. -- Solid Snake
* Clock uses CPU cycles and isn't safe, it wraps around. So you can only use it for really small timings. Another thing to be aware of is that there's an start-up "issue" with the UnrealEngine?, the whole environment needs to be set-up and stuff like that. At the beginning UnrealScript is rather slow, running the same code a 2nd time gives better results, or even waiting a couple seconds before running the benchmark also has better results. In the real world this start-up issue is not a problem, it just might skew the benchmark results. I don't know about Lua, but UnrealScript is not optimized during compiling. Writing ++i is faster than i++. Ofcourse these things shouldn't matter because the average users wouldn't know that either. -- elmuerte
* when you do performance-timings, you should _NOT_ take the average of all the runs you time, but only THE BEST one: it is safe to assume that the actual execution time is the same each time around, so the only differences you get are because the OS-Scheduler is interfering. Thus the time that comes closest to the "true" execution time of your script is the one with the shortest runtime.
^^^^^^ Beware this advice. In my experience this is quite misleading. For example you will then assume the most lightweight execution portions of your application run to be the best performance, this is plainly misleading. You _should_ average your performance testing over a number of identical, reproducable runs, so that you have comparative benchmarks to test against. There are far more things than just the OS-Scheduler that can effect the performance of a script run. So beware the above advice. -- Grover. | http://lua-users.org/wiki/LuaVersusUnrealScript | crawl-002 | refinedweb | 1,227 | 73.37 |
Yep... That's the fix. IIRC, it also fixes Tomcat
startup delays. If it's not in there, I should commit
it :)
But yeah, it's not an APR issue ;)
Sean Neeley wrote:
>
> Someone sent me this patch on the tomcat mailing list, which I believe
> does the same thing:
>
> bash-2.03$ diff -c network.c network.c.orig
> *** network.c Mon Feb 6 12:50:54 2006
> --- network.c.orig Mon Feb 6 12:50:11 2006
> ***************
> *** 385,391 ****
> UNREFERENCED_STDARGS;
> TCN_ASSERT(sock !=3D 0);
> TCN_ASSERT(s->sock !=3D NULL);
> + apr_socket_opt_set( s->sock, APR_SO_REUSEADDR, 1 );
> return (jint)apr_socket_bind(s->sock, a);
> }
>
> - Sean
>
> -----Original Message-----
> From: Jim Jagielski [mailto:jim@jagunet.com]=20
> Sent: Wednesday, February 22, 2006 11:02 AM
> To: Sean Neeley
> Cc: Garrett Rooney; dev@apr.apache.org
> Subject: Re: APR leaves port bound when terminated?
>
> Sorry if this wasn't clear: the reason that SO_REUSEADDR
> exists (and it's APR cousin) is to remove this
> problem, and allow for the tcp/ip stack to
> reuse it. So the fact that you're seeing this
> is likely due to that option isn't being sent.
>
> I believe the patch is to adjust
> TCN_IMPLEMENT_CALL(jint, Socket, bind) in network.c
> and add apr_socket_opt_set(s->sock, APR_SO_REUSEADDR, 1)
> right before the apr_socket_bind call...
>
> On Feb 21, 2006, at 7:05 PM, Sean Neeley wrote:
>
> > I would be happy to test a version of APR with different socket =20
> > options.
> > Thanks.
> >
> > - Sean
> >
> > -----Original Message-----
> > From: rooneg@gmail.com [mailto:rooneg@gmail.com] On Behalf Of Garrett
> > Rooney
> > Sent: Tuesday, February 21, 2006 5:54 PM
> > To: jim@jagunet.com
> > Cc: Sean Neeley; dev@apr.apache.org
> > Subject: Re: APR leaves port bound when terminated?
> >
> > On 2/21/06, Jim Jagielski <jim@jagunet.com> wrote:
> >> I would guess this in an artifact of SO_REUSEADDR
> >
> > Actually, wouldn't setting SO_REUSEADDR (or APR_SO_REUSEADDR in this
> > case) make the problem go away? I'd assumed that the code in Tomcat
> > just wasn't doing that or something.
> >
> > -garrett
> >
>
--
===========================================================================
Jim Jagielski [|] jim@jaguNET.com [|]
"If you can dodge a wrench, you can dodge a ball." | http://mail-archives.apache.org/mod_mbox/apr-dev/200602.mbox/%3C200602221719.k1MHJa703012@devsys.jaguNET.com%3E | CC-MAIN-2016-26 | refinedweb | 350 | 67.76 |
TableGen's purpose is to help a human develop and maintain records of domain-specific information. Because there may be a large number of these records, it is specifically designed to allow writing flexible descriptions and for common features of these records to be factored out. This reduces the amount of duplication in the description, reduces the chance of error, and makes it easier to structure domain specific information.
The core part of TableGen parses a file, instantiates the declarations, and hands the result off to a domain-specific "TableGen backend" for processing. The current major user of TableGen is the LLVM code generator.
Note that if you work on TableGen much, and use emacs or vim, that you can find an emacs "TableGen mode" and a vim language file in llvm/utils/emacs and llvm/utils/vim directory of your LLVM distribution, respectively.
TableGen files consist of two key parts: 'classes' and 'definitions', both of which are considered 'records'.
TableGen records have a unique name, a list of values, and a list of superclasses. The list of values is main data that TableGen builds for each record, it is this that holds the domain specific information for the application. The interpretation of this data is left to a specific TableGen backend, but the structure and format rules are taken care of and fixed by TableGen.
TableGen definitions are the concrete form of 'records'. These generally do not have any undefined values, and are marked with the 'def' keyword.
TableGen classes are abstract records that are used to build and describe other records. These 'classes' allow the end-user to build abstractions for either the domain they are targetting (such as "Register", "RegisterClass", and "Instruction" in the LLVM code generator) or for the implementor to help factor out common properties of records (such as "FPInst", which is used to represent floating point instructions in the X86 backend). TableGen keeps track of all of the classes that are used to build up a definition, so the backend can find all definitions of a particular class, such as "Instruction".
With no other arguments, TableGen parses the specified file and prints out all of the classes, then all of the definitions. This is a good way to see what the various definitions expand to fully. Running this on the X86.td file prints this (at the time of this writing):
... def ADDrr8 { // Instruction X86Inst I2A8 Pattern string Name = "add"; string Namespace = "X86"; list<Register> Uses = []; list<Register> Defs = []; bit isReturn = 0; bit isBranch = 0; bit isCall = 0; bit isTwoAddress = 1; bit isTerminator = 0; dag Pattern = (set R8, (plus R8, R8)); bits<8> Opcode = { 0, 0, 0, 0, 0, 0, 0, 0 }; Format Form = MRMDestReg; bits<5> FormBits = { 0, 0, 0, 1, 1 }; ArgType Type = Arg8; bits<3> TypeBits = { 0, 0, 1 }; bit hasOpSizePrefix = 0; bit printImplicitUses = 0; bits<4> Prefix = { 0, 0, 0, 0 }; FPFormat FPForm = ?; bits<3> FPFormBits = { 0, 0, 0 }; } ...
This definition corresponds to an 8-bit register-register add instruction in the X86. The string after the 'def' string indicates the name of the record ("ADDrr8" in this case), and the comment at the end of the line indicates the superclasses of the definition. The body of the record contains all of the data that TableGen assembled for the record, indicating that the instruction is part of the "X86" namespace, should be printed as "add" in the assembly file, it is a two-address instruction, has a particular encoding, etc. The contents and semantics of the information in the record is specific to the needs of the X86 backend, and is only shown as an example.
As you can see, a lot of information is needed for every instruction supported by the code generator, and specifying it all manually would be unmaintainble, prone to bugs, and tiring to do in the first place. Because we are using TableGen, all of the information was derived from the following definition:
def ADDrr8 : I2A8<"add", 0x00, MRMDestReg>, Pattern<(set R8, (plus R8, R8))>;
This definition makes use of the custom I2A8 (two address instruction with 8-bit operand) class, which is defined in the X86-specific TableGen file to factor out the common features that instructions of its class share. A key feature of TableGen is that it allows the end-user to define the abstractions they prefer to use when describing their information.
TableGen runs just like any other LLVM tool. The first (optional) argument specifies the file to read. If a filename is not specified, tblgen reads from standard input.
To be useful, one of the TableGen backends must be used. These backends are selectable on the command line (type 'tblgen --help' for a list). For example, to get a list of all of the definitions that subclass a particular type (which can be useful for building up an enum list of these records), use the --print-enums option:
$ tblgen X86.td -print-enums -class=Register AH, AL, AX, BH, BL, BP, BX, CH, CL, CX, DH, DI, DL, DX, EAX, EBP, EBX, ECX, EDI, EDX, ESI, ESP, FP0, FP1, FP2, FP3, FP4, FP5, FP6, SI, SP, ST0, ST1, ST2, ST3, ST4, ST5, ST6, ST7, $ tblgen X86.td -print-enums -class=Instruction ADCrr32, ADDri16, ADDri16b, ADDri32, ADDri32b, ADDri8, ADDrr16, ADDrr32, ADDrr8, ADJCALLSTACKDOWN, ADJCALLSTACKUP, ANDri16, ANDri16b, ANDri32, ANDri32b, ANDri8, ANDrr16, ANDrr32, ANDrr8, BSWAPr32, CALLm32, CALLpcrel32, ...
The default backend prints out all of the records, as described above.
If you plan to use TableGen for some purpose, you will most likely have to write a backend that extracts the information specific to what you need and formats it in the appropriate way.
TableGen doesn't care about the meaning of data (that is up to the backend to define), but it does care about syntax, and it enforces a simple type system. This section describes the syntax and the constructs allowed in a TableGen file.
TableGen supports BC:
Note that all of the values have rules specifying how they convert to values for different types. These rules allow you to assign a value like "7" to a "bits<4>" value, for example.
As mentioned in the intro, classes and definitions (collectively known as 'records') in TableGen are the main high-level unit of information that TableGen collects. Records are defined with a def or class keyword, the record name, and an optional list of "template arguments". If the record has superclasses, they are specified as a comma seperated 'let' SpecialFP : FPFormat.
TableGen supports the 'include' token, which textually substitutes the specified file in place of the include directive. The filename should be specified as a double quoted string immediately after the 'include'-seperated list of bindings to apply, and one of more records to bind the values in. Here are some examples:
let isTerminator = 1, isReturn = 1 in def RET : X86Inst<"ret", 0xC3, RawFrm, NoArg>; let isCall = 1 in // All calls clobber the non-callee saved registers... let Defs = [EAX, ECX, EDX, FP0, FP1, FP2, FP3, FP4, FP5, FP6] in { def CALLpcrel32 : X86Inst<"call", 0xE8, RawFrm, NoArg>; def CALLr32 : X86Inst<"call", 0xFF, MRMS2r, Arg32>; def CALLm32 : X86Inst<"call", 0xFF, MRMS2m, Arg32>; }
File-scope "let" expressions are often useful when a couple of definitions need to be added to several records, and the records do not otherwise need to be opened, as in the case with the CALL* instructions above.
How they work, how to write one. This section should not contain details about any particular backend, except maybe -print-enums as an example. This should highlight the APIs in TableGen/Record.h.
This is just a temporary, convenient, place to put stuff about the code generator before it gets its own document. This should describe all of the tablegen backends used by the code generator and the classes/definitions they expect. | http://llvm.org/releases/1.2/docs/TableGenFundamentals.html | CC-MAIN-2016-26 | refinedweb | 1,298 | 56.39 |
Troubleshooting Data Types
This page lists some common problems that can occur when performing operations on intrinsic data types.
When you work with floating-point numbers (Single Data Type (Visual Basic) and Double Data Type (Visual Basic)), keep in mind, while, using the Abs method of the Math class in the System namespace.
Determine an acceptable maximum difference, such that you can consider the two quantities to be equal for practical purposes if their difference is no greater.
Compare the absolute value of the difference to the acceptable difference.
The following example demonstrates both improper and proper preceding example uses the ToString method of the Double structure so that it can specify greater precision than the CStr keyword uses. The default is 15 digits, but the "G17" format extends it to 17 digits. greater precision.
To find the integer remainder of floating-point quantities
Declare variables as Decimal.
Use the literal type character D to force literals to Decimal, in case their values are too large for the Long data type. preceding example uses the ToString method of the Double structure so that it can specify greater default to Double and decimalRemainder receives the same inaccurate value as doubleRemainder.
Boolean Data Type (Visual Basic) values are not stored as numbers, and the stored values are not intended to be equivalent to numbers. For compatibility with previous versions, Visual Basic provides conversion keywords (CType Function, it is necessary to mix Boolean and numeric values, be sure that you understand the conversion method you choose.
Conversion in Visual Basic
When you use the CType or CBool conversion keywords to convert numeric data types to Boolean, 0 becomes False and all other values become True. When you convert Boolean values to numeric types using the conversion keywords, False becomes 0 and True becomes -1.
Conversion in the Framework
In the absence of any type characters, Visual Basic assumes default data types for literals. The default type for a character literal — enclosed within double quotes (" ") — within double..
The String Data Type (Visual Basic) participates in very few widening conversions. String widens only to itself and Object, and only Char and Char() (a Char array) widen to String. This is because String variables and constants can contain values that other data types cannot accommodate.
When the type checking switch (Option Strict Statement) is On, the compiler disallows all implicit narrowing conversions, including those involving String. Your code can still use conversion keywords such as CStr and CType Function, which direct the .NET Framework to attempt the conversion. attempt a conversion.
If you need to convert from String to another data type, the safest procedure is to enclose the attempted conversion in the Try...Catch...Finally Statement (Visual Basic). This allows you. | https://msdn.microsoft.com/en-US/library/ae382yt8(v=vs.80).aspx | CC-MAIN-2015-27 | refinedweb | 456 | 53.1 |
How to Create a Chat Room in Java
When you start to think about how to create your own personal chat room, probably the first thing that you think of is related to network I/O, sockets, etc. and maybe you begin to feel discouraged. Don't be! There is a great solution that makes implementing an application like this easy: JGroups.
What is JGroups? It is a reliable multicast system written in the Java language. From Wikipedia: "Multicast is the delivery of a message or information to a group of destination computers simultaneously in a single transmission from the source".
In simple words, we can imagine our chat room as a group. Each user represents a node in this group, and every time a message is sent by a node, it is delivered to all the other nodes in the group.
Basic Concepts of JGroups
In our chat room we can forget sockets and other low level network elements, but we have to learn some basic concepts about JGroups before continuing.
As already stated, we can see our chat room as a group. To join a group and to send/receive messages, we need channels. Every channel has its own address and it is connected to a group using the group name. So a group can have many channels associated to it (in our case, one channel per user).
Channels can always retrieve a list of the member addresses in the group (basically a user can see who is in the chat room). We can even be notified when a user leaves/joins the chat room.
It's Code Time!
import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.ReceiverAdapter; import org.jgroups.View; import org.jgroups.util.Util; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.LinkedList; import java.util.List; public class GUIChat extends ReceiverAdapter { final List<String> history = new LinkedList<String>(); private JChannel channel; private String userName = System.getProperty("user"); private JTextField textField; private JTextArea textArea; public static void main(String[] args) throws Exception { new GUIChat().start(); } public void viewAccepted(View newView) { appendText("** in room: " + newView + "\n"); } public void receive(Message msg) { String line = msg.getObject().toString(); synchronized(history) { history.add(line); appendText(line); } } public void getState(OutputStream output) throws Exception { synchronized(history) { Util.objectToStream(history, new DataOutputStream(output)); } } public void setState(InputStream input) throws Exception { List<String> list = (List<String>) Util.objectFromStream(new DataInputStream(input)); synchronized(history) { history.clear(); history.addAll(list); } appendText("received " + list.size() + " messages in chat history:\n"); for(String str: list) appendText(str); } private void start() throws Exception { final JPanel panel = createPanel(); channel = new JChannel(); channel.setReceiver(this); channel.connect("ChatCluster"); channel.getState(null, 10000); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame("Simple Chat"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.pack(); frame.setVisible(true); } }); } private JPanel createPanel() { JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = c.weighty = 1.0; textArea = new JTextArea(20, 40); textArea.setEditable(false); panel.add(new JScrollPane(textArea), c); c.weightx = c.weighty = 0.0; c.fill = GridBagConstraints.HORIZONTAL; JPanel messageContainer = new JPanel(new FlowLayout()); messageContainer.add(new JLabel("Message:")); textField = new JTextField(40); textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String line="[" + userName + "] " + textField.getText() + "\n"; try { channel.send(new Message(null, null, line)); } catch (Exception e) { e.printStackTrace(); } } }); messageContainer.add(textField); JButton button = new JButton("Bye!"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { channel.close(); System.exit(0); } }); messageContainer.add(button); panel.add(messageContainer, c); return panel; } private void appendText(String newline) { textArea.append(newline); textField.setText(""); textArea.setCaretPosition(textArea.getDocument().getLength()); } }
The code above represents an all-in-one client/server chat room based on JGroups and Swing. The main features are:
- Keeping a chat history (as a list in memory) to send to any new user connected.
- Sending and receiving messages to/from other users.
- Being notified when someone leaves/joins the chat.
First of all, GUIChat class extends org.jgroups.ReceiverAdapter that has most of the code ready for us, and we limit to override only a few methods of it.
To start the chat, we need to define the channel and its group:
channel = new JChannel();
channel.setReceiver(this);
channel.connect("ChatCluster");
channel.getState(null, 10000);
and when we leave the chat the channel must be closed:
channel.close();
To keep the chat history updated, we use the method:
public void receive(Message msg)
This method is used when we receive messages from other users (and ourself) too. Indeed, don't forget that in a multicast system, messages are sent to all members of the group including the sender.
So when a message is received, it is appended on the history-list and displayed in the text area.
To send a message to the other members we use the method:
channel.send(new Message(null, null, line));
The constructor parameters for the Message class are, respectively, destination address, source address, and data to send. Null on the destination address will send the message to all the group's members.
When a new user joins the chat, the already present members send him/her the history with the method:
public void getState(OutputStream output) throws Exception
that 'streams' (marshalling) the history-list object.
The history received is converted (unmarshalling) to history-list object with the method:
public void setState(InputStream input) throws Exception
When a user joins or leaves the chat all the other members are notified via:
public void viewAccepted(View newView)
To have a better comprehension of the API and the functionalities of JGroups I recommend that you read the official documentation here.
Compiling and Running the Application
First, create a folder where you will create the GUIChat.java file with the code above. Then download from here the JGroups jar file (I have used jgroups-3.2.8.Final.jar).
To compile run:
javac -cp jgroups-3.2.8.Final.jar GUIChat.java
and to run the application:
java -cp .:jgroups-3.2.8.Final.jar -Duser=john -Djava.net.preferIPv4Stack=true GUIChat
You can run different instances of the chat on the same machine or on different machines in the same network.
Well, that's it guys, I hope you enjoyed it!
I share my best form of escapism; my two favourite Adventure Mystery Hidden Object Games and where you can try them and others for Free. | http://hubpages.com/technology/how-to-create-a-chat-room-in-java | CC-MAIN-2017-09 | refinedweb | 1,102 | 50.73 |
Python Modules and Packages
Contents
What are the modules in Python?
A module in Python is defined as files containing python functions, classes or variables which can be used by other programs. When programs grow large in size, we use modules to break them down and make a useful component that can be reused later.
How do I create a module in Python?
For example, if we make calculator.py that contains helpful functions to perform various calculations, we can import this module in another python file where its module name would be a calculator.
Let us create a module for storing our calculations function definitions so that we can use it later in our main.py file.
""" Calculator Module (calculator.py) """ # Function to add two numbers def add(x, y): return x + y # Function to subtract two numbers def subtract(x, y): return x - y # Function to multiply two numbers def multiply(x, y): return x * y # Function to divide two numbers def divide(x, y): return x / y
Here, we have defined four functions to perform basic mathematical operations inside a module named calculator. These functions take in two numbers and return their sum, difference, multiplication, and division.
How to import modules in Python?
Now as we have defined our module, to import that module we use “import” keyword in python. The syntax of import module is
import calculator num1 = 10 num2 = 5 print("Addition: ", calculator.add(num1, num2)) print("Subtraction: ", calculator.subtract(num1, num2)) print("Multiplication: ", calculator.multiply(num1, num2)) print("Division: ", calculator.divide(num1, num2))
The output of the above program is:-
Subtraction: 5
Multiplication: 50
Division: 2.0
What is the from-import statement?
We can import specific functions or classes from the module using from import statement.
from calculator import add num1 = 10 num2 = 5 print("Addition: ", add(num1, num2))
The output of the above program is:-
How to rename a module in Python?
We can rename module under different name as per our convineince.
import calculator as cal num1 = 10 num2 = 5 print("Addition: ", cal.add(num1, num2))
The output of the above program is:-
The dir() built-in function
To get all the list of names defined in the passed module, we can use dir() function. Let us see the following example:-
import calculator print(dir(calculator))
The output of the above program is:-
The reload() function
For a given session, a module is imported once only in Python. This is a good practice in python as it gives efficiency to the program. But, if the module is dynamically changed during the program execution, we may require it to load again. For that, we use the reload() function. The syntax is
Python packages
The package hierarchy allows python program to be broken into the various folder to organize the project. The package is a folder that contains sub-packages, modules, and sub-modules. A directory must contain a file named __init__.py in order for Python to consider it as a package. This file can be left empty but we generally place the initialization code for that package in this file.
Let us consider the following directory structure for our Game Package which contains three sub packages:-
- Sound
- Image
- Level
Importing module from a package
We import modules from the package using a dot operator | https://www.programming-techniques.com/2019/04/python-modules-and-packages.html | CC-MAIN-2020-40 | refinedweb | 553 | 55.44 |
Age: 13
Meet Uno the Arduino powered robot. Some functions include a blinking nose, moving antennas, rotating head, IR distance sensor, twin motor gear box and rotation counters. Uno is made with relatively easy to obtain parts. This project provides a good introduction to Arduino.
Step 1: Materials
Material and tools
• Foam board
• Fimo
• 4 Rare Earth magnets
• 4 small metal plates (from transformer)
• Thrust bearing
• LEDs
• IR distance sensor
• Twin motor gear box with wheels
•JST
• 2 9VDC pin solenoid
• Arduino
• A-B USB cable
•power source
•switch
• Servo
•3 TIP 120 or121
•male header pins
• School glue
• Weld bond
• Hot Glue gun
• Xato knife/carpet cutter
• Pen
• Wire strippers/cutters
•Pliers
•Clear tape
• copper clad
• ferric chloride
• 2 lever switch
• 2 1 µF capacitor
• 30 gauge wire
• 5 1k ohm resistors
• 1 470 ohm resistor
• 2.1mm barrel Jack
Step 2: Cutting
Download the PDF file and print it. rough cut the templates then tape them to the foam board. Next use a new Xato knife blade and a straight edge to cut it out. Cut out 4 pattern A, 1-B, 3-C, 2-D, 1-E, 1-F, 2-G.
Step 3: The Base
Cut out the circle in template B then assemble the gear box to 1: 60. Draw a line through the center of the template. Match the center of the gear box with this line. mark the template on each side of the mounting plate, do the same for the wheels, then cut(see photo). Hot glue the gear box in place then glue the thrust bearing in place(see photo).
Step 4: The Body
Find the center of template F then drill a 3/16'' hole. Put servo knob in the hole and trace the servo then cut out this piece. Reinsert the servo and hot glue it in place. To form body glue 3 A's and 1 F together with white school glue (see photo)then paint. Find the center of piece D and drill a 5/32'' hole. Then line up the hole in the servo horn with the hole in the foam board and hot glue. Drill a 1/4'' hole through piece D and F(see picture for position).
Step 5: The Arms
Paint template G, then insert a L.E.D in to the end and remove. To make a hole push a pen ink cartridge in the arm, stop 1/4'' before the end. Make a hole at the end of the tunnel with a Xacto knife. Run 2 wires through the arm then wire the L.E.D. and push it in the hole. Make two arms.
Step 6: Removable Door
Push a magnet into the top and bottom of the indented edge and glue in place, do the same for the door. Apply metal on the other edges and paint the door.
Step 7: The Head
Find where you want the nose to go on template E and cut a hole to fit the LED, do the same for the "eyes" and glue in place. Before you bake the antennas poke a hole in the bottom with the solenoid. Drill a 3/16 hole in center of piece F. Glue the C's to make a block C, then glue piece E to close the C, and glue F on top. Bracket the solenoid with foam board and hot glue and glue antennas on the solenoid.
Step 8: The PCB
See this instructable.
Step 9: Switches
Drill a hole in the wheels to mach the BB and glue it in place. Cover the little PCBs in hot glue, and line them up so that the BB depresses the lever. There are many options for the main switch the simplest is the toggle switch, but I used a reed switch and SCR.
Step 10: Power
There are a couple different options for power, you can use a 9 volt battery but it won't last long. I used a battery "back back", but you could also use a rechargeable pack as long as it is between 7 and 9 volts.
Step 11: Putting It to Together
First feed the wires from the head through the holes then glue the head on. Next hot glue the base on so the motors face the side without the removable door. Then cut almost all the way through the door in the shape of the big PCB and hollow it out(see picture) and hot glue it in place. Find where you want the arms to go and lightly trace them, after that drill holes to mach the wire holes in the arms and glue them in place.
Step 12: Wiring
Wrap the two grounds of the LED arms together, do the same with the positives and add a 470 ohm resistor. Next, connect the wires from the head to their places on the PCB, do the same with the motors and servo. Now add a 1k resistor between one lever switch wire and ground then connect them to the PCB. Connect the LEDs to the positive and negative wires and do the jack the same way. Now you are done, test it with some basic sketches like blink and sevo sweep. Here is the setup script:
#include <Servo.h>
Servo myservo;
int L1 = 7;
int led1 = 13;
int S1 = 4;
int S2 = 5;
int J1 = A0;
int M1 = 10;
int M2 = 11;
int pos = 0;
void setup()
{
myservo.attach(9);
pinMode(L1, OUTPUT);
pinMode(led1, OUTPUT);
pinMode(S1, INPUT);
pinMode(S2, INPUT);
pinMode(J1, OUTPUT);
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);
}
5 Discussions
3 years ago
kool can u use cardboard instead of foamboard?
Reply 3 years ago
Cardboard would work just fine
Reply 3 years ago
ok thanks
3 years ago on Introduction
looks cool
7 years ago on Introduction
it's head look s like a slime from minecraft :3 | https://www.instructables.com/id/Uno-The-Arduino-Robot/ | CC-MAIN-2019-26 | refinedweb | 985 | 87.55 |
This example scans for any I2C slave address current on the I2C bus.
(I am using a RPi 3B+ with raspbian buster from september release)
Script
trial_smbus.py:
from smbus2 import SMBus channel = 1 i2c = SMBus(channel) for i2c_addr in range(127): try: read_data = i2c.read_byte_data(i2c_addr, 0) except Exception as e: if e.errno == 121: pass # no ACK else: print (e) else: print ("0x{:02X} => ACK!".format (i2c_addr))
It works nicely after a fresh boot of the RPi!
This script (not in the same script) simply ‘plays’ with the same IO pins:
Script
trial_gpio.py:
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)
I run this script, and indeed the GPIO are set as input with pullup resistors.
Now, I run again script
trial_smbus.py, and I got:
[Errno 5] Input/output error
That means 2 things: – that little
trial_gpio.py script set something that SMBus2 does not like. – SMBus2 does not init everything correctly.
Now I reboot and run again script
trial_smbus.py==> works:
Run again
trial_gpio.py.
Run again
trial_smbus.py, does not work.
Run the
wiringpi tool:
gpio mode 8 alt0 gpio mode 9 alt0
Run again
trial_smbus.py, does work.
The easy solution would be to call those 2 command lines with a system call from within python. however wiringpi is deprecated:
The issue I have is that I want a robust implementation with SMBus package. As you know some people might run several other programs prior they run my program, so I want the init to be done robustly.
Is there any alternative to set the pins in the correct mode?
- 1Hi @karelv, Ah, let me see. (1) WiringPi once worked but now deprecated, so I am saying good bye without even once saying Hello. (2) SMBus1 works most of the time, but not always, eg no bus stretching, block read is buggy, but can get around by lowering I2C speed (from 100kHz to 10kHz!), (3) I once thought SMBus2 is new so would be better than SMBus1. I was very wrong. I tried it but gave up almost immediately. My conclusion is that I can only reluctantly bear SMBus1 for a couple of more years. – tlfong01 yesterday
- It is difficult to see what your question is. You cannot have 2 programs setting GPIO unless you release between uses. – Milliways yesterday
- @tlfong01 thanks for your take on SMBus2 vs SMBus1, I have the same view as you had, although for me it is not an option to lower the clock to 10kHz, as it would be way to slow; I would rather like to work at 400kHz, if you know how to do that, feel free to share! – karelv 9 hours ago
- @Milliways, I updated the question. I agree, the 2 scripts I made to show the issue; for isolation from all other clutter I build around it… My point is not to run them in parallel, but if somebody run a program that set some GPIO, and later they run my program it does not work. I don’t like that, and I am looking for a solution. – karelv 9 hours ago
- Hi @karelv, Rpi3B+ I2C is mission impossible: (1) raspberrypi.org/forums/… (2) raspberrypi.org/forums/…. But if you don’t need bus stretching, I heard the rumour aht you can set I2C bus higher than 100kHz. But I need to let my scope to display the real 400kHz or higher wave form to my stupid human eyes. Perhaps I can try to do the possible mission over this weekend. – tlfong01 6 hours ago
- Hi @karelv. GOOD NEWS! I have verified that Rpi4B buster can set I2C speed to 500 kHz without any problem. I did the following test: Ping I2C PWM controller and found every thing OK. Then I repeat ping the same controller and use a scope to display the I2C 500kHz SCL waveform and found it sharp: penzu.com/p/1d0bb304. – tlfong01 1 hour ago
- So I have tested that my python program can ping a device at I2C speed 500kHz. I then increased to 800kHz and found everything OK. Then greedy me tried 1Mhz and got IO error after one or two seconds repeat pinging. I fell back to 800kHz and found everything OK again. So my conclusion: 500kHz OK, 800 kHz still OK. But 1000kHz has IO errors. Fall back to 800 kHz OK again. CONCLUSION: For reliable use, don’t go over 500 kHz. 400 kHz should be OK for the following conditions:Bus 1, only two I2C devices on the bus. WIRING LESS THAN 60 CM LONG. – tlfong01 6 mins ago
- I forgot to mention that as the I2C speed goes up, the “RINGING” (oscillation) at the rising edge of the SCL pulse should also go up, with the result that a positive pulse cannot be read as a positive pulse, thus the I/O ERROR MESSAGE. By the way, this is the end of my comments on I2C speed testing. I will do more speed test later, as I add more and more devices on the same bus, also other that Bus 1. I also need to find out why there is one or two I2C buses configured by dt driver, but not detected, … 😦 – tlfong01 just now Edit
For GPIO 2/3 (pins 3/5) to operate as the I2C bus they must be in a GPIO mode called ALT0.
They are set to this mode when the Linux I2C/SMBus driver is loaded.
The RPi.GPIO module is changing the mode of GPIO 2/3 to INPUT. This stops the proper operation of the I2C bus.
You need to again set the mode to ALT0 for GPIO 2/3 for the bus to operate again.
As far as I am aware the RPi.GPIO module provides no way of setting a GPIO to this mode.
To set GPIO 2 and 3 to mode ALT0 do one of the following.
If the wiringPi gpio utility is installed you can use the command.
gpio -g mode 2 alt0 gpio -g mode 3 alt0
If the pigpio pigs utility is installed you can use the command.
sudo pigpiod # start the daemon if not already running pigs m 2 0 m 3 0
If the raspi-gpio utility is installed you can use the command.
raspi-gpio set 2 a0 raspi-gpio set 3 a0
- Up to gpio, I’m aligned with you, then you start with new stuff. – karelv 9 hours ago
- 1pigs is installed but I got error message:
socket connect failed. – karelv 9 hours ago
- 1raspi-gpio is also installed, no error message, and it works! – karelv 9 hours ago
- 1raspi-gpio seems part of the package ‘raspi-gpio’ (dpkg -S raspi-gpio), and was preinstalled with raspbian buster. – karelv 9 hours ago
- 1I rather stick with raspi-gpio, it works of-the-shelf! Thanks for your help! – karelv 9 hours ago
The mode of each pin is either in, out or any of the other functions (I2C in this case). Pins 3 and 5 are in ALT0 mode by default after reboot if the I2C driver is active. Type
gpio readall on the command line to see which pins are in which mode.
To do the same as
gpio mode 8 alt0 gpio mode 9 alt0
in code, you need to do something like
GPIO.setup(3, GPIO.ALT0) GPIO.setup(5, GPIO.ALT0);
(Not sure about the exact naming at the moment, though).
- 1I like your pure python approach, so I would love it works! I’ve read that RPi.GPIO is working on I2C (5 years ago), but they will NEVER support ALT0 mode as such. I might be wrong of course, so please can you verify the exact naming convention? Thanks. – karelv 9 hours ago
To Answer the additional question you asked in Comments:-
RPi.GPIO has a cleanup command which can be used at the end of the program to restore startup state and should resolve the problem of releasing GPIO pins.
I don’t actually use
RPi.GPIO;
gpiozero does this automatically.
- Thanks, but.. you know, any program can crash accidentally… so I rather work on my init, the trial_gpio,py is just do demonstrate what a wrong starting condition for the trial_smbus.py. – karelv 28 mins ago
Categories: Uncategorized | https://tlfong01.blog/2019/11/21/i2c-speed-tests/ | CC-MAIN-2020-40 | refinedweb | 1,402 | 82.04 |
wcsrtombs - convert a wide-character string to a character string (restartable)
#include <wchar.h> size_t wcsrtombs(char *dst, const wchar_t **src, size_t len, mbstate_t *ps);:
- When a code is reached that does not correspond to a valid character.
- terminating null wide-character, the resulting state described is the initial conversion state.
If ps is a null pointer, the wcsrtombs()csrtombs().
The behaviour of this function is affected by the LC_CTYPE category of the current locale.
If conversion stops because a code is reached that does not correspond to a valid character, an encoding error occurs. In this case, the wcsrtombs() function stores the value of the macro EILSEQ in errno and returns (size_t)-1; the conversion state is undefined. Otherwise, it returns the number of bytes in the resulting character sequence, not including the terminating null (if any).
The wcsrtombs() function may fail if:
- [EINVAL]
- ps points to an object that contains an invalid conversion state.
- [EILSEQ]
- A wide-character code does not correspond to a valid character.
None.
None.
None.
mbsinit(), wcrtomb(), <wchar.h>.
Derived from the ISO/IEC 9899:1990/Amendment 1:1995 (E). | http://pubs.opengroup.org/onlinepubs/007908775/xsh/wcsrtombs.html | CC-MAIN-2016-44 | refinedweb | 186 | 56.76 |
23 May 2012 08:59 [Source: ICIS news]
By Clive Ong
?xml:namespace>
Offers of packaging resins were around $1,600-1,630/tonne (€1,264-1,288/tonne) CFR (cost and freight) NE (northeast)
Spot EPS prices were assessed at $1,660-1,690/tonne CFR NE Asia in the week ended 18 May, down $40/tonne week on week, according to ICIS.
Prices of feedstock SM, on the other hand, have declined to around $1,360/tonne CFR China this week, down by more than 9% from early May, ICIS data showed, amid a flaring up of concerns over the eurozone debt crisis.
The eurozone’s debt crisis, as well as
“Customers [of EPS] are lobbying for parcels below $1,600/tonne, with some indications at around $1,550/tonne,” said a producer in
Weak economic conditions in the
EPS is used for packaging of food and consumer electronics.
“The slower property sector in
While few suppliers have quoted prices below $1,600/tonne CFR NE Asia, some conceded that prices will have to decline if sellers wanted to engage customers.
“Definitely, there will be limited buying interest at $1,600/tonne CFR NE Asia and above. Most buyers are looking at around $1,550/tonne,” said another Taiwanese producer.
Major EPS makers in NE Asia | http://www.icis.com/Articles/2012/05/23/9560458/asia-eps-under-pressure-from-weak-demand-falling-sm-values.html | CC-MAIN-2014-49 | refinedweb | 218 | 64.24 |
ReactGrid is a component for displaying and entering data in a spreadsheet-like way.
On the Internet, you can find many spreadsheets files that e.g. accountants and financial analysts use -one of them, as an inspiration, will be moved from spreadsheet to standalone, fully reactive React.js app. We also visualize common parameters that help in decision-making with the Chart.js library.
ReactGrid was designed to handle complex data displaying and editing in an arbitrary way. We depart from the rule of placing cells in the same order in every row - therefore you are able to add a spreadsheet-like experience to your React app.
Liquidity planner is one of the many cases, in which 90% of React data table components usage is insufficient to recreate the expected look and feel.
Before we start coding, we will talk about good practices that help to make predictable apps. Obviously, it's a good idea to apply them in all projects:
1. Separate the data from ReactGrid
The main concept of reactivity is updating your view every time your data changes. Very often we have no influence on the data structure, but we can map it to the structure that is the most convenient for us. Before the data becomes acceptable by ReactGrid or Chart.js we have to calculate a few variables in a repeatable way. This data lives only “for a moment” and should be independent from data and ReactGrid internal interfaces like
andand
Column
..
Row
import * as React from "react"; import { ReactGrid, Row } from "@silevis/reactgrid"; const App = () => { const [rows, setRows] = React.useState<Row[]>(() => getReactGridRows()); return ( <ReactGrid rows={rows} ...{props} /> ); };
2. Apply changes directly to the data
ReactGrid contains its own encapsulated state to manage many background functionalities, like virtual scrolling or rendering optimizations. This state is based on
andand
rows
- two necessary- two necessary
columns
props. ReactGrid is read-only until you define your own changes handling function, but a good practice is to update data at its source. After that the cycle of reactivity concept is complete.props. ReactGrid is read-only until you define your own changes handling function, but a good practice is to update data at its source. After that the cycle of reactivity concept is complete.
ReactGrid
Be aware of updating data that is directly related with ReactGrid interfaces ⚠️
import * as React from "react"; import { ReactGrid, Row, CellChange } from "@silevis/reactgrid"; const App = () => { const [rows, setRows] = React.useState<Row[]>(() => getReactGridRows()); const handleChanges = (changes: CellChange[]) => { changes.forEach((change) => { setRows(rows => [ ...rows, // ... ]) }); }; return ( <ReactGrid rows={rows} onCellsChanged={handleChanges} {...props} /> ); };
3. Use Typescript wherever it is possible
Typescript prevents us from possible bugs at runtime. We encourage you to use it, especially with ReactGrid. For cell templating reasons we introduced a few types of how the cell templating engine interfaces with ReactGrid. Thanks to this, you can safely transfer data between incompatible cells while interacting with them using the cell editor or, for example, pasting data from external sources or even other spreadsheets.
A concrete example will be shown in the next chapter, but for now, take a look at the tiny example of Typescript discriminating unions. Implemented in ReactGrid,
interfaceinterface
CellChange
field allows you to ensure that thefield allows you to ensure that the
type
field onfield on
checked
really exists.really exists.
newCell
import { CellChange } from "@silevis/reactgrid"; const handleChanges = (changes: CellChange[]) => { // evaluates as `CellChange<CheckboxCell>[] | CellChange<Datecell>[] | ...` changes.forEach(change => { if (change.type === 'checkbox') { console.log(change.newCell.checked); console.log(change.previousCell.checked); } // ... }); };
4. Compose your cell styling and behavior
In most cases, you will use built-in cell templates like
oror
NumberCell
. ReactGrid allows you to style a cell and its behavior without introducing a new cell template, for example, “non-editable number cell with blue background”. Instead, you can compose the functions as follows:. ReactGrid allows you to style a cell and its behavior without introducing a new cell template, for example, “non-editable number cell with blue background”. Instead, you can compose the functions as follows:
DateCell
bottomLine( nonEditable( showZero(numberCell(yearlyGroupsDiff, "text-lg disabled font-bold")) ) )
5. Avoid merging metadata with cells
Since all of the cells have no idea where they are placed, it’s tempting to extend them with some metadata. By metadata we mean the data that was added to ReactGrid related interfaces (e.g.
) by extending them with new attributes.) by extending them with new attributes.
Row
/* * There should be no `isCollapsed` and `backgroundColor` metadata attributes */ const row: Row & { isCollapsed: boolean; backgroungColor?: "red" | "blue" } = { isCollapsed: true, backgroungColor: 'blue', rowId: 0, cells: [ { type: "text", text: "John" }, { type: "text", text: "Doe" } ] };
You can also come across a similar situation that has arisen when some cells are related with each other - when building a tree list. Let’s have a look at the
interface:interface:
ChevronCell
interface ChevronCell extends Cell { type: 'chevron'; text: string; isExpanded?: boolean; hasChildren?: boolean; parentId?: Id; indent?: number; }
Except for
.
parentId
We will show you how to implement row toggling and working with tree-like structures in the next article.
We could debate financial issues for a long time, but there is not enough room for it so let’s look at them in a nutshell. You can skip this chapter if you like.
You can place a new value only in light green cells (credit line, opening balance) or with white background (cash inflows and outflows). Grayed-out cells are read-only.
Two of them (opening balance and credit line) are just numbers. We merged types of cash flow into two. Each entry is called “group” and has its own title like “Travelling expenses” for outflow and “Sales” for inflow. Except for the title, all groups have an array of the amount of money spent/earned each month.
Groups are aggregated vertically (inflows and outflows separately) into a total inflow or outflow per month. The last column presents all of the totals in a calendar year.
“Cash in” and “Cash out” make up the “Total” row. This row and the other cells should update their content when sourcing data has changed or e.g. user typed a new value into the cell.
Some items remain to be explained (and it’s the hardest thing to understand):
The last part is the “Credit line”. Users can update it by typing it in. This variable is constant for all months and is used for calculating “Credit line overdraft” - in a nutshell - if the absolute value from “Cumulative” exceeds the given credit line, then the cell should display this result.
What about the chart? This part should give us an instant knowledge about the company’s state of finance. In this case, we limit ourselves to display “Cashbox/bank” and “Credit Line Overdraft” as a line chart and cash inflow and outflow as bars.
In the penultimate chapter, we discussed 5. tips for good app implementation with ReactGrid. We will not discuss every line of code, but only code fragments in terms of the above-mentioned tips on how to work with ReactGrid.
1. Separate the data from ReactGrid
App component named
has four React’shas four React’s
LiquidityPlanner
hooks, each of them stores part of raw financial data. E. g.hooks, each of them stores part of raw financial data. E. g.
useState
is initiated withis initiated with
cashInflow
that comes from thethat comes from the
emptyInflows
file. This data has no connection with ReactGrid’s interfaces, and can be used directly by other components like charts.file. This data has no connection with ReactGrid’s interfaces, and can be used directly by other components like charts.
rawData.ts
const emptyMonthsValues: Values = [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN]; export const inflows: CashInflow[] = [ // ... { title: "Other income", values: emptyMonthsValues } // ... ];
2. Applying changes to the data
ReactGrid runs your changes handler function when you interact with the data displayed by the grid. Each change is applied by dispatching
. To set updated inflows we used a technique called currying (more info), to apply particular. To set updated inflows we used a technique called currying (more info), to apply particular
setCashInflow
on desired groups (on desired groups (
change
).).
cashInflow
import * as React from "react"; import { CellChange, NumberCell, ReactGrid } from "@silevis/reactgrid"; export const LiquidityPlanner: React.FC = () => { // ... const [cashInflow, setCashInflow] = React.useState(() => [...emptyInflows]); const handleChanges = (changes: CellChange[]) => { changes.forEach((change: CellChange<NumberCell>) => { // ... setCashInflow((cashInflow) => applyChange(change)(cashInflow)); // ... }); }; return ( <ReactGrid onCellsChanged={handleChanges} // ... /> ); };
Implementing changes handling in this way closes the reactivity cycle, therefore our task of processing input data into outputs is fully repeatable and has no side effects.
3. Typescript + ReactGrid = ❤️
ReactGrid is built with Typescript and fully supports it. We also encourage you to use it in your projects. A real example from our app shows how we narrowed down the expected change object type exclusively to
, therefore you are sure that you are able to access only actually existing fields., therefore you are sure that you are able to access only actually existing fields.
NumberCell
const handleChanges = (changes: CellChange[]) => { changes.forEach((change: CellChange<NumberCell>) => { if (change.rowId === CASHBOXBANK_ROW_ID && change.columnId === 1) { setOpeningBalance(change.newCell.value); } if (change.rowId === CREDITLINE_ROW_ID && change.columnId === 1) { setCreditLine(change.newCell.value); } // ... }); };
The other part is e. g. extending the set of built-in cell templates with your own. To be able to do it you have to pass the name of your custom Cell interface into a generic
interface.interface.
CellChange
Of course, you are not obliged to move your project right now to Typescript, but we highly suggest using static typing.
4. Compose your cell styling and behavior
When you work with ReactGrid it’s highly possible that you will need to achieve the same or similar behavior or styling on many cells. The solution is quite simple - small, reusable functions. Familiarity with documentation will definitely be useful.
export const textCell = ( text: string, className = "", style?: CellStyle ): TextCell => ({ type: "text", text, className, style }); export const numberCell = ( value: number, className = "", style?: CellStyle ): NumberCell => ({ type: "number", value, className, style, format: numberFormat }); export const nonEditable = (cell: DefaultCellTypes): DefaultCellTypes => ({ ...cell, nonEditable: true }); export const showZero = (cell: NumberCell): NumberCell => ({ ...cell, nanToZero: true, hideZero: false });
and the usage: a function that uses mentioned functions to fill up the cells array in a single row.
function getCashboxBankRow(title: string, cashboxBank: MonthlyValues): Row { return { rowId: CASHBOXBANK_ROW_ID, height: ROW_HEIGHT, cells: [ nonEditable(textCell(title, "padding-left-lg")), ...months().map((_, idx) => idx === 0 ? numberCell(cashboxBank[idx], "light-green-bg") : nonEditable(showZero(numberCell(cashboxBank[idx], "disabled"))) ), nonEditable(emptyTextCell) ] }; }
We created a fully working liquidity planner example on codesandbox.io. This sample runs with the ReactGrid MIT, we encourage you to visit a fully functional sample deployed at our website. There you can try extra features available only in the PRO version: fill handle, range selection, area copy/cut/paste. You can compare both versions here.
Liquidity planner is only one of many possible ReactGrid use cases when the standard data table is not enough. The main purpose of this article was to show you five useful tips that help you start the ReactGrid project using good practices.
Don’t forget to leave a ⭐ on our Github .
We encourage you to visit our official ReactGrid website , where you will find the documentation and information what the PRO version of our component offers.
Bye 👋
Create your free account to unlock your custom reading experience. | https://hackernoon.com/using-reactgrid-and-chartjs-to-create-a-financial-liquidity-planner-pj2733ke | CC-MAIN-2021-31 | refinedweb | 1,887 | 56.45 |
26 July 2011 17:57 [Source: ICIS news]
LONDON (ICIS)--The volume of petrochemicals passing through ports in ?xml:namespace>
Data showed that 2.59m tonnes of petrochemicals passed through the Kingdom’s ports in May, down from 2.68m tonnes in the same month last year and 2.66m tonnes in April 2011, according to the authority.
Throughput fell at all of the country’s major ports in May apart from at Dammam, in the country’s eastern province, where the volume of petrochemicals passing through rose to 348,707 tonnes, up from 340,310 tonnes in May 2010 and 320,143 tonnes in April 2011.
However, overall volumes are up for the year. In the five months to the end of May, a total of 12.56m tonnes of petrochemicals passed through Saudi Arabian ports. The figure for the same period in 2010 was 11.75m tonnes.
The volume of petrochemicals passing through the country’s ports has risen consistently in recent years. In 2010, the figure was 30.7m tonnes, up from 26.2m tonnes in 2009 and 23.9m tonnes | http://www.icis.com/Articles/2011/07/26/9480083/saudi-arabia-petrochemicals-transport-volumes-fall-in-may.html | CC-MAIN-2014-35 | refinedweb | 184 | 84.78 |
.
Pingback from Links (9/6/2007) « Steve Pietrek’s SharePoint Stuff
Strong-typed provisioning of custom lists in Sharepoint 2007
Great Job Waldek,
I've also discussed about an association between a lookup field a a list, via a feature.
If you please, you can go there
apichot.blogspot.com/.../sharepoint-2007-create-field-lookup-and.html
it was a greate post. and it is working perfectly but one problem is when we select multiple value from lookup field the result always defferent .mean some time it take 2 value some time it is taking 3 .and it is taking value on its own.
plz tell me why it is happning . and can we do it by using xml file.
ok
thanks once again for this post.
can
in the preveous comment ,bymistake i have specify wrong mail id.as ( mmoharana@leveernt.com)
thecorrect one is mmoharana@leverent.com
On there is a DSL addin to Visual Studio to model CAML schema including lookups, but there is little information except screencast. I asked about demo and I'm waiting.
Pingback from Creating Lookup Columns Using Features in SharePoint 2007 « Rusty’s SharePoint Blog
you can also look at infowise product - Infowise Connected Fields - its also a manipulation of MOSS lookup fields
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Security;
using Microsoft.SharePoint;
[assembly: AllowPartiallyTrustedCallers]
namespace TestClassLibrary
{
public class HelloWorldWebPart : WebPart
{
protected override void Render(HtmlTextWriter writer)
{
currentWeb.AllowUnsafeUpdates = true;
SPWeb currentWeb = SPContext.Current.Web;
SPList list = currentWeb.Lists[VivekList];
SPListItem newListItem = list.Items.Add();
newListItem["Title"] = "Root";
newListItem["City"] = "Root";
newListItem.Update();
}
}
}
by this you can access list in sharepoint and insert items in that ..this is very usefull article.. i have't founde this on net so i am posting this..but this will insert item when list will be there. so first need to create a list with two column title and city...and then through C# prgm u can add items programtically
Enjoy Sharepoint!
Hi Waldek,
I am trying your approach but I am having some problems.
First of all, when I am creating a site from the site definition wich includes this feature, SPContext.Current is null.
I think I have overcome this problem using properties.Feature.Parent to get de Web instead.
Second, once I get the web being created, the list collection doesn't have the list that I have to reference in my lookup field. (I guess because my code gets called before the list is created in the feature).
What should I do? I don't understand why in your scenario you dont have the same problem.
Thank you,
Manuel | http://www.sharepointblogs.com/tmt/archive/2007/09/06/sharepoint-programmatically-provisioning-lookup-fields.aspx | crawl-002 | refinedweb | 460 | 61.73 |
This module provides various datastructures.
Sentinel object which can be used instead of None. This is useful if you have optional parameters to which a user can pass None e.g. in datastructures.
Iterates over the items of the given mapping.
If a key has multiple values a (key, value) item is yielded for each:
>>> for key, value in iter_multi_items({1: [2, 3]}): ... print key, value 1 2 1 3 >>> for key, value in iter_multi_items(MultiDict({1: [2, 3]})): ... print key, value 1 2 1 3
An object whose attributes are looked up in a mapping residing in an internal stack.
If an attribute is accessed, the value of the first mapping, which contains the appropriate attribute, is returned.
New in version 0.6.
The top-most object.
Pushes the given mapping on the stack.
Pops the given mapping from the stack.
If the stack is empty a RuntimeError is raised.
A MultiDict is a dictionary customized to deal with multiple values for the same key.
Internally the values for each key are stored as a list, but the standard dict methods will only return the first value of those lists. If you want to gain access to every value associated with a key, you have to use the list methods, specific to a MultiDict.
Adds the value for the given key.
Returns the list of values for the given key. If there are none an empty list is returned.
Sets the values associated with the given key to the given values.
Like setdefault() but sets multiple values and returns the list associated with the key.
Returns a list of (key, values) pairs, where values is the list of values associated with the key.
Returns a list of all values.
Like lists() but returns an iterator.
Like listvalues() but returns an iterator.
Returns the list of values associated with the given key, if the key does not exist in the MultiDict an empty list is returned.
Like popitem() but returns all associated values.
A dict which remembers insertion order.
Big-O times for every operation are equal to the ones dict has however this comes at the cost of higher memory usage.
This dictionary is only equal to another dictionary of this type if the items on both dictionaries were inserted in the same order.
Pops the last or first item from the dict depending on last.
Moves the item with the given key to the end of the dictionary if last is True otherwise to the beginning.
Raises KeyError if no item with the given key exists.
New in version 0.4.
dict subclass for counting hashable objects. Elements are stored as keys with the values being their respective counts.
This object supports several operations returning a new Counter object from the common elements of c1 and c2, in any case the new counter will not contain negative counts.
Furthermore it is possible to multiply the counter with an int as scalar.
Accessing a non-existing element will always result in an element count of 0, accordingly get() uses 0 and setdefault() uses 1 as default value.
Returns a list of all items sorted from the most common to the least.
>>> from brownie.datastructures import Counter >>> Counter('Hello, World!').most_common(2) [('l', 3), ('o', 2)]
Iterator over the elements in the counter, repeating as many times as counted.
>>> from brownie.datastructures import Counter >>> sorted(Counter('abcabc').elements()) ['a', 'a', 'b', 'b', 'c', 'c']
Updates the counter from the given countable and kwargs.
A dict whose items can only be created or deleted not changed.
If you attempt to change an item a KeyError is raised.
New in version 0.5.
New in version 0.5: ImmutableDict is now hashable, given the content is.
New in version 0.5: ImmutableMultiDict is now hashable, given the content is.
An immutable OrderedDict.
New in version 0.2.
New in version 0.5: ImmutableOrderedDict is now hashable, given the content is.
An immutable OrderedMultiDict.
An immutable dict which combines the given dicts into one.
You can use this class to combine dicts of any type, however different interfaces as provided by e.g. MultiDict or Counter are not supported, the same goes for additional keyword arguments.
New in version 0.2.
New in version 0.5: CombinedDict is now hashable, given the content is.
An ImmutableMultiDict which combines the given dicts into one.
New in version 0.2.
Implements a lazy list which computes items based on the given iterable.
This allows you to create list-like objects of unlimited size. However although most operations don’t exhaust the internal iterator completely some of them do, so if the given iterable is of unlimited size making such an operation will eventually cause a MemoryError.
Cost in terms of laziness of supported operators, this does not include supported operators without any cost:
New in version 0.5: It is now possible to pickle LazyLists, however this will exhaust the list.
Returns a wrapper for a given callable which takes the return value of the wrapped callable and converts it into a LazyList.
Inserts the given object at the given index.
This method exhausts the internal iterator up until the given index.
Removes and returns the item at the given index, if no index is given the last item is used.
This method exhausts the internal iterator up until the given index.
Looks for the given object in the list and removes the first occurrence.
If the item is not found a ValueError is raised.
This method exhausts the internal iterator up until the first occurrence of the given object or entirely if it is not found.
Reverses the list.
This method exhausts the internal iterator.
Sorts the list using the given cmp or key function and reverses it if reverse is True.
This method exhausts the internal iterator.
Counts the occurrences of the given object in the list.
This method exhausts the internal iterator.
Returns first index of the object in list
This method exhausts the internal iterator up until the given object.
A sequence combining other sequences.
New in version 0.5.
Returns the sequence and the ‘sequence local’ index:
>>> foo = [1, 2, 3] >>> bar = [4, 5, 6] >>> cs = CombinedSequence([foo, bar]) >>> cs[3] 4 >>> cs.at_index(3) ([4, 5, 6], 0)
A list combining other lists.
New in version 0.5.
Returns the number of occurrences of the given item.
Returns the index of the first occurence of the given item between start and stop.
Appends the given item to the end of the list.
Extends the list by appending from the given iterable.
Inserts the given item before the item at the given index.
Removes and returns the item at the given index.
An IndexError is raised if the index is out of range.
Removes the first occurence of the given item from the list.
Reverses the list in-place:
>>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> l = CombinedList([a, b]) >>> l.reverse() >>> a [6, 5, 4]
Sorts the list in-place, see list.sort().
Returns a tuple subclass named typename with a limited number of possible items who are accessible under their field name respectively.
Due to the implementation typename as well as all field_names have to be valid python identifiers also the names used in field_names may not repeat themselves.
You can solve the latter issue for field_names by passing rename=True, any given name which is either a keyword or a repetition is then replaced with _n where n is an integer increasing with every rename starting by 1.
namedtuple() creates the code for the subclass and executes it internally you can view that code by passing verbose==True, which will print the code.
Unlike tuple a named tuple provides several methods as helpers:
Returns a SomeNamedTuple populated with the items from the given iterable.
Returns a dict mapping the field names to their values.
Returns a SomeNamedTuple values replaced with the given ones:
>>> t = SomeNamedTuple(1, 2) >>> t._replace(bar=3) SomeNamedTuple(foo=1, bar=3)
Note
namedtuple() is compatible with collections.namedtuple().
New in version 0.5.
A set which remembers insertion order.
New in version 0.2.
Returns the last element if last is True, the first otherwise.
Bases: Queue.Queue
Thread-safe implementation of an ordered set queue, which coalesces duplicate items into a single item if the older occurrence has not yet been read and maintains the order of items in the queue.
Ordered set queues are useful when implementing data structures like event buses or event queues where duplicate events need to be coalesced into a single event. An example use case is the inotify API in the Linux kernel which shares the same behaviour.
Queued items must be immutable and hashable so that they can be used as dictionary keys or added to sets. Items must have only read-only properties and must implement the __hash__(), __eq__(), and __ne__() methods to be hashable.
An example item class implementation follows:
class QueuedItem(object): def __init__(self, a, b): self._a = a self._b = b @property def a(self): return self._a @property def b(self): return self._b def _key(self): return (self._a, self._b) def __eq__(self, item): return self._key() == item._key() def __ne__(self, item): return self._key() != item._key() def __hash__(self): return hash(self._key())
Note
This ordered set queue leverages locking already present in the queue.Queue class redefining only internal primitives. The order of items is maintained because the internal queue is not replaced. An internal set is used merely to check for the existence of an item in the queue.
New in version 0.3.
Return True if the queue is empty, False otherwise (not reliable!).
Return True if the queue is full, False otherwise (not reliable!).
Remove and return an item from the queue.
If optional args ‘block’ is true and ‘timeout’ is None (the default), block if necessary until an item is available. If ‘timeout’ is a positive number, it blocks at most ‘timeout’ seconds and raises the Empty exception if no item was available within that time. Otherwise (‘block’ is false), return an item if one is immediately available, else raise the Empty exception (‘timeout’ is ignored in that case).
Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise raise the Empty exception. an item into the queue.
If optional args ‘block’ is true and ‘timeout’ is None (the default), block if necessary until a free slot is available. If ‘timeout’ is a positive an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available. Otherwise raise the Full exception.
Return the approximate size of the queue (not reliable!).. | http://packages.python.org/Brownie/api/datastructures.html#brownie.datastructures.OrderedDict | crawl-003 | refinedweb | 1,798 | 67.76 |
import random import numpy as np import matplotlib.pyplot as plt from math import sqrt, pi, erf import scipy.stats as ss
Parametric Statistics: What we've seen before, where we do statistics by assuming the data follows some underlying probability distribution (like normal distribution). Sometimes this is a good assumpetion because of the CLT.
Nonparametric Statistics: We do statistics without assuming an equation form for the underlying probability distribution. Typically harder to prove significance here because we have less information due to not assuming probability distribution.
Nonparametric statistics are secret and not widely taught because people belive they are challenging to understand. This is true, but I don't think undergraduates completely understand probability measure spaces but it doesn't stop us from using them.
From here onwards, most tests will not assume normality and are nonparametric. You won't find these tests in most traditional statistics textbooks
To do nonparametric statistics, one of the underlying principles is converting measurements into rankings.
d = np.random.rand(10) print (d) print (ss.rankdata(d))
[0.70148411 0.96522843 0.41747704 0.8159568 0.02398743 0.14613944 0.01542925 0.75959105 0.63014733 0.52986675] [ 7. 10. 4. 9. 2. 3. 1. 8. 6. 5.]
Data Type: Ranks
Compares: Two sets of measurements.
Null Hypothesis: The two sets of measurements are from the same distribution
Conditions: Unmatched measurements. Unmatched the measurements aren't in pairs and you don't necessarily have the same number
Related Test 1: Wilcoxon's Signed Ranks Test for matched data measuring one thing (i.e, temperature)
Related Test 2: Spearman's Correlation Test for matched data measuring two things (i.e., temperature and pressure)
Python:
scipy.stats.ranksums
Hints: Make sure all data is in the same units!
import pandas as pd data = pd.read_csv('grades.csv') #get some info: data.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 65 entries, 0 to 64 Data columns (total 12 columns): R1 65 non-null float64 R2 65 non-null float64 R3 65 non-null int64 R5 65 non-null int64 R6 65 non-null int64 HW1 65 non-null float64 HW2 65 non-null float64 HW3 65 non-null float64 HW4 65 non-null float64 HW5 65 non-null float64 HW6 65 non-null float64 Midterm 65 non-null float64 dtypes: float64(9), int64(3) memory usage: 6.2 KB
I'm going to standardize the homework so that they are all out of 100%. The first row contains perfect scores on each.
data /= data.iloc[0,:] data *= 100 data.mean(axis=0)
R1 91.794872 R2 89.807692 R3 84.615385 R5 93.846154 R6 81.538462 HW1 82.939560 HW2 80.118343 HW3 74.230769 HW4 83.367730 HW5 73.282648 HW6 75.182595 Midterm 76.130769 dtype: float64
plt.title('HW1') plt.hist(data.HW1) plt.show()
plt.title('HW2') plt.hist(data.HW2) plt.show()
ss.ranksums(data['HW1'], data['HW2'])
RanksumsResult(statistic=0.39578610596263436, pvalue=0.6922628274842608)
The $p$-value is 0.70, so we cannot rule out the null hypothesis that they are from the same distribution. What about a more recent difficult homework?
ss.ranksums(data['HW1'], data['HW5'])
RanksumsResult(statistic=2.567953381628151, pvalue=0.010230091290609646)
So HW 1 and HW 5 were significantly different.
Data Type: Ranks
Compares: Two sets of measurements
Null Hypothesis: The two sets of measurements are from the same distribution
Conditions: Measurements are matched. Matched means the data comes in tuples/pairs. More than 6 samples, better to have more than 20.
Related Test 1: Wilcoxon's Sum of Ranks Test for unmatched data measuring one thing (i.e, temperature)
Related Test 2: Spearman's Correlation Test for matched data measuring two things (i.e., temperature and pressure)
Python:
scipy.stats.wilcoxon
Hints: Make sure all data is in the same units!
Since the same people are doing the HW each week, a more accuracte comparison would be to used the Signed Rank Test.
ss.wilcoxon(data.HW1, data.HW2)
WilcoxonResult(statistic=634.5, pvalue=0.08703592427905478)
ss.wilcoxon(data.HW1, data.HW5)
WilcoxonResult(statistic=434.0, pvalue=0.000398645278025264)
Notice that the p-values are lower relative to the unmatched sum of ranks test, meaning have paired data allows us to be more certain in our conclusions.
Data Type: Ranks
Compares: Two sets of measurements
Null Hypothesis: The two sets of measurements are uncorrelated
Conditions: Measurements are matched. Matched means the data comes in tuples/pairs. The measurements are of different things
Related Test 1: Wilcoxon's Sum of Ranks Test for unmatched data measuring one thing (i.e, temperature)
Related Test 2: Wilcoxon's Signed Ranks Test for matched data measuring one thing (i.e, temperature)
Python:
scipy.stats.spearmanr
First, let's get the average grade on the homeworks. The spreadsheet has 6 homeworks
#build a list of all the HW indices index = [] for i in range(1,7): index.append('HW{}'.format(i)) #access those homeworks and then take the mean along the columns hw_means = data[index].mean(axis=1)
plt.plot(hw_means, data.Midterm, 'o') plt.show()
ss.spearmanr(hw_means, data.Midterm)
SpearmanrResult(correlation=0.3466347056828196, pvalue=0.004673660991129944)
Remarkable!
np.corrcoef(hw_means, data.Midterm)
array([[1. , 0.60007556], [0.60007556, 1. ]])
Data Type: Count
Compares: Count vs a poisson distributed population
Null Hypothesis: The number of observations (count) came from the known population
Conditions: Less than 40 samples (for computational simplicity)
Related Test 1: $zI$ test, for more than 40 samples
Python: Construct an interval and integrate using
scipy.stats.poisson.cdf(x, mu=...)
Hints: Your interval should contain your value and all other extreme values. The interval should go up to infinity or down to 0 depending on if it's higher or lower than the expected value.
We will construct an interval containing all values as extreme as ours. We don't consider a low number of hurricanes to be extreme in this example. Remember that we want to include the value into this interval.
First consider only saying that lots of hurricanes is out of the ordininary (not part of the null hypothesis).$$ P = P(x \geq 15) = 1 - \sum_0^{14} P(x) $$
print('p-value is', (1 - ss.poisson.cdf(14, mu=6.3)))
p-value is 0.002217122790073134
So we reject the null hypothesis. This is a highly unusual number of hurricanes. | https://nbviewer.jupyter.org/github/whitead/numerical_stats/blob/master/unit_10/lectures/lecture_2.ipynb | CC-MAIN-2020-40 | refinedweb | 1,057 | 50.63 |
Haskell Quiz/Word Blender/Solution Sjanssen
From HaskellWiki
< Haskell Quiz | Word Blender(Difference between revisions)
Latest revision as of 11:14, 13 January 2007
import qualified Data.ByteString.Char8 as B import System.Random import Data.List import Data.Char -- Given sorted lists 'xs' and 'ys', 'subset xs ys' tests whether xs -- is a subset of ys subset [] _ = True subset _ [] = False subset (x:xs) (y:ys) = case compare x y of EQ -> subset xs ys LT -> False GT -> subset (x:xs) ys valid w = B.length w >= 3 && B.length w <= 6 && B.all isAlpha w uniq = map head . group main = do f <- B.readFile "/usr/share/dict/words" let ws = filter valid . B.lines . B.map toUpper $ f sixes = filter (\x -> B.length x == 6) ws i <- randomRIO (0, length sixes - 1) let seed = sort . B.unpack $ sixes !! i putStrLn "Letters: " putStrLn seed putStrLn "" putStrLn "Solutions: " mapM_ B.putStrLn $ filter (\w -> subset (sort . B.unpack $ w) seed) ws | http://www.haskell.org/haskellwiki/index.php?title=Haskell_Quiz/Word_Blender/Solution_Sjanssen&diff=prev&oldid=10252 | CC-MAIN-2013-48 | refinedweb | 161 | 70.7 |
Calculate length of the Hypotenuse of right angled triangle
We have provided basic program which is 90% same as command line program, just except scanf and other functions.
Please re-write the same program in command line format and post in comments below, we will post it here ASAP.
Please follow Command Line Programming here.
#include <stdio.h> #include <math.h> #include <stdlib.h> int main(int argc, char *argv[]) { if(argc<2) { printf("please use \"prg_name value1 value2 ... \"\n"); return -1; } int a,b,side1,side2,side3; a=atoi(argv[1]); b=atoi(argv[2]); side1=pow(a,2); side2=pow(b,2); side3=sqrt((side1+side2)); printf("the hypotenuse is %d",side3); return 0; } | http://prepinsta.com/tcs-programming-questions-4/ | CC-MAIN-2018-22 | refinedweb | 116 | 67.35 |
Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search Coderanch
Advance search
Google search
Register / Login
Rekha Rao
Greenhorn
15
11
Threads
0
Cows
since Jan 23, (15 (15/10)
Number Threads Started (11/10)
Number Likes Received (0/3)
Number Likes Granted (0/3)
Set bumper stickers in profile (0/1)
Set signature in profile
Set a watch on a thread
Save thread as a bookmark
Create a post with an image (0/1)
Recent posts by Rekha Rao
CMR assignment rules...
In assignment rules for relationships (pg 154 of ejb spec)..
A and B are in one-to-one bidirectional relation..
a1 <--> b1
a2 <--> b2
changing:
a1.setB(a2.getB()) will result in
'a2.getB() == null'.
Suppose we just have:
a1.setB(b2) (that is, not accessing b2 through a2), will the container still be aware that b2 is involved with a2 and yield the same result ?
show more
16 years ago
EJB Certification (OCEEJBD)
Valid operation in ejbCreate for stateless session bean
Can a statless session bean acess EJBObject in ejbCreate method ? The EJB specification lists getEJBObject and getEJBLocalObject under operations allowed in ejbCreate method.
I am under the impression that EJBOjbect is created when the client invokes create method on home. For a statless session bean however, ejbCreate could be invoked much earlier for a stateless session bean unrelated to any calls from the client.
So, how can getEJBObject be a valid operation in ejbCreate for a statless session bean ?
show more
16 years ago
EJB Certification (OCEEJBD)
Need inputs: Failed SCJD
No, I did not resubmit.
show more
18 years ago
Certification Results
Remote Client ?
The instruction says:
"The remote client code that you write must provide all the public methods of the suncertify.db.Data class. "
Why are they specifying remote client?
I am under the impression that- in the network mode the server is "remote" and, the client is local in the non-network mode.
The client does not implement Remote interface in either mode.
show more
19 years ago
Developer Certification (OCMJD)
Jxam question..
If such questions are asked in the exam, should we look for just method names or the exact signature/argument list etc ?
Which are the valid methods in java.awt.Graphics class ?
1. drawRect()
2. fillRect()
3. drawOval()
4. drawString()
As there are no arguments in the options, I am tempted to say none of the above are valid methods.
show more
20 years ago
Programmer Certification (OCPJP)
Static context and local inner classes..
Annonymous classes are never static even if it's in a static context.
What about the local inner classes in a static method ?
Why static declarations are not allowed in the following ?
I have this:
class Test{
int i;
static void test(){
class Test1{
static int j // This complains..that inner classes
// cannot have static declarations
int k = i; //this complains, as non-static variable
//cannot be accessed from a static context
}
}
}
show more
20 years ago
Programmer Certification (OCPJP)
Widening conversion from int to float..
From JLS 5.1.2:
int big = 1234567890;
float f = big;
System.out.println(i - (int)f);
is not 0, as the float values are not precise for nine significant digits.
Going by the same, I was not expecting to get a 0 when I used, Integer.MAX_VALUE for 'big'. Why is that 0 ?
show more
20 years ago
Programmer Certification (OCPJP)
Protected access for finalize and clone methods..
In the Object class, why are only the methods clone and finlaize have protected access ?
My understanding for providing the protected access modifier is to provide visibility for subclasses in different packages.
java.lang package is available by default and all classes extend the Object by default.
show more
20 years ago
Programmer Certification (OCPJP)
ClassCast Exception..
I thought the following should work. But, I get a ClassCastException in I, whereas II works fine. What's the difference between I and II ?
class Test{}
class Test1 extends Test{}
I.
<some method>....
Test t[] = {new Test1(), new Test1()};
//ClassCastException, here:
Test1 t1[] = (Test1[])t;
II.
<some method>....
Test t[];
Test1 t1[] = {new Test1(), new Test1()};
t = t1;
Test1 t11[] = (Test1[])t;
show more
20 years ago
Programmer Certification (OCPJP)
createImage always returns null..
The same thing works in the context of an applet, however.
Like in the code:
class Test extends Applet{
Image img;
public void init(){
img = createImage(100,100);
//Image is created it.
}
}
show more
20 years ago
Programmer Certification (OCPJP)
createImage always returns null..
createImage is in java.awt package, defined in Component class.
show more
20 years ago
Programmer Certification (OCPJP)
createImage always returns null..
I am not sure what is wrong here. createImage is always returning null. What's the usage of createImage ?
class Test extends Panel{
Image img;
public Test(){
img = createImage(100,100);
// After this, img is always null.
}
}
show more
20 years ago
Programmer Certification (OCPJP)
Exception and Instance Initializer
From JLS 8.6 :
An instance initializer of a named class may not throw a checked exception unless that exception or one of its superclasses is explicitly declared in the throws clause of each constructor of its class and the class has at least one explicitly declared constructor. An instance initializer in an anonymous class (�15.9.5) can throw any exceptions.
I thought the following code should compile. What is wrong here ?
public class Test{
{
// I get an error here: unreported exception TestException; must be caught or declared to //be thrown
print();
}
void print() throws TestException{
}
Test() throws TestException{
}
}
class TestException extends Exception{}
show more
20 years ago
Programmer Certification (OCPJP)
exception handling in instance initializer
Just giving a shot at this one, not sure if it makes enough sense.
I think, you need to connect lot of things together here.
From JLS 8.6:
"It is a compile-time error if an instance initializer cannot complete normally "
From JLS: 14.20
"A break, continue, return, or throw statement cannot complete normally"
Hence the following code will give a compiler error ('initializer must be able to complete normally') .
class Test{
{
throw new TestException();
}
}
class TextException extends RuntimeException{
}
Also from JLS 14:20,
"HYPOTHETICAL: An if-then statement can complete normally iff at least one of the following is true:
The if-then statement is reachable and the condition expression is not a constant expression whose value is true.
The then-statement can complete normally
"
So, the following code compiles fine as, if-then statement is considered to complete normally (since if statement is reachable) and hence the instance initializer itself is considered to complete normally.
class Test{
{
if(true) // or if(false)
throw new TestException();
}
}
class TextException extends RuntimeException{
}
show more
20 years ago
Programmer Certification (OCPJP)
Choosing the Most Specific Method ?
Can someone explain this (preferably with an example)?
From JLS 15.12.2.2., to choose the most specific method::
If all the maximally specific methods have the same signature, then:
1. If one of the maximally specific methods is not declared abstract, it is the most specific method.
2.
How can the method be chosen arbitarirly (the 2nd point) ? Shouldn't there be compile-time ambiguous error , if, there are more than one maximally specific method ?
show more
20 years ago
Programmer Certification (OCPJP) | https://coderanch.com/u/8519/Rekha-Rao | CC-MAIN-2022-05 | refinedweb | 1,212 | 64.71 |
#include <KSharedPtr>
Detailed Description
template<class T>
class KSharedPtr< T >
Can be used to control the lifetime of an object that has derived QSharedData.
As long a someone holds a KSharedPtr on some QSharedData object it won't become deleted but is deleted once its reference count is 0. This struct emulates C++ pointers virtually perfectly. So just use it like a simple C++ pointer.
The difference with QSharedPointer is that QSharedPointer does the refcounting in the pointer, while KSharedPtr does the refcounting in the object. This allows to convert to a raw pointer temporarily and back to a KSharedPtr without deleting the object, if another reference exists. But it imposes a requirement on the object, which must inherit QSharedData.
The difference with using QSharedDataPointer is that QSharedDataPointer is a building block for implementing a value class with implicit sharing (like QString), whereas KSharedPtr provides refcounting to code that uses pointers.
- Deprecated:
- use QExplicitlySharedDataPointer instead
Definition at line 66 of file ksharedptr.h.
Constructor & Destructor Documentation
Creates a null pointer.
Definition at line 72 of file ksharedptr.h.
Creates a new pointer.
- Parameters
-
Definition at line 79 of file ksharedptr.h.
Copies a pointer.
- Parameters
-
Definition at line 91 of file ksharedptr.h.
Unreferences the object that this pointer points to.
If it was the last reference, the object will be deleted.
Definition at line 103 of file ksharedptr.h.
Member Function Documentation
Attach the given pointer to the current KSharedPtr.
If the previous shared pointer is not owned by any KSharedPtr, it is deleted.
Definition at line 291 of file ksharedptr.h.
Clear the pointer, i.e.
make it a null pointer.
Definition at line 305 of file ksharedptr.h.
- Returns
- a const pointer to the shared object.
Definition at line 171 of file ksharedptr.h.
Returns the number of references.
- Returns
- the number of references
Definition at line 213 of file ksharedptr.h.
- Returns
- the pointer
Definition at line 155 of file ksharedptr.h.
- Returns
- the pointer
Definition at line 163 of file ksharedptr.h.
Convert KSharedPtr<U> to KSharedPtr<T>, using a dynamic_cast.
This will compile whenever T* and U* are compatible, i.e. T is a subclass of U or vice-versa. Example syntax:
KSharedPtr<T> tPtr; KSharedPtr<U> uPtr = KSharedPtr<U>::dynamicCast( tPtr ); Since a dynamic_cast is used, if U derives from T, and tPtr isn't an instance of U, uPtr will be 0.
Definition at line 269 of file ksharedptr.h.
Test if the shared pointer is null.
- Returns
- true if the pointer is null, false otherwise.
- See also
- opertor (bool)
Definition at line 225 of file ksharedptr.h.
- Returns
- Whether this is the only shared pointer pointing to to the pointee, or whether it's shared among multiple shared pointers.
Definition at line 235 of file ksharedptr.h.
Test if the shared pointer is NOT null.
- Returns
- true if the shared pointer is NOT null, false otherwise.
Definition at line 147 of file ksharedptr.h.
Convert KSharedPtr<U> to KSharedPtr<T>, using a static_cast.
This will compile whenever T* and U* are compatible, i.e. T is a subclass of U or vice-versa. Example syntax:
KSharedPtr<T> tPtr; KSharedPtr<U> uPtr = KSharedPtr<U>::staticCast( tPtr );
Definition at line 253 of file ksharedptr.h.
The documentation for this class was generated from the following file:
Documentation copyright © 1996-2019 The KDE developers.
Generated on Sun Sep 15 2019 05:00:41 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006
KDE's Doxygen guidelines are available online. | https://api.kde.org/frameworks/kdelibs4support/html/classKSharedPtr.html | CC-MAIN-2019-39 | refinedweb | 588 | 60.41 |
I'm writing a script that will run through multiple mxd files and list the file name, and then the layer names, data sources, and fields. The script runs fine when I run it in the Python window or if I run the script tool in ArcMap while the mxd is open, but if I refer to a different mxd or just run the script in ArcCatalog, it gives IO Errors and says that it can't find the layers. Here's my code:
Any help would be greatly appreciated!
import arcpy #set file path for input mxd fileName = arcpy.GetParameterAsText(0) arcpy.AddMessage("got file name: " + fileName) fileNameList = fileName.split(";") #set file path for output txt file out = open(arcpy.GetParameterAsText(1), "w") arcpy.AddMessage("got out file") #loop through file names for fName in fileNameList: mxd = arcpy.mapping.MapDocument(fName) arcpy.AddMessage("got map file: " + mxd.filePath) #print mxd file name out.write("Mxd file: " + mxd.filePath + '\n') #print list of data frames for df in arcpy.mapping.ListDataFrames(mxd): out.write("Data Frame:" + '\n') out.write(df.name + '\n') out.write("Layers:" + '\n') for lyr in arcpy.mapping.ListLayers(mxd, "*", df): out.write(lyr.name + '\n') try: if lyr.supports("DATASOURCE"): out.write(lyr.dataSource + '\n') if lyr.isGroupLayer == False: fieldList = arcpy.ListFields(lyr) for field in fieldList: out.write(str(field.name) + ", ") out.write ('\n') except Exception as e: out.write("field error" + '\n') out.write(e.message + '\n') out.write(str(type(e)) + '\n') out.write('\n') del mxd #close output file out.close()
Any help would be greatly appreciated! | https://community.esri.com/thread/32009-list-fields-doesnt-work-outside-of-arcmap | CC-MAIN-2018-22 | refinedweb | 265 | 63.56 |
Uploading code without restarting the board
Is there a way to update code on the board without restarting it?
the VS code plugin is uploading the files and resetting it.
This is a frustrating process to test code.
I know I can run 1 file, but i have several code files and not only 1
I wish I could just copy files to the board and test without it getting restarted
I also tried to upload changes via FTP, but the latest code copied is not updated (cached files?)
any solution?
- Ralph Global Moderator last edited by
Hi guys, I didn't read everything below in detail, but I just wanted to add that the Pymakr package for Atom has an option for not rebooting after upload :) No need to switch to FTP if the reboot part is the issue.
Actually, VSCode is supposed to have the same option, but when testing it just now it shows a bug (it doesn't show any output in the terminal after upload). I'm going to fix that now and add it in the next release. After that, you can add "reboot_after_upload" key to the global or project config file (
"reboot_after_upload": false) and it will not reboot the board after uploading or downloading.
- oved.yavine last edited by oved.yavine
@robert-hh thanks for the reply .. i resolved my issue ... your help is really appreciated
- robert-hh Global Moderator last edited by
@oved-yavine I would not consider re-boot as a painful process. It's just pushing Ctrl-D. If uploading is what hurts, you could also keep all files on the device and edit them in-place, for instance with the use of Filezilla. Once you see the files of your device in the device pane of Filezilla, you can edit them there with your favorite editor. Filezilla will take care of downloading and uploading the file. That#s what I do.
@robert-hh I am still having issues with testing my modules without "upload all" files and restart my board. my code changes are not reflected even when I execute reload as mentioned.
I cannot figure out how to do this.
making a code change, upload all and test again is a painful process..
Any help would be appreciated
@robert-hh I was partially able to accomplish what you explained
it seems like that if i am testing module A, but calling a function on Module B that loads Module A your method to relaod module A is not working
I tried reloading module A and B, but with no luck
After struggling i found that I need to reload all tested modules in the hierarchy starting from the bottom
in my case reloading module A and then reloading module B
I enhanced your reload function to be:
def reload(mods): import sys for mod in mods: mod_name = mod.__name__ del sys.modules[mod_name] print (__import__(mod_name))```
- robert-hh Global Moderator last edited by
@oved-yavine Yes.
@robert-hh so what you are suggesting is to upload via FTP and call the reload function?
- robert-hh Global Moderator last edited by robert-hh
@oved-yavine You have to remove the names of the to-be-tested module from the list of symbols. The following short function may do so:
def reload(mod): import sys mod_name = mod.__name__ del sys.modules[mod_name] return __import__(mod_name)
If the module you are testing is called mymodule.py, and you had it imported with
import mymodule, then calling
reload(mymodule)will re-import it and start it again. I have that function included in my main.py, so I can call it from REPL when needed. | https://forum.pycom.io/topic/4011/uploading-code-without-restarting-the-board | CC-MAIN-2019-35 | refinedweb | 613 | 70.13 |
from tambur import Tambur tambur = Tambur(api_key='API_KEY', app_id='APP_ID', secret='SECRET') tambur.publish('mystream', 'some message')
Tambur.io provides your business with APIs to build scalable realtime web and mobile apps.
<html> <head> <script src=""></script> <script> var connection = new tambur.Connection("API_KEY", "APP_ID"); var stream = connection.get_stream("my_stream"); stream.onmessage = function(msg){ /* do some fancy things with your msg */ }; </script> </head>
require 'ruby-tambur' tambur = Tambur::Connector.new('API_KEY', 'APP_ID', 'SECRET') tambur.publish('mystream', 'some message')
from tambur import Tambur tambur = Tambur(api_key='API_KEY', app_id='APP_ID', secret='SECRET') tambur.publish('mystream', 'some message')
<?php require_once 'tambur.php'; $tambur = new TamburClient('API_KEY', 'APP_ID', 'SECRET'); $tambur->publish('mystream', 'some message'); ?>
import io.tambur.*; Tambur tambur = new Tambur("API_KEY", "APP_ID", "SECRET"); tambur.publish("mystream", "some message");
Tambur = tambur_client:new("API_KEY", "APP_ID", "SECRET"), Tambur:publish("mystream", "some message").
You're seconds away from bringing some realtime dynamics to your web or mobile app!
Build websites that react to events triggered by your web application in realtime. You can publish your data in realtime to your subscribers with just a few lines of code.
Build websites that make use of online visitors' presence information. You can react to presence events triggered whenever a user comes online or gets disconnected.
Build websites that allow visitors to connect. Your online visitors can send and receive messages to each other in realtime.
We provide libraries in Python, Ruby, PHP, C#, Erlang, and Java that wrap our HTTP REST API for publishing data to your subscribers. All of our libraries are open source software and hosted on GitHub.
Use SSL to connect to our HTTP API endpoints and Messaging servers if you like, we won't charge you extra for that.
We try our best to discover if the browser supports HTML5 WebSockets. If it doesn't we switch to an alternative transport.
Realtime analytics of your Apps and Streams. Aggregated counters per minute, per hour, per day, and per month | https://www.tambur.io/ | CC-MAIN-2014-15 | refinedweb | 324 | 52.36 |
This section provides descriptions of some of the more common wait event parameters.
This is the block number of the block for which Oracle needs to wait. The block number is relative to the start of the file. To find the object to which this block belongs, enter the following SQL statements:
select name, kind from ext_to_obj_view where file# = file# and lowb <= block# and highb >= block#;
If the value for this parameter equals 0, a reset was sent to the client. A nonzero value indicates that a break was sent to the client.
The class of the block describes how the contents of the block are used. For example, class 1 represents data block, and class 4 represents segment header.
The initials "dba" represents the data block address, which consists of a file number and a block number.
The address of the disconnect function of the driver that is currently being used.
The following query returns the name of the database file:
select * from v$datafile where file# = file#;
The first identifier (id1) of the enqueue or global lock takes its value from P2 or P2RAW. The meaning of the identifier depends on the name (P1).
The second identifier (id2) of the enqueue or global lock takes its value from P3 or P3RAW. The meaning of the identifier depends on the name (P1).
The relative index number into
V$GC_ELEMENT.
The mode is usually stored in the low order bytes of P1 or P1RAW and indicates the mode of the enqueue or global lock request. This parameter has one of the following values:
Use the following SQL statement to retrieve the name of the lock and the mode of the lock request:
select chr(bitand(p1,-16777216)/16777215)|| chr(bitand(p1, 16711680)/65535) "Lock", bitand(p1, 65535) "Mode" from v$session_wait where event = 'DFS enqueue lock acquisition';
The name or "type" of the enqueue or global lock can be determined by looking at the two high order bytes of P1 or P1RAW. The name is always two characters. Use the following SQL statement to retrieve the lock name.
select chr(bitand(p1,-16777216)/16777215)|| chr(bitand(p1,16711680)/65535) "Lock" from v$session_wait where event = 'DFS enqueue lock acquisition';
The name of the object namespace as it is displayed in
V$DB_OBJECT_CACHE view.
The number of I/Os that are "requested." This differs from the number of blocks in that one request could potentially contain multiple blocks.
The number of the inactive session. Use the following SQL statement to find more information about the session:
select * from v$session where sid = session#;
This is the total amount of time the session has waited for this session to terminate. | https://docs.oracle.com/cd/B19306_01/server.102/b14237/waitevents002.htm | CC-MAIN-2019-18 | refinedweb | 448 | 69.62 |
So I am creating a slot machine game were it plays and then picks a random number between 1-10 and then ask the user if he wants to play again if they put in y they play again and if no it stops. So What Am I doing wrong? Sorry the problem is that I can see would you like to play again but I can actually get it to generate the numbers and then have it print out would you like to play again.
Code java:
<YOUR CODE HERE> package HW10; import java.util.Scanner; public class HW10 { public static void main(String[] args) { //This header explains what the program does System.out.println("This program randomly generates a number between 1 and 10"); //Declares variables String another = "y"; int slot1; int slot2; int slot3; //Ask the use to input a yes or a no. Scanner keyboard = new Scanner (System.in); System.out.print("Would you like to continue y or n:"); another = keyboard.toString(); //Add comments while(another.equalsIgnoreCase("y")); { slot1 = (int) (Math.random() *(10)); slot2 = (int) (Math.random() *(10)); slot3 =(int) (Math.random() *(10)); } slot1 = slot2 = slot3 = slot2; } } | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/28384-what-am-i-doing-wrong-slot-machine-game-printingthethread.html | CC-MAIN-2015-35 | refinedweb | 192 | 74.79 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.