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
50120/how-to-install-a-module-in-python-3-6 If you are using Ubuntu then the module BeatifulSoup is by default installed in it. You can find it using the command : $ apt-cache search beautifulsoup If you are using Python 3.x and still are not able to find it then install it using the following command : $ sudo apt-get install python3-bs4 Once you download it then you can import it by following command from bs4 import BeautifulSoup To install biopython on your project, simply ...READ MORE I am having trouble choosing interpreter as ...READ MORE You can use '\n' for a next ...READ MORE calculate square root in python >>> import math ...READ MORE Your code is good until you get ...READ MORE You missed a few login data forms, ...READ MORE Try this:<b>"Assemble under ...READ MORE If you are using Python 3.x then ...READ MORE Yes you can do it using the ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/50120/how-to-install-a-module-in-python-3-6?show=50127
CC-MAIN-2019-51
refinedweb
167
75.61
#include <mlFields.h> It accepts a new value only if it is 0, 1 or at least an epsilon higher than the previous value. Definition at line 580 of file mlFields.h. Default constructor, do not use it. Constructor, creates a field with a name to manage a progressive float value. Default epsilon value is 0.02. Default value is 0. Same as getFloatValue(). Definition at line 604 of file mlFields.h. References ml::FloatField::getFloatValue(). Sets field value to floatValue if floatValue==0, floatValue==1 or floatValue > previous floatValue + setUpdateDifference. Reimplemented from ml::FloatField. Same as setFloatValue(). Sets an epsilon value which a new value must have more than the previous value to be accepted as new field value.
http://www.mevislab.de/fileadmin/docs/current/MeVisLab/Resources/Documentation/Publish/SDK/ToolBoxReference/classml_1_1ProgressField.html
crawl-003
refinedweb
120
53.58
C break continue example C break continue example In this section, you will learn how to use break statement with continue statement in C. The continue statement provides a convenient way break and continue break and continue hi difference between break and continue break and continue break and continue hi i am jane pls explain the difference between break and continue Continue and break statement Continue and break statement How can we use Continue and break... is an example of break and continue statement. Example - public class ContinueBreak... is an example of break and continue statement. Example - public class ContinueBreak break . Using jumping statements like break and continue it is easier to jump out of loops... use break. It gives the following output: C:\javac>...; continue Continue statement is just similar to the break Java - Continue statement in Java the statements written after the continue statement. There is the difference between break and continue statement that the break statement exit control from the loop... Java - Continue statement in Java   Continue statement in java . Difference between break and continue is, break exit from the loop...Continue statement in java In this section we will discuss about continue statement in java. continue is one of the branching statement used in most JavaScript Break Continue Statement JavaScript Break-Continue Statement: Generally we need to put the break... of the program. On the other hand continue helps us to continue the flow.... Example 1(Break): <html> <head> <title>Write your title here Continue in java between break and continue statement that the break statement exit control... Continue.java C:\chandan>java Continue chandan Value of a : 0... Resource: Java - Continue statement in Java Java Break continue Continue C Tutorials ; C break continue example The continue statement provides... C Tutorials In this section we have given large number of tutorials on C | Array of String using Pointers | C break continue example | C Break...; C Tutorials | Java Tutorials | PHP Tutorials | Linux...; | XPath Tutorials | HTML Tutorials C Tutorial Section C String Reverse Java Break of the controlling statement like continue and return. Break statement can be used in while loop... Java Break Many programming languages like c, c++ uses the "break" statement. Java also Java - Break statement in java ; 2.The continue statement 3.The return statement Break: The break...;javac Break.java C:\chandan>java Break The Prime number in between 1 - 50... Java - Break statement in java   PHP Continue Continue Control Structure: Continue is another type of control structure... iteration, continue is used within looping structures (like for, foreach, while, do-while and switch case)to avoid rest of the code. If we want C Break for loop C Break for loop In this section, you will learn how to use break statement in a for loop. The break statement terminates the execution of the enclosing loop Java Break loop of opposite nature, break and continue respectively. In the following example break statement is used to break two looping statements do-while & for loop... Java Break loop   Java Break keyword and for handling these loops Java provides keywords such as break and continue respectively. Among these Java keywords break is often used in terminating the loops... Java Break keyword   Java Break Lable Java Break Lable In Java, break statement is used in two ways as labeled and unlabeled. break is commonly used as unlabeled. Labeled break statement is used Break statement in java Break statement in java Break statement in java is used to change the normal control flow of compound statement like while, do-while , for. Break statement is used in many languages such C, C++ etc. Sometimes it may... that shows how to use 'continue' keyword in jsp page. The continue statement skips c c++ - Java Beginners c c++ Write a small record management application for a school...){} } }); continue.. delBtn.addActionListener(new ActionListener...]; String name = f[1]; String c = f[2]; String note = f[3 c c++ - Swing AWT c c++ Write Snake Game using Swings Hi Friend, Try the following code: 1)SnakeGame.java: import javax.swing.JFrame; public...(DELAY, this); timer.start(); } continue.... public void paint Java Control Statement is the greater"); break; case 3: System.out.println("c is the greater... of jumping statement break, continue, and return. These statement transfer...;value of a" +a); break; } } 2.The continue C Tutorials C Java... company to another. Continue Statement The continue statement occurs.... The continue statement skips the current iteration (for while or a do-while loop).  Java Control Statements statements (while, do-while and for) and branching statements (break, continue... the control statements in C++. You must be familiar with the if-then statements in C++. The if-then statement is the most simpler form of control flow statement Loop in java For Loop in Java Break statement in java Continue statement in Java Java Break example these loops Java provides keywords such as break and continue respectively... Category in which it has two keywords of opposite nature, break and continue.... Java Break continue Java has two C language C language i want that when i hit any key only * to be print not the hit key in c language The given example will display aestricks...(); if(ch == 13) { break; } else if (ch == 8 What is BREAK? What is BREAK? What is BREAK? Hi, BREAK command clarify reports by suppressing repeated values, skipping lines & allowing for controlled break points. Thanks Java Break out of for loop statements. These Java labels are break and continue respectively. 'break' is mainly used... = "break", strc = "continue", choice = ""; JOptionPane.showMessageDialog(null... Java Break out of for loop   how java programming differ from pascal and C - Java Beginners "early out" statements "break" and "continue". Pascal does not. Using... have to read about it for my exams thanks Hi friend, C... functions, and routines that don't return a value are called procedures. In C all c++ - Java Beginners c++ 1. Create the equivalent of a four-function calculator. The program should request the user to enter a number, an operator, and another number..., operator, second number: "; cin<<"%f %c %f", &num1, &ch, &num2 ); cin > C/C++ Programming Books C/C++ Programming Books Visual C++ 6 Unleashed Visual C++ 6 Unleashed provides comprehensive coverage of the core topics continue java - Date Calendar continue java and how to subtract date(day month year) form jframe(jtextfiled). Thank's Hi friend, Please give full details and source code where you having the problem. Thanks Thanks for posting Continue Statement Continue Statement The continue statement occurs only inside the iterator statements like while, do or for statements. The continue statement skips the current iteration break image click the imageview break image click the imageview i clcik the button than image break in multiple PHP Break Break Control Structure: Break is a special kind of control structure which helps us to break any loop or sequence, like if we want to break the flow of any loop (for, while etc) then we can use break statement, generally we need c# c# how to find out the size of the BMP image in C C++ C++ How can i write this in dev c using switch,break and for loop using switch,break and for loop generate a 10 digit number and display the length of longest increasing series++ dear sir How to create windows form application for login screen using C++? USER Name -TESTADMIN Password -testuser c++ c++ i use turbo c++...i want to change the background color...what is the command for it and the header file used C++ C++ Trace the bubble sort using the following integers,which represent the elements in an array. 5,7,3,8,6,7,3 C++ C++ Describe the principle advantages of deploying a linked list versus a static array when implementing a Queue or a Stack Continue statement in jsp Java Training and Tutorials, Core Java Training : The continue Statement: The break Statement... Java Training and Tutorials, Core Java Training Introduction to online Java tutorials for new java programmers. Java is a powerful object C# C# register form i want to generate a user id automatically after filling their register form and i want to show their id to their email? please reply me soon++ .write a program that accepts 5 subjects of a student,it should have a function to calculate the average & another function to grade.grade should be as follows-<40=E,40-49=D,50-59=C,60-69=B & >70 gets a key or character from the keyboard and displays it ASII code in decimal, hexadecimal and binary form.It must also give a description of the key pressed c++ c++ Consider the following declarations: class xClass { public: void func(); void print() const; xClass (); xClass (int, double); private: int u... private members does class xClass have? c. How many constructors does class xClass C String Tokenizer C String Tokenizer In this section, you will learn how to use strtok() function to break the string into a series of tokens. You can see in the given example, we have c++ c++ Write a console based C++ program that reads student information from a text file, build an array of objects of type class StudentInfo... name with the minimum GPA 7) Display Student GPAs as Letter Grades (A, B, C, D c++ c++ Characterize the following algorithm in terms of Big-O notation. Also find the exact number of additions executed by the loop. (Assume that all variables are properly declared.) for (int i = 1; i <= n; i++) sum = sum + i Continue Statement in java 7 Continue Statement in java 7 In this tutorial we will discuss about continue statement in java 7. Continue Statement : Sometimes you need to skip block of statements under specific condition so for that you can use continue c++ c++ write a programme that calculates the area and circumference of a rectangle #include<conio.h> #include<iostream.h> class rect { int l,b; int area; int peri; public: void get_rect() { cout<<"\n c++ c++ Assume vector "x" of integers with values of 7, 3, 5, 8, 1, 9, 0, 4, 2, 6. Second, assume integer variables "a," "b" and "y" with values of 3, x.size()-5 and 0, respectively. Third, assume a for-loop header which: 3.1 Implementing Continue Statement In Java Implementing Continue Statement In Java  ... continue statement. First all of define class "Continue"...*; class Continue{ public static void main(String C++GraphicsTutorials C++ Graphics Tutorials  ... in this document is correct. C/C++ Windows programmers who want to learn... MFC. OpenIL in Dev-C++ OpenIL Loop statement using switch and break The break Keyword The break Keyword  .... In other word we can say that break keyword is used to prematurely exit.... Also break keyword is used for terminate a loop. The break always exits New to programming... fear of pointers... Break the old rhythm. Explore the new... at RoseIndia.Net, we have developed hundreds of tutorials, examples and articles to help.... These tutorials and examples are arranged in a sequence, so that you can learn Java step Break Statement in java 7 Break Statement in java 7 In this tutorial we will discuss about break statement in java 7. Break Statement : Java facilitate you to break the flow of your program by using break statement. The break statement breaks the flow implementation of stacks using linked lists in c++ implementation of stacks using linked lists in c++ how to implementation of stacks using linked lists in c++ #include<stdio.h>...; top=temp; break; case 2: if(top!=NULL all c library functions all c library functions hi dear c coders, i need all c library functions with a detailed explanation. Who can give me usefull link? thanks beforehand! Hi Friend, Please go through the following link: C Tutorials C program - SQL C program Thank You . Write some C programs using pointers . Write some C programs using files. Please reply me . Hi Friend, Please visit the following link:
http://www.roseindia.net/tutorialhelp/comment/99337
CC-MAIN-2014-52
refinedweb
1,997
56.05
Hi guys! As you might have seen, recently there was some spontaneous discussion about the namespaces-working-together problems. Ted T'so proposed to create some document that describes what problems user may have when he/she creates some new namespace, but keeps others shared. I like this idea, so here's the draft with the problems I currently have in mind and can describe somewhat audibly - the "namespaces compatibility list". The Documentation/namespaces/ dir is about to contain more docs about the namespaces stuff (e.g. I'm going to prepare a doc about the pid namespaces, maybe Serge will want to write something about the user namespaces development, Eric may want to put some notes about the netns API and so on), but currently there will be only one file. What would you say about it? Signed-off-by: Pavel Emelyanov <xemul@...> --- diff --git a/Documentation/namespaces/compatibility-list.txt b/Documentation/namespaces/compatibility-list.txt new file mode 100644 index 0000000..4be4a3c --- /dev/null +++ b/Documentation/namespaces/compatibility-list.txt @@ -0,0 +1,32 @@ + Namespaces compatibility list + +This document contains the information about the problems user +may have when creating tasks living in different namespaces. + +Here's the summary. This matrix shows the known problems, that +occur when tasks share some namespace (the columns) while living +in different other namespaces (the raws): + + UTS IPC VFS PID User Net +UTS +IPC 1 +VFS +PID 1 1 +User 2 +Net + +1. Both the IPC and the PID namespaces provide IDs to address + object inside the kernel. E.g. semaphore with ipcid or + process group with pid. + + In both cases, tasks shouldn't try telling this id to some + other task living in different namespace vid shared filesystem + or IPC shmem/message. The fact is that this ID is only valid + within the namespace it was obtained in and may refer to some + other object in another namespace. + +2. Intentionnaly, two equal user ids in different user namespaces + should not be equal from the VFS point of view. In other + words, user 10 in one user namespace shouldn't have the same + access permissions to files, beloging to user 10 in another + namespace. But currently this is not so.
http://article.gmane.org/gmane.linux.kernel.containers/2237
crawl-002
refinedweb
369
62.88
This article shows how to perform basic Dependency Injection (DI) using Spring 3.2 and Context and Dependency Injection (CDI) of Java EE 6. Basically, this will help someone quickly learn one of the technologies when she knows the other. Note: For Spring, we assume that the application is Spring MVC based. Also, for the sake of brevity I don’t create interfaces for Spring beans. Basic Setup For CDI, a file called beans.xml must be present in WEB-INF folder of a WAR file or META-INF folder of a JAR file. The file may be completely empty. If this file is absent, CDI is disabled at runtime. This is a common rookie mistake. In a Spring MVC application, specify the location of the configuration file in web.xml as a part of the Spring dispatcher servlet definition. It is common to break up configuration in multiple files. For example: <servlet> <servlet-name>spring-servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml,/WEB-INF/applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> To enable annotation based DI, the configuration file must specify the Java packages that will be scanned for injection points. You need to specify the parent package only. Spring will scan all child packages. For example: <beans xmlns="" xmlns: </beans> In contrast, CDI will scan all classes at deployment time for injection points. Both will undeploy the application if an injection point can not be resolved for whatever reason. Defining a Managed Bean A bean must be managed by a DI container for all the magic (like injection and method interception) to happen. In CDI, any POJO class can be managed without any modification. For example: public class MyClass { public void doIt() { } } Use the @Named annotation only if you must give the class an EL name. This is something we need to do for JSF controllers so that we can refer to it from a XHTML view file. @Named public class MyClass { public void doIt() { } } In addition to above, a few classes are implicitly managed: - All EJB business classes (annotated with @Stateless, @Stateful etc) are also managed beans without the need to use the @Named annotation. - JSF controller classes can be annotated with either @Named or @ManagedBean. In either case, they are managed by CDI. - Servlets are implicitly managed by CDI. In Spring, use @Component or one of its derivatives like @Controller, @Service and @Repository to make a class managed by DI. It is recommended that you use the appropriate specialized annotations for added benefits. For example, for a Spring MVC controller, use @Controller. Example: @Controller public class MyClass{ } @Component public class AnotherClass { } Injecting a Managed Bean For both Spring and CDI, the class where injection is performed must itself be a managed bean. In other words, both the bean being injected and the bean receiving the injection are managed beans. In CDI, use @Inject to perform injection (define an injection point). @Named public class MyClass { @Inject AnotherClass obj; } public class AnotherClass { } In the example above, we used @Named with MyClass because we intend to use it as a JSF controller. Where as, AnotherClass has no special decoration and can still be managed and injected by CDI. In addition to @Inject, you can use @EJB to inject EJB and @Resource to inject resources like data source. @EJB and @Resource become necessary when you must refer to the injected item by some kind of a string name. In Spring, use the @Autowired annotation to define an injection point. @Controller public class MyClass { @Autowired AnotherClass obj; } @Component public class AnotherClass{ } What is described above is field level injection. Instances can be injected in many other places, like in method parameter and constructor. We will not discuss them here. Bean Lifecycle Events Both Spring and CDI use the @PostConstruct and @PreDestroy annotations to mark lifecycle callback methods. A @PostConstruct method is called after all the injection points have been satisfied. This happens sometime after the costructor and as a result a better place to perform initialization than the constructor. @PreDestroy is called when a bean’s scope is about to be destroyed. For example, if a bean is in session scope and the session is about to expire. CDI example: public class AnotherClass{ @PostConstruct public void init() { } } Spring Example: @Component public class AnotherClass{ @PostConstruct public void init() { } } Bean Scope In CDI, you can put a bean in dependent, request, conversation, session, and application scopes. The default is dependent scope (except JSF controllers are in request scope by default). With dependent scope, a new instance is created to satisfy every injection point. The remaining scopes have a larger lifespan. For example a bean in session scope is created only once per user session. The bean is destroyed when the session expires. CDI provides an annotation for each scope. For example, the following sets the scope of a managed bean to request. @Named @RequestScoped public class AnotherClass { } CDI gives complete flexibility about mixing of scopes. That means, a bean of any scope can inject another bean in any other scope. For example, a session scoped bean can inject a request scoped bean. @Named @SessionScoped public class MyClass { @Inject AnotherClass obj; } Spring works in a very similar way. But, be aware of subtle differences. First, let’s map the CDI scopes with Spring. CDI Scope Spring Scope ================================= Dependent (default) Prototype Request Request Conversation (No equivalent exists) Session Session Application Singleton (default) The default scope in Spring is singleton. Spring provides the @Scope annotation to set the scope of a bean. But, it’s usage is less straightforward and you need to be aware of a few things. The scope of a @Controller is fixed as a singleton and you can’t change it. A single instance of a controller is used to serve all requests from any user. So, be aware of thread safety and information leakage across users. Spring supports mixing of scopes. For example, a controller that is always a singleton can inject a request scoped bean. But, this takes a little extra work. @Controller public class MyClass { @Autowired AnotherClass obj; } @Component @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "request") public class AnotherClass { } The extra work I was talking about is setting the proxyMode attribute. With proxy enabled, Spring wraps the actual bean instance in a dynamic proxy. This is necessary for injecting a bean with a shorter lifespan (request) in a longer lifespan (singleton) bean. In the example above, the injected instance of AnotherClass is created in the request scope. As a result, it is safe as a member variable of the controller which itself is a singleton. This is not your usual Java programming and takes a little getting used to. The same magic happens in CDI, which uses proxy in all cases, except for dependent scope. Basically, with a proxy, a bean is instantiated lazily on demand. Consider a method of the controller: @Controller public class MyClass { @Autowired AnotherClass obj; public String doIt() { System.out.println("Controller doing it"); obj.doSomething(); //Injected instance created here } } An instance of AnotherClass is created very late just prior to calling the doSomething() method. Once again, this instance is created in request scope and completely distinct for every request. So, the code above is completely safe without any worry for thread safety or information leakage between users. The principles are exactly the same for CDI. Except, there, proxy is always used and there is no need to set a proxyMode type flag anywhere. Proxy mode does not need to be set when a bean injects another bean that has the same or longer lifespan. For example, a bean in request scope can inject a bean in session scope without setting the proxy. @Component @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "request") public class AnotherClass { @Autowired ClassB obj; } @Component @Scope(value = "session") public class ClassB { } Alternative Bean Resolution One of the biggest benefits of DI is that you can switch the implementation of a bean throughout an application without making mass changes. For example, we can switch a data access class that fetches data from a SQL database to another class that uses Web Service. The basic mechanism is same for Spring and CDI. Your application contains multiple classes that are candidates for injection at an injection point. Then you use some kind of configuration to narrow down the choice to a single candidate. There are several ways of doing alternative bean resolution in CDI. One way is to disable a non-candidate bean using @Alternative. public interface MyService { public void doIt(); } @Alternative //Disable this class public class ServiceA implements MyService { @Override public void doIt() { } } public class ServiceB implements MyService { @Override public void doIt() { } } @Named public class HomeController { @Inject MyService obj; //ServiceB will be injected } In Spring, mark the preferred injection candidate with @Primary. public interface MyService { public void doIt(); } @Component public class ServiceA implements MyService { @Override public void doIt() { } } @Primary @Component public class ServiceB implements MyService { @Override public void doIt() { } } @Controller public class HomeController { @Autowired MyService obj; //ServiceB will be injected } Custom Bean Creation By default, the DI container (Spring or CDI) is responsible for instantiating an injected bean instance. It uses the zero argument constructor to create the object. Some classes may not have a zero arg constructor or may need special initialization sequence. These beans can not be managed by the container. The solution is to provide one’s own bean creation routine. In CDI, this is done using a producer method. A producer method returns an instance of a bean. It becomes the source of the bean at an injection point. To avoid ambiguity, we must declare the bean itself as an alternative. @Alternative public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Person(String name) { super(); this.name = name; } } Then, we can define a producer class that acts as a factory. public class PersonFactory { @Produces @RequestScoped public Person createPerson() { return new Person("Daffy Duck"); } } Note, you can set the scope of the bean. Similarly, if you need to give the bean an EL name, you can use @Named. The bean can be injected as usual: @Named public class MyClass { @Inject Person person; } Now, at the point of injection, the createPerson() method will be called. If we did not designate the Person class as an alternative, there will be two potential sources for the bean’s instance. This leads to ambiguity and error during deployment. In Spring, if a bean is created by a factory class, there is no need to designate the bean class using @Component. public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Person(String name) { super(); this.name = name; } } The factory class and its producer method is declared as follows. @Configuration public class PersonFactory { @Bean @Scope(value = "request") public Person createPerson() { return new Person("Daffy Duck"); } } Note, just as in CDI, you can set the scope with the producer method. Summary Spring and CDI are both very capable DI containers. As we have seen here, they work in a very similar manner. Unfortunately, bulk of Spring documentation still uses the old XML syntax. Finding information about annotation based processing is unusually difficult. Hopefully, this article will be useful for someone who want to do apples to apples comparison of the two technologies. 12 thoughts on “Spring DI and CDI Comparative Study” The best tutorial on CDI. thanks so much One of the biggest problems that CDI has is the alternate strategy being isolated to a jar. If you had a war app and classes Foo and Bar that implemented the FooBar interface and wanted to provide alternatives for the classes in WEB-INF/classes you would be fine. But if you had 2 jars that had classes using Foo and wanted to switch to Bar you would have to crack open those 2 jars and specify the alternate within the beans.xml in each respective jar. Specialization is the only way to override behavior application wide and that requires extending the class you wish to override. In Spring you could have a completely annotation driven app while having the ability to override a particular implementation with xml which, would not require recompilation or opening jars that might contain other infrastructure code you were trying to override a bean reference for. Thanks, nice post Thank you for this comparision and introduction. 🙂 Very helpful comparison. However… I actually like/prefer Spring’s xml configuration. I like not cluttering my code with annotations, especially not vendor/framework-specific ones. That is, I like my code being true POJOs and doing the “injecting” from the outside. I can accept using standards-based annotations, but this is all still more verbose and coupled, IMO, than XML definition with un-annotated POJOs. Sorry, just thinking aloud. Don’t know if I’m missing something… I agree with above comment. I prefer using xml configuration so that you don’t have to recompile java code in order to change annotation Cdi is quite standard, even spring supports most of its annotation. And since you’re using a bean container, do not fight your framework. annotation is cleaner way of telling spring to manage a bean and same as injecting them to its dependent classes. Also when you work on a module, you just have to drill down on related classes within that module if you are using package by feature over layer, and you dont have to look somewhere else such as xml configurations, xml is very cluttered and verbose. If you are applying layering architecture and module levelization, then your way of looking into class relationships would be pretty standard and easy. For me it just feels easy and clean. thanks for a very clear article Great article! Actually, CDI offers more than is mentioned in this article. I’d also like to point out that CDI’s Application scope is not equal to Spring’s singleton scope ! Application scoped bean may be instantiated multiple times. The true opposite is @Singleton in CDI. Application scope is also not available in Spring.
https://mobiarch.wordpress.com/2013/01/11/spring-di-and-cdi-comparative-study/
CC-MAIN-2017-22
refinedweb
2,373
56.15
Infragistics Team, I have been using Infragistics tools for most of a decade, and have been supporting my developer peers in the Infragistics forums for nearly that long. I would really appreciate you giving this proposal some serious thought. I have taken a lot of time to think this through and document it for you, and I hope you will afford this suggestion appropriate consideration. I have been chewing on an idea for a long time that would be an enhancement to the Infragistics documentation and support website. You really need a community-driven code samples area, preferably cross-linked into the documentation. You have made some efforts at code samples in the past... And they have been pretty good. Your staff content authors are brilliant. Tony, Craig, and Murtaza are amazing, and I love reading their stuff. The problem with each effort has had to do with goal and structure, not content. Here is a summary. I know documentation is tedious, and is not really core to what you do (which is developing outstanding tools). Having a community code sample site would actually take some pressure off of your documentation team, because people could go to the community site to fill in the gaps. I am sure it would also take some pressure off of your support staff. So here is what I am thinking would be features of a Community Code Samples website... Like I said, I have put a lot of time in using your products, and fleshing out this proposal. I believe that this suggestion offers some real gains to your company in reduced documentation and support pressure. That translates to real dollars and cents in reduced support costs. Even more than that, it will help galvanize the loyalty of your user community. Your talented users will feel appreciated, and your new users will more quickly tie in to the sense of community. That translates into real dollars and cents in increased sales and retention. I hope you will consider it. Thanks, Rob Hudson Rob: Thanks – thanks for the time you took out of your day to write to us. Thanks for the time you spent thinking through a challenging problem and thanks for pointing out how Infragistics can improve to benefit not only you, but all of our customers. You’ve mentioned a number of issues here and I am going to do my best to carefully deal with each one. Please don’t hesitate to correct or guide me as I work through these issues because your feedback is invaluable. Even though Infragistics is, as viewed by many, a ‘controls vendor’ – that by no means diminishes our commitment to customer support. We have teams that live and breathe the developer support, documentation, samples and design experiences for our customers. The bottom line is we care deeply about how each of these departments relate to you – so your suggestions, thoughts and ideas are welcome anytime. Your proposal for leveraging the Infragistics customer community by strengthening code samples and making content more discoverable makes a lot of sense. To begin, though, I have some good news and some bad news. The good news is the highest priority among the company at this time surrounds shipping our new corporate website. Now that may not sound relevant to our discussion but please allow me to explain. We have recognized that one of the main difficulties that our customers face is the daunting task of trying to find information. Right now information about our products is scattered across the myriad of Infragistics web properties making it hard for customers to know where to go for what information. The bedrock feature of our new website is an integrated faceted search that not only returns search results from: …but also allows you to filter in or out the types of content (blog posts, samples, forums, etc.) you want along with related tags. The ability to search across all the content silos of the company and quickly narrow down to what you are looking for will, I certainly hope, provide a much more effective way of getting the answers you need. Note: Our current site has a “global” search available at, but the search in our new site far out-performs this search engine. Now for the bad news. Based on our research we stopped putting resources behind code samples because the response we’ve heard is a desire for more in-depth samples and topics that extend beyond the base-level concepts and code snippets. Unfortunately code samples, as they stand today, haven’t met the needs for more comprehensive learning. But as they say, “never say never”. From what I understand your desire is to address: how can Infragistics open up access to our rich community of customers to enable better collaboration? Our past hesitation to granting open access to areas of our sites is rooted in some bad experiences we encountered with users not being responsible with the power to post content to our sites. Invariably these problems lead us to consider very carefully what we are able to make open to the public and what needs to be locked down. Therefore what I would like to do is to get you in contact with a member of our Interaction Design Team, Riddhima Shelat. She is about the business of making sure our new website is usable, beautiful and fulfills the needs of our customers. Perhaps we can work together to find a reasonable answer to how we can open up the keys to the kingdom more? Another point you mentioned is that our documentation is a “last resort” in the options you consider while attempting to learn how to use Infragistics’ products. I’d love for that not to be the case and I’d like to share some of proactive steps we are taking to increase the quality and coverage of our documentation: Focusing on the Important and the Urgent With each release cycle we face the same dilemma. How much of our resources do we allocate to shoring up existing samples and documentation and how much of those resources are pointed toward supporting content around the latest release? For the most part the Product Guidance (PG) team has placed the highest priority on supporting new products. After all if customers don’t have resources to learn new products how will they ever start using them, right? The problem with this mindset is that more in-depth content that we would have liked to provide during the previous release is often skipped in light of providing new content for new features. To speak to this problem we are instituting a new PG role which is reserved 100% during a release cycle for working with existing documentation. People in this role will: My hope is that by establishing and supporting this role existing issues among product samples and documentation will dissipate over the long run. Enhancing the Presentation We are currently looking at a few options that present some ways for us to change direction regarding how we provide content on the web and on our customer’s machines. Our current approach is too restrictive to really allow us to make our content as discoverable as possible. We are looking toward updating our tooling and processes that will allow us to better present our content that better facilitate searching, scanning content and provide an overall better experience with our content. Improving Quality In the past Infragistics has used outside editing firms who were responsible for editing our documentation. The feedback we would get would be to fix a few grammatical errors and correct some spelling mistakes. Today we have established in-house editing staff. Going far beyond a few spelling tweaks our editing team is working hard to build a “consistent voice” among our documentation and help enforce a higher standard among our written work. Further, we are adopting the Information Mapping writing technique to create documents that are clearer, easier to scan and that help readers find and understand relevant content faster than ever. Since I still don’t feel like I’ve provided a good enough answer for you regarding your overall question, I’ll pursue this further with our design and development teams to see if there are some features of our new website that we can build around exposing more to community contributions. While we won’t be able to introduce anything beyond our current project plan in the first version, perhaps with some design interaction we can create something that will work for a coming release of the site. Further, as I read your post I was wondering if you could help me by understanding better the answers to the following questions: 1 What does good “How to” content look like? I don’t want to make any assumptions here. We have some ideas, but I’d love to get your perspective on exactly what you’re looking for. 2 How can we make showcase samples more relevant while still being flexible enough for change? One issue I see with your suggestion for deep linking into the showcase samples is that we must be able to account for change. When the code in a sample is updated then there is a risk that a description in a topic is then out of sync. What would you like to see? 3 Would you be in support of us somehow integrating something like the code samples in the same structure of our feature samples? Doing this may give you the organizational structure you’re describing and make a clean way to integrate some other approach in our existing framework. 4 Can we contact you outside the forums for feedback regarding our new website and other advancements we’re considering? Your experience with our products, well-crafted insight and obvious desire to see conditions improve make your direct feedback coveted. Thanks once again, Rob. I know some of what I’ve discussed goes beyond the original scope of your post, but I hope that you see that I share all this information in the spirit of demonstrating that we are dedicated to the process of continually improving your interactions with us on all levels. We won’t always get it right and much of what we are doing represents a long-term dedication to improvement, but together I think we can make some significant change. Best, Craig PS: I have included my contact information along with some of my colleagues at Infragistics if you or any others would like to continue this conversation on this thread or by any other means that is most convenient for you. Craig Shoemaker Product Guidance Manager cshoemaker@infragistics.com 951-310-4496 @craigshoemaker Stephani Smyth Director, Developer Support DSManager@infragistics.com609-448-2000 X 1139 Riddhima Shelat Interaction Designer RShelat@infragistics.com 609-448-2000 X 1258 Craig ShoemakerProduct Guidance ManagerBlog | Pixel8 Craig, Your response reminds me exactly of why I have been loyal to Infragistics for so long. I don't want to sound like I am coming down on your support or documentation team. Lord knows there is a ton of documentation, blogs, etc, all over the place. I see the result of a tremendous amount of work. Your support team has some really strong players as well. Whenever Victor or Tsvetelina chimes in on a conversation, you know it's going to be resolved, and usually in an elegant way. I have had a chance to read through your response... and the idea that the bedrock of the new site is a global search leaves me disappointed. Maybe it's a personal flaw of mine, but when I want to find information, I gravitate to structured sources rather than unstructured fuzzy sources. My instinct is to go to documentation and find the control/feature, and expect to find the answer there. Using search feels like a desperate last resort to find something that should have been intuitively placed from the beginning. Maybe it is a better global search... but it feels awkward building a search, guessing at keywords, and setting filters, when it should be as easy as pulling up a control from an organized hierarchy and scanning a list of articles. A few notes specifically on your well-thought-out response. In response to your questions: I appreciate that the all products and processes have flaws, and I do not have "perfection" as my expectation. I love your products, and will continue to use them regardless of what you might do with my input. Lastly, I have a couple of more insights. I think really, there are two main challenges with the Infragistics support site now. The first challenge, I think, is despite all of the content, it lacks cohesive structure. Where do I go if I have a "How do I" question? Do I go to the documentation, a sample website, a blog, the forums, or the sample browser? Who knows... the answer may lie in any one of those places, and maybe not in any of them. But I have to check all of them. You would have me search all of these globally, but you are making me work to find information that should be organized. A cohesive structure could be provided by the tree hierarchy in the documentation, but it's not linked to anything. The second basic challenge is more fundamental... I think the documentation is designed to answer the wrong questions. If my question is "What is the class structure of the xyz object?" The documentation has an answer for me. But that's rarely the question I have in my mind when I go searching. 99% of the time, the question is some variant of "How do I.....?" Craig, I want you to look at this forum post by another seasoned user, posted only yesterday. His forum post really deserves as much attention than anything I have written. It is simple... only three sentences... but it speaks volumes, and should reverberate.. He says simply "Frustrated here trying to do one of the most common things possible in JavaScript for WebTab. Change the tab. Can't find it anywhere." This guy isn't a slouch. He's been with Infragistics since the classic controls. If a seasoned user is having this much trouble trying to use the documentation to perform simple tasks, how much more do new users struggle? And is there actual documentation to answer his question? Yeah, there is technically documentation. Nested 6 levels deep, buried beneath topics on namespaces and classes, in a property description. There is no place to go to get a simple answer to the question "How do I do this very common task..." Today, I spent much of my day teaching one of my junior developers how to customize output in the WebDocumentExporter and WebExcelExporter CellExported events. Why? Because he came to me and said "I looked everywhere, and I can't find documentation on how to customize output." He didn't even have an inkling that the CellExported event is where you would want to do this kind of customization. I knew how to do it... but how? Not because of anything in the documentation... but because of a code sample Tsvetelina posted in the forums in response to one of my questions. Ultimately, this lack of documentation cost me in development time weeks ago, when I had to hunt it down. It cost Tsvetelina (and by connection, it cost you) in her taking the time to respond. And it cost me twice again today both for me and my helper, in the time it took to train him. If IG would have afforded me the opportunity, I would have gladly taken what I showed him and posted it as a code sample to a public library to prevent this from happening to others. But as it is, it is simply valuable time lost... for me, my protege, Tsvetelina, and the next chap who has this question (and Tsvetelina again when she has to respond to his support request). That is four separate times this one lack of documentation has cost both of our companies valuable time... needlessly. And several of them could have been avoided. What really baffles me is why Tsvetelina wasn't given the opportunity to post the code sample into the core documentation... redeeming herself from having to answer the same questions over and over again. She's internal, knowledgeable, and immensely helpful.. but even she can't contribute code samples to an easy-to-use library. It sounds to me like the worst side of politics. I really believe that if you shift the focus of the documentation away from "What are the technical specifications of xyz" to "How do I?" I think that solves most of the problems. But I recognize that that sounds much easier than it actually is. Just the math of it is daunting. The number of useful tasks a person can perform with your tools is some multiplication of the combination of features, increased again by multiplying the combination of controls. It's a massive project. As you mentioned, resources are limited, and resources are weighted toward documenting new features. I don't personally think you can accomplish a project of that scale while limiting yourself to only staff sources. Without leveraging the community, the achievement of a comprehensive "how do I?" library may be impossible. If you will humor me, let me describe my ideal Infragistics documentation site. Regarding documentation... and I can't underscore it enough...This could be a mission statement for the documentation team. A person should feel confident that if they go to the documentation, they will find the answer in an intuitive way. Even if the documentation doesn't have the actual information, it will contain a current intelligent link to some resource that has the information. And most of the time anyone goes to the documentation, their question is "How do I...?". The documentation as it is now is basically a static help file. Instead, it should be a dynamic, breathing, growing documentation website, which is cross-linked by feature to *everything*. The tree structure that you have now is fine, because it provides structure and organization, but content within each document should be dynamic. Within each page of the documentation, you should have links to the following: Second, my ideal Infragistics support site should have a comprehensive "How Do I..." library. This is where you need samples of how to do everything, from the basic to the advanced. I feel that that can't be fully accomplished without community involvement, but that's not my decision. But even if you only increase scope to allow contributions by internal support staff, it would be a lot better than it is. Right now, it appears your support staff can only contribute to the forums. I have worked support. They would love to contribute to the documentation, if only to make their own jobs easier. Just let them contribute to the samples library. Want to know how to download a WebExcelExporter spreadsheet asynchronously? Duane Hoyte's article is there instead of being lost in the forums. Want to know how to change a selected tab in Javascript? Tsvetelana fielded a support question on that, so she posted a sample for all to benefit. Thank you, and cheers, -Rob Thanks for being a loyal customer for so long! Please understand that I certainly didn’t take your comments as you were coming down on anyone. I just wanted you to know that we at Infragistics truly do view ourselves as much more than just an Engineering firm. Like I said, I really value your perspectives. You care, you are well-spoken and your criticism is both specific and constructive. (You’re calling out people by name like you’ve been working here for 5 years - why oh why are you in Texas! I can’t take you out to lunch from there :) I’ve tried to distill the main topics of our conversation below. Again, let me know if I miss anything… Search as a Bedrock Our focus on search emerged from customer research that told us that people valued the Google-like search experience and wanted to use search as a viable means of finding the content they need. That being said we plan to keep our structured access to samples and topics. My hope is that the “best of both worlds” approach will help facilitate much better discoverability. Our rationale: The structured access is valuable when you look in the right place – search will expose content when you don’t know where to look. Showcase Samples Database Fleshing this out will require some deeper interaction than the scope of this post. Expect a phone call :) New Samples Browser Interface I am not satisfied with the samples interface either. For various reasons we shipped the revamped samples browser as-is and not only is there a lot to be desired, but we have also made some great strides in moving the interface beyond what you see here. Our updated samples navigation includes a search mechanism allowing you to search the samples. Further, “New” and “CTP” flags will return next to the samples titles so you’ll be able to differentiate among samples. (I’ll send you a screenshot and you can tell me what you think.) Our rationale: Some of the trees were pretty big and organization can be difficult. The new concept provides organization with search. Creating Dynamic Content To better augment our current topics we could render a series of related links at the bottom of each document that represents the results of our search against tags and other metadata available in the current topic. What do you think of this approach? 5 Building Cohesive Structure To go beyond making individual help topics more dynamic, what do you think about creating a ‘How Do I’ section in the documentation tree which pulls in content tagged with our ‘How Do I’ tag and organizes it for the reader? Would you suggest something else or something more? 6 Code Snippets After some discussions among our web team we see a path that may make it possible to re-instate the code samples functionality. We could even extend the core to allow moderated community involvement. This area would be categorized in the same manner as our samples and could be available to internal teams like Evangelism, Services, Developer Support as well as community members like you. Are we on the right track? What if this were extended to include articles as well as code? Note: This functionality is in a conceptual state at the moment and would not be available in v1 of our new website. 7 Crafting ‘How Do I’ Content As you stated, orienting our help content around the “How Do I” perspective is a bit easier said than done. Once again, in the spirit of making no assumptions, how will I know when I’ve created an acceptable “How Do I” topic? Let’s look at the igGrid Columns and Layout topic from our last release. What can we do differently? Even just a few bullets of your ideas would be great. 8 Organizing ‘How Do I’ Content If we placed more emphasis on “How Do I” content what format do you think would be the best way to present the information? I have mocked up two approaches below. The first format organizes the content by type giving the reader a quick way to discern the different types of content available. The second example organizes all the content together regardless of type showing a more topical type of organization. A third approach possible (but difficult to depict here) is the same as the second approach where instead of bullet points the links are preceded by icons giving a clue to the content type. 1) Organized By Content Type WebDataGrid: How To Samples Topics Forum Posts Blog Posts Videos 2) Organized By Subject WebDataGrid : How To CRUD: Paging Would you suggest one of these approaches or something entirely different? Perhaps we could generate a page like this for each product on a weekly basis to keep the contents fresh. 9 Other Resource Beyond Samples and Topics Have you ever used the WebDataGrid Cheat Sheet or our Startup Solutions? Do you see any value in these resources? I am really enjoying this conversation and please know that there are many more at Infragistics that are reading along and examining the topics we discussing here. You are making a difference. Wow, ok, so many things... First responses to your specific notes. Just now finding out about the Cheat Sheet prompts me to add one more topic to our conversation... That is how to communicate new information to end users. Information subscription needs to be centralized, and topic-based.... with the option to subscribe to notifications across all sources based on topic. Right now, just looking at the Community ASP.Net tab, let's see what information I can subscribe to and what my notification options are... Pretty much, if you guys post anything to any of the tabs in the ASP.Net support page, it is only discoverable by users if they manually come to the site and click on each tab looking for new content. I don't have time to do that. Maybe that's one reason your posts to these pages don't yield impact that you might hope for? How should subscriptions work? I want to be able to subscribe to email updates *by topic across all sources*. I don't want to have to subscribe to each source individually. I work with a handful of controls, but I use those controls very heavily. I want to have a subscription option that says "send me all new posts about the WebDataGrid, regardless of whether that post is a blog, article, code sample, video, or whatever new source you might introduce". Quick update... I just noticed the "RSS Subscribe" button located in the tab row used for navigation. No wonder I missed it. It's in literally the last place I would look. When I was looking for the RSS option, I scanned the whitespace at the top, bottom, and sides of the content area. I also checked the page footer and page header. It never occurred to me that it might be in the navigation area. Also, the Blogs page that announces the Cheatsheet does not have an RSS option, even in the navigation area. I hope you had a good weekend! I had a few responses and answers to your last posts: Search The search you see on the site right now does not index the same information nor is it the same engine as what will soon power our new site. I think you'll find many of your concerns regarding search will be alleviated when we bring our new engine live. I still expect to have areas where we can improve, but I think we'll take a big step in the right direction with our new search. Plus, remember that we're still going to have formal and loosely structured areas of the site as well. We can look into the tagging approaches you suggest. We don't have anything hierarchical planned at the moment, but we are instituting a much more rigid tagging schema which is primarily maintained by our Interaction Design Group, the same folks to oversee our APIs. Showcase Samples Yes, the showcase samples and the Application Samples are one in the same Samples Browser Again, I agree with you regarding the samples browser. What we have up today is a trimmed down version of the real browser going up with the new site. Beyond it just being less functional, we have also redesigned the navigational area with much more explicit UI elements - including page numbers in place of the cryptic dots! Good point - I was just throwing a concept your way. We'll certainly have to think through any approach. We certainly want any 'related' information to be related indeed. Again the search we using is a search appliance with an API allowing us to customize the results. This is far beyond anything we have live at the moment. Building a Cohesive Structure Yes - I was thinking for this to work the returned data would have to match the control or feature name and must have the 'How To' tag applied to the topic. These are great ideas. I'll chat with our Developer Support lead about your ideas when we get to the point of making the integration changes. Crafting 'How Do I' Content I've asked everyone on my team to read your suggestions regarding perspectives for creating content. What's nice is that some of the structural changes we're making in our writing address a few of the items you call out specifically. The inherent problem here though (as you pointed out earlier) is that since there really are so many different ways and contexts a control or feature may be used, we often find it difficult to define the right 'How to' scenarios. Organizing 'How Do I' Content Again - great suggestions. We'll refer back to your ideas as we develop the features. Other Resources I'm so glad you like the cheat sheet! Grid migration was one use I was hoping for people to find great benefit from the sheet. Right now we not doing all we can to help people find the cheat sheet, startup solutions and the like. Notifications & RSS The limitations of our RSS and notification systems are largely rooted in the software we're running to power our Community site. Here also, I'll spend some time with our web team to discuss how we can deal with these issues in our new website. Thank you very much! I have appreciated the opportunity to contribute, and I look forward to great things from Infragistics as a whole. There are several very good reasons that you guys dominate. A little over a year ago, we had this really valuable discussion. I haven't been active on the website this last year, because I've been focused on customer deployments and migrating off of 11.1. I am just now diving back in. I am curious what progress has been made on topics addressed in this thread. Looking through the forums this morning, there is one thing that strikes me. It appears that the support staff are still relegated to posting their code samples into the forums, where their work is poorly categorized, and will be eventually lost. Are you guys working on a place where they can put code samples that is organized and can be easily referenced? Also, as a source of inspiration for managing sample code, have you seen what Microsoft is doing with their OneScript website? It looks pretty genius. Thanks, - Rob Rob, thank you for reply to your old post that I've missed!!! I'm also a decade-customer of IG and I SUBSCRIBE ALL of your statements in your main posts. You have done a great job with great content, many thanks for having wrote the "thinking" of most of us. PS: Microsoft it's a non standard company ... they are bigger but they move forward their brain ... not always ;). If you use VS2010 I really suggest to you VS2012, MS team have done a great job. Regards and have a nice Halloween,Davide Thanks Davide, it is good to meet another Infragistics fan! I have not upgraded to VS2012 yet... I have to migrate our SCC to TFS first. We have been using SourceGear for SCC. Their heart is in the right place, but it's just too buggy. No reply from Infragistics yet... It is possible that they have their hands full, with Hurricane Sandy disrupting the country and all. Hopefully they'll get around to this in a few days. Great to hear from you again, Rob and nice to meet you Davide! As you can see from the new site, the new search and other we've been able to make public much of what we had cooking behind the scenes when this thread started. As for the code repository, that is still something we haven't had an opportunity to implement yet. We have some new folks on our web team and I will make sure they read this thread so we can continue that discussion. Hey Craig, hope you are doing well. I know you are busy, and don't expect your personal attention. If you want to pass this to a henchman, that is fine with me. Infragistics has provided you with a hidden lair and henchmen, haven't they? Some initial feedback for the henchmen: Search: I spent some time exploring the new support site this morning... I put in the same "real world" searches that I did last year, to see if the results are better. I searched "webdatagrid summaryrow behavior" to see if there was anything available for customizing the output of the SummaryRow. The results were mixed, but better than last year. While only two results were returned, both of these results were related tangentially, and maybe useful... Both were "How Do I" documents, one of which was a "How Do I" video, and the other was a blog post that contained a video. Both were very general to WebDataGrid, and not very specific to Summary Row. There were no links to the documentation or forum posts that might be relevant. No links to the samples browser that might also have an example. No links to the sample applications either. I would have expected search results to return both documentation and forum posts as possibilities. I see the use of tags is improved, with the inclusion of the "How Do I" tag. Love that. I searched "webtab javascript change tab" to see if there was any info on how to change the tab from JavaScript. No search results returned. I tried again with "webtab CSOM change tab". No results returned. I tried again with just "webtab change tab". There were links to general WebTab documentation, but the top level links didn't include anything on using JavaScript. The user will still have to dig into the documentation. The forum post where this question was answered specifically did not appear in search results. I wanted to find out if there was information on how to customize the output of individual cells WebExcelExporter. I searched for "webexcelexporter customize". No search results were returned. I searched for "webexcelexporter cellexported". No results found. However, several possibly relevant results were returned if I just searched for "WebExcelExporter". The new search feels finicky, and I haven't yet received relevant information on a first attempt. It feels like work, and a gamble. Maybe the strategy for using search is to not be specific in the search phrase... but I want to be specific so that my search results will be relevant. Documentation: I do like the layout of the support page, where you can tab between "Search" and "Control Specific Help". After clicking "Control Specific Help", and selecting my environment, I was instantly drawn to the "Popular Blogs" section. It's the first thing I noticed, and I felt compelled to explore some of the blogs before I even started looking at the documentation. Several of them were highly relevant to me. I can see how selecting options in the "Control Specific Help" basically returns results from the same Search engine that drives the Search window, however these results all appear specific and informative. I don't have the same complaints when working with this interface.. I can live with that, as long as the results are relevant, which they are. I am struggling a little with the color scheme. Light-blue links on white background looks terrific on my desktop, but on my laptop it is hard on the eyes to try to read. I am a little annoyed that the forum is aggressively removing markup from posts. I love to use bullets, and the HTML editor has bullets in the toolbar, but they are stripped out of forum posts. My one piece of advice is this: While you guys are fine-tuning the organic search function, you should make the support page default to "Control Specific Help". Don't make people spin their wheels with organic search when the drill-down tool is presently much more helpful. I agree with Rob, but not on this: ." IMO IS NOT FORGIVABLE, the User Experience is emabrassing ... especially by those who promote it as an added value, which is ;) This issue on their WEB UI probably shows that it is more difficult to create a full UI that the individual components. I always had a feeling from IG ... that it is a bit "away" from the real world of theirs customer, but is a my sensation ... not the reality ;) However, congratulations, you have made progress, but do not stop! The leadership must be keep it! I think Rob has given you most valuable advice, more than a cold consultant ;)Best,Davide. Rob and Davide: I apologize it's taken me so long to follow up on this thread... I have asked our Web team to follow this thread so they are hearing from you directly. Your feedback is not only greatly appreciated, but very valuable. We're continually working the site so please feel free to share anything else that can help us improve.
http://www.infragistics.com/community/forums/p/59078/300595.aspx
CC-MAIN-2014-52
refinedweb
6,287
62.88
Results 1 to 2 of 2 - Join Date - Mar 2012 - 2 - Thanks - 1 - Thanked 0 Times in 0 Posts Simple Java (symbol error) problem Hey sorry to double post but i am at my wits end trying to understand why my code is not working. I understand that there is very likely some simple problems that need fixing but this i do not need help with. When i try to compile this it tells me it cannot find the createNewFile() and .exists() symbols but i made sure to import them correctly and unless i can no longer see the wood from the trees im stumped. A bottle of guinness for the first fellow who can help Thanks, S. Code: import java.io.*; import javax.swing.JOptionPane; import java.util.*; import java.util.Collections; import java.io.File; public class DictionaryProject { public static int count= 0; public static String userInput= "", tempFile, dictFile; public static String userMessage =""; public static void main (String [] args) throws IOException { String message1= "1. Add word\n" + "2. Delete word \n" + "3. Search \n" + "4. List on screen dictionary entries\n" + "5. List secondary functions"; String message2= "1. Add your word now:\n " + "2. Finished creating(Return to main options menu)\n"; String message3= "1. Delete word now:\n" + "2. Finished destroying (return to main menu)\n"; String message4= "1. Search for your word now:\n" + "2. Finished fishing (return to main menu)\n"; String message5= "Display the...\n" + "a. Number of words in dictionary.\n" + "b. Number of words that start with each letter of the alphabet\n" + "c. Number of pallidromes within dictionary\n" + "d. The shortest word\n" + "e. The longest word\n"; String pattern1= "[0-9, A-Z, a-z] {1,}.txt"; String pattern2= "1|2|3|4|5"; String pattern3= "a|b|c|e"; String temporaryFile, dictionaryFile, result; Vector preDictionaryList = new Vector(); dictionaryFile = JOptionPane.showInputDialog(null, "Enter the name of your dictionary file now: /n"); temporaryFile = JOptionPane.showInputDialog(null, "Enter then name of your temporary file now: /n"); temporaryFile = temporaryFile.toLowerCase(); dictionaryFile = dictionaryFile.toLowerCase(); if (!(dictionaryFile.matches(pattern1) || temporaryFile.matches(pattern1))) { result = "The file name entered does not match the required criteria, please ensure your filenames are spelt correctly."; } else { File dictFile = new File (dictionaryFile); File tempFile = new File (temporaryFile); } if( !(dictFile.exists() || tempFile.exists())) { result = "File does not exist, Creating file now"; dictFile.createNewFile(); tempFile.createNewFile(); FileWriter fw1 =new FileWriter(dictFile); FileWriter fw2 =new FileWriter(tempFile); BufferedWriter bw1 = new BufferedWriter(fw1); BufferedWriter bw2 = new BufferedWriter(fw2); } else { FileWriter fw1 =new FileWriter(dictFile); FileWriter fw2 =new FileWriter(tempFile); BufferedWriter bw1 = new BufferedWriter(fw1); BufferedWriter bw2 = new BufferedWriter(fw2); } } - Join Date - Sep 2002 - Location - Saskatoon, Saskatchewan - 17,027 - Thanks - 4 - Thanked 2,668 Times in 2,637 Posts This is a scope issue. When you are in the else, File declared and will not be available outside of the else. Move the entire if and else block for the exists check into the else clause of the .matches check. If the match for the file fails, then the entire lower section shouldn't execute at all. The alternative is to declare the File objects before any of the if/else calls, and add a != null check to the exists block (since now there is no guarantee that File has been constructed). I'd suggest moving it into the else since its just easier to move one bracket down.
http://www.codingforums.com/java-and-jsp/255082-simple-java-symbol-error-problem.html
CC-MAIN-2016-07
refinedweb
564
66.84
29 March 2010 19:56 [Source: ICIS news] By Joseph Chang SAN ANTONIO, Texas (ICIS news)--ExxonMobil Chemical’s petrochemical project on Jurong Island, Singapore, is approaching peak construction activity and is on track to start up in stages through 2011, a senior executive said on Monday. “The ?xml:namespace> “We will stage in mechanical completion of units from late 2010 through 2011,” she added in an interview with ICIS news on the sidelines of the International Petrochemical Conference (IPC). Lachenmyer would not specify the order in which the units would start up. The project would include a 1m tonne/year ethylene cracker, two polyethylene (PE) trains of 650,000 tonnes/year each, and specialty elastomers production, she said. ExxonMobil already has a 900,000 tonne/year cracker at the The company and its partners started up their The site has an 800,000 tonne/year cracker, an 800,000 tonne/year PE unit and a 400,000 tonne/year polypropylene (PP) unit. It includes paraxylene (PX) capacity of 780,000 tonnes, she said. ExxonMobil has a 25% interest in the
http://www.icis.com/Articles/2010/03/29/9346824/npra-10-exxonmobils-singapore-petchems-on-track.html
CC-MAIN-2015-06
refinedweb
181
55.98
stable null safety release (#62) The Dart project benchmark harness is the recommended starting point when building a benchmark for Dart. You can read more about Benchmarking the Dart VM. 1. Add the following to your project's pubspec.yaml dependencies: benchmark_harness: any 2. Install pub packages pub install 3. Add the following import: import 'package:benchmark_harness/benchmark_harness.dart'; 4. Create a benchmark class which inherits from BenchmarkBase(); } Template(RunTime): 0.1568472448997197 us. This is the average amount of time it takes to run run() 10 times. µs is an abbreviation for microseconds. This package is carefully curated by the Dart team to exact specifications. Please open an issue with any proposed changes, before submitting a Pull Request.
https://dart.googlesource.com/benchmark_harness/+/refs/tags/2.0.0
CC-MAIN-2022-21
refinedweb
118
61.22
I need to pass the variable to a python program consisting of special character in it. Not sure if it is silly thing or not. i am new to the python programing. Here a small script used to connect the local postgres db and run a query. >/usr/bin/python emp.py emp-1345 #!/usr/bin/python import psycopg2 as pdb import sys import pprint conn_string = "host='localhost' dbname='emp' user='emp' password='emp'" conn = pdb.connect (conn_string) cursor = conn.cursor () empid = sys.argv[1] print "Arg1", empid cursor.execute ("SELECT sal FROM emp.empfieldvalue WHERE eid = (SELECT id FROM emp.empinfo WHERE id = 'empid') AND dept_id= '10055'") records = cursor.fetchall() pprint.pprint(records) Issue: i am able get the empid in the print statement. but coming to the query it's returning nothing(i am able to get the info by running manually on the db).
http://forums.devshed.com/python-programming-11/variables-passing-run-run-time-953083.html
CC-MAIN-2017-30
refinedweb
147
70.19
This article demonstrates how to create and use a Custom Entry control in Xamarin.Forms, XAML, and C#. Introduction This article demonstrates how to create and use a Custom Entry control in Xamarin.Forms, XAML, and C#. This article starts with the introduction of the Custom Entry tag in XAML. After that, it demonstrates how to set BorderColor, BorderWidth, CornerRadius, and IsCurvedEnabled of a Custom Entry. In the end, the article discusses how to create a button at run-time. Implementation Open Visual Studio and select a New Project. Now, select Cross Platform App, give the project a name, and set the project path. Then, click OK. Select the template as "Blank App" and code sharing as "PCL". Right-click on PCL Project and select Add >> New Item or Add >> Class. We are creating a class CustomEntry.cs and writing the following C# code. This property is set in the Android project as well as in iOS project. CustomEntry.cs Now, it's time to go to the iOS project. Again, set the PCL(CustomEntry) property in IOS Project…. We are creating a Class, so right click on iOS Project and select Apple. Then, select "Class" and give this class a name as CustomEntryRendered.cs. Now, let us write some code for Entry and Set Property. CustomEntryRenderer.cs Now, go to the PCL Project and write this code in MainPage.xaml. As you can see in the above code, we have to set the view reference in xmlns:custom="clr-namespace:CurvedEntry" MainPage.xaml. Now, you will have your Custom Entry working!! Features of CustomEntry controls View All
https://www.c-sharpcorner.com/article/xamarin-forms-custom-entry/
CC-MAIN-2021-21
refinedweb
268
69.28
Two categories of settingsGeneral and Tabsare present in all languages. Visual Studio .NET allows you to specify these settings on a per-language basis. However, if you want to use the same settings for these two categories in all languages, you can do so using the Text Editor All Languages folder. The General and Tabs categories contain settings for common editor services. However, some languages do not use all of these services. For example, the General setting lets you configure IntelliSense, but the Plain Text "language" (used for editing .txt files) cannot support this feature. In such cases, the relevant checkboxes will be grayed out. The configuration panel for the General settings presents three groups of settings: Statement Completion, Settings, and Display. Here is a summary of the General settings: IntelliSense will automatically show members of a type during code editing. IntelliSense will hide advanced members of a type. IntelliSense will automatically show parameter information for function calls. The insertion point can be placed anywhere in the editor window (whitespace padding will be inserted when necessary). Long lines of code will wrap within the text editor window. Line numbers will appear on the lefthand margin of the text editor. URLs can be followed using a single-click. A class/member navigation bar will appear at the top of the text editor window. The first group, Statement Completion, contains three IntelliSense-related settings. The first (Autolist Members) determines whether Visual Studio .NET will display a pop-up list of members in appropriate scopes. With this option enabled, a member list will automatically appear in C# and VB.NET projects if you type a variable or class name followed by a period (.). (In C++ it will appear after typing in either a period, the operator, or the :: operator, depending on the type of identifier.) The second IntelliSense-related setting is Hide Advanced Members. This determines which members will be displayed on the member list. If this is enabled, certain items will be hidden when the member list is displayed. It is up to each individual language service to decide what constitutes an "advanced" member to be hidden. VB.NET is the most interesting language since it hides the most. Consider the following class definition: Public Class TestHidden Public Sub Foo( ) End Sub Private Sub Quux( ) End Sub End Class When Hide Advanced Members is turned on, the member list (see Figure F-1) shows only the Foo member function and the GetType function, which is defined by the base type (System.Object). If Hide Advanced Members is turned off, we will also see all of the functions that are inherited from the base class, as Figure F-2 shows. Note that in both cases, only the public members are shownthe member list will show only members that are in scope. (The private member Quux would have been visible if we had tried to display the member list from inside the TestHidden class itself.) Although VB.NET makes its own decisions about which members of intrinsic types such as System.Object are advanced, we can influence its decisions with our own types. The .NET Framework Class Library defines a custom attribute called EditorBrowsable, which is defined in the System.ComponentModel namespace. We can use this to indicate that particular members of our classes are advanced. We can modify our TestHidden example to use this: Imports System.ComponentModel Public Class TestHidden <EditorBrowsable(EditorBrowsableState.Advanced)> _ Public Sub Foo( ) End Sub Private Sub Quux( ) End Sub End Class This marks the Foo method as being advanced. VB.NET will no longer display this item in member lists if the Hide Advanced Members option is selected. VB.NET and C# are the only languages that support the Hide Advanced Members settingit is grayed out for all other languages. VB.NET has it turned on by default, while in C# it is turned off by default. Even if you turn it on for C#, the behavior you get is not quite the same as for VB.NET. C# considers a member to be advanced only if it has had the relevant EditorBrowsable attribute applied, so unlike VB.NET it will not hide members of the System.Object class. Also, C# honors the EditorBrowsable attribute only on classes defined in external componentsit is ignored for classes in the same project. Hide Advanced Members can be selected even if Autolist Members is deselected. This is because even though Autolist might be turned off, the list of members of a type can still be displayed by pressing Ctrl-J or Ctrl-Space. The third IntelliSense-related setting is Parameter Information. When this option is selected, the parameter information for a particular function is automatically displayed when the function delimiter (in most cases the left parenthesis) has been typed in. The parameter information can be displayed at any time by using the Ctrl-Shift-spacebar shortcut while the cursor is inside a parameter list, regardless of whether this setting is enabled. The second group of options in the General category is under the heading Settings. It contains two settings that affect the way you see and type text. The first, Enable Virtual Space, is off by default. If you turn this setting on, you will be able to place the cursor beyond the end of the line of code you are typing on. The space between the end of the line of code and the new placement of the cursor is automatically filled in with whitespace. This is similar to Microsoft Word's click-and-type feature. The second option under Settings turns word wrap on or off. (Again, it is off by default.) When this option is enabled, any text that would appear beyond the righthand side of the text editor window is automatically placed on the next line. VS.NET does not insert line-feed characters in the text to achieve thisthis option merely changes how overly long lines are displayed. The General category's third group of options is labeled Display. (It's not entirely clear what the distinction between Settings and Display is supposed to be. Word wrap is a display feature, despite appearing in Settings, and some of the items in Display modify the editor's behavior!) The first item, Line Numbers, determines whether numbers are shown on the lefthand side of the text editor pane (between the indicator margin and the selection margin). If Enable Single-click URL Navigation is on, a single-click on a URL in the text editor will follow the URL. If disabled, you have to right-click on the URL and select Navigate to URL. (The text editor supports this behavior for any text that looks plausible as a URL, regardless of context.) The last option, Navigation Bar, determines whether a class and member navigation bar is displayed at the top of the text editor. The navigation bar is described in Chapter 2. The second category of text editor settings available in all languages is the Tabs category. Here is a summary of the Tabs settings: Controls whether and how automatic indenting is applied to source code The number of spaces between each tab stop The number of spaces inserted when you press the Tab key or when VS.NET indents your code Determines whether VS.NET will insert tab characters when it can The first setting, Indenting, controls the behavior of the editor when you press the Enter key. It can be set to None, Block, or Smart. When set to None, the text editor never indents automatically. When set to Block, the text editor indents new lines by the same amount as the preceding line. The most helpful indentation setting is Smart. This setting uses the current language service to provide context-sensitive indentation. For example, in a C# file, when you press Enter after an open brace ({), the language service tells the text editor to indent the new line by more than the preceding one. And when you type a closing brace, the editor (under the guidance of the C# Language Service) locates the line containing the corresponding opening brace and indents the closing brace by the same amount as the opening one. (It also reformats all of the code in between to fix its indentation if necessary.) The next pair of settings (which are under the Tabs heading) allows you to control tab sizes. The first value, Tab Size determines the number of spaces between tab stops when a tab character is used. (Remember that a tab character does not insert a fixed number of spaces; it merely advances to the next tab stop.) By default, tab stops are 4 characters apart. The second text box in the Tabs section of the Tabs category is Indent Size. This determines the spacing that Visual Studio .NET will use when you press the Tab key or when smart indenting decides to insert a tab in some code for you. (Again, the default is 4.) This setting is entirely independent of Tab Size. Tab Size controls how tab characters will be displayed; Indent Size controls how Visual Studio .NET will format your code. (Just because your system may be configured to display tabs as 4 characters wide, you are not required to format your code in 4-character columns.) Visual Studio .NET will not necessarily insert a tab character when you press the Tab key or when it performs automatic indentation. For one thing, you may have chosen an Indent Size that is incompatible with the Tab Size. (For example, if you like to format your code with 3-space indentation, this style does not line up very well with either 4-character or 8-character tab stops.) But when use of tab characters is an option, VS.NET will insert them if you want it to. If you choose the Insert Spaces radio button, Visual Studio .NET will never generate any tab characters. All indentation will be done entirely with spaces. This has the advantage that your files will look the same in any text editor. It has the slight disadvantage of making your files larger. The alternative is to select Keep Tabs. This will cause Visual Studio .NET to generate tab characters whenever possible. If your Indent Size setting is not an exactly multiple of your Tab Size setting, VS.NET will use tab characters when possible and fall back to spaces otherwise. For example, suppose you use 3-space indentation with 4-character tab stops. If your current indentation level is 15 columns, VS.NET will insert 3 tabs to form the first 12 columns, followed by 3 spaces to make it up to 15.
http://etutorials.org/Programming/Mastering+visual+studio+.net/Appendix+F.+Text+Editor+Settings/F.2+Generic+Settings/
CC-MAIN-2018-26
refinedweb
1,779
64.3
Introduction As part of the Big Data group, my assignment was to learn and document HANA learnings, and possible extend/find some of the uses that have not quite been documented yet. My first task was to find a way to connect with HANA from a Windows machine using an ODBC/JDBC connection. It was tricky at first to find a way to connect with ODBC, but digging into HANA online resources (corporate and community web portals) helped in the end. I also got to learn a lot about HANA technology and associated tools. HANA ODBC connection through Windows (step 1) This part was tricky because you will not find the proper driver using the regular ODBC connection wizard on Control Panel -> Administrative Tools -> Data Sources (ODBC) . The procedure is described here: . Testing the ODBC connection using HANA Command Line Interface (step 2) It is also easy to open up a HANA CLI once you have the ODBC connection installed and you have a working installation of the HANA Client on your system. All you need to do is execute: C:\Program Files (x86)\SAP\hdbclient\hdbsql.exe from the Windows Command Line; Microsoft Windows [Version 6.1.7601] C:\Users\SomeUser>cd C:\Program Files (x86)\SAP\hdbclient C:\Program Files (x86)\SAP\hdbclient>hdbsql.exe Welcome to the SAP HANA Database interactive terminal. Type: \h for help with commands \q to quit hdbsql=> You should be able to use any scripting programming language to do this part. Since we were using Python extensively in our project I did this part using Python. I used the pyodbc module which can be found here: . So if you do: import pyodbc conn = pyodbc.connect(‘DSN=<the_name_of_the_connection_you_created_in_step_1>;UID=<user_id>;PWD=<some_password>’) cursor = conn.cursor() this should create an ODBC connection, along with a cursor, the later of which can be used to execute SQL Scripts (HANA queries) and fetch the results, such as: cursor.execute(“SELECT * FROM <SCHEMA>.<TABLE> ORDER BY <FIELD>”) print cursor.fetchall() Endnote Thanks to a post by Ethan: Hi Parvez, Is there a way to cofigure the connection without goin to DSN..I have installed the HDBODBC32 driver... like the one below for HANA... DRIVER={SQL Server};SERVER=cloak;DATABASE=test;UID=user;PWD=password In the above connection striing i tried with our driver name HDBODBC32 and other required information...but it doesnt work...im getting the error "Data source name not found and no default driver specified" It works fine when i configure DSN...but it would be great if i can set it from python code... Regards, Vinoth. Hi Parvez, I got the solution, below is it, pyodbc.connect('DRIVER={%s};ServerNode=%s;DATABASE=%s;UID=%s;PWD=%s'%(driver,server,database,userid,pswd)) Regards, Vinoth. Hi what is "database" in this case? Hi, step 1 points to a death URL. What needs to be done in step 1? Unfortunately the link points to a SAP internal WIKI. This is tricky to check from within SAP network as you will always find the WIKI ... However, all you've to do is to setup a ODBC data source on your system via the ODBC Data Source Administration panel from your Windows control panel (just type odbc into the search bar). (if your Windows is 64-Bit then you should use the 64-Bit version of R and the 64-Bit version of the HANA ODBC driver. In case you use the 32-Bit version of R the 32-Bit HANA ODBC driver is required. To setup a data source for this one on a 64-Bit Windows you need to start the 32-Bit version of the Data Source Administration via program C:\Windows\SysWOW64\odbcad32.exe ) Once you are there, you simply create a system data source. The connection test can also be done from this dialogue box - simply click on "Connect" and type in the logon data. The connection test via HDBSQL however, does not check the ODBC connectivity as HDBSQL doesn't use ODBC at all. The HSQL call above actually does only open the tool and does not connect to anything... 😉 Finally, if you want to avoid creating the DSN beforehand and want to declare the connection parameters dynamically, the only way I found it to be working is by using the SERVERNODE parameter like this: conn = pyodbc.connect('driver={HDBODBC};SERVERNODE={<hostname>:<port>}', uid='<username>', pwd='<password>') For example: conn = pyodbc.connect('driver={HDBODBC};SERVERNODE={vml3012:30015}', uid='LARS', pwd='***') would connect me to my HANA toy system. Cheers, Lars I created the DSN (32-Bit) and was able to test it successfully using the dialogue box. However, when I execute a few lines of Python code similar to what is described in this blog I see no results. What could be going wrong? This is what I am trying to run: import pyodbc cnxn = pyodbc.connect('DSN=HDB;UID=******;PWD=******'') cursor = cnxn.cursor() cursor.execute("SELECT COUNT(*) from *****.******") print cursor.fetchall()
https://blogs.sap.com/2012/10/29/hana-connectivity-with-odbc-on-windows-using-python/
CC-MAIN-2021-25
refinedweb
831
56.66
Code. Collaborate. Organize. No Limits. Try it Today. In FlashPlayer, there is always this ContextMenu which never fits the design of the flash movie. ContextMenu I started making a FlashGame which has multiple clients and is always up-to-date with all other clients. This is very difficulty to manage with WebRequests and Intervals, so I decided to make my FlashGame in my C# application. The only problem was that I have a new application but with the old ContextMenu which I hate so much. So I searched for a solution on this site, but I didn't find one. Then I started searching on Google and after some dead links and unmatching code snippets, I found a .NET Visual Basic solution which is easily translated into C# and here it is. Just download the project and see how it works (if it works since it's my first article). For all those who only want to know how the code looks like, here is the core (a small core, very small core): public class IForcePlayer : AxShockwaveFlash { const int WM_RBUTTONDOWN = 0x0204; protected override void WndProc(ref Message m) { if (m.Msg == WM_RBUTTONDOWN) { m.Result = IntPtr.Zero; return; } base.WndProc(ref.
http://www.codeproject.com/Articles/29102/How-To-Disable-FlashPlayer-AxShockwaveFlash-Right-
CC-MAIN-2014-23
refinedweb
200
63.9
NAME SYNOPSIS DESCRIPTION RETURN VALUE SEE ALSO pmemblk_read(), pmemblk_write() - read or write a block from a block memory pool #include <libpmemblk.h> int pmemblk_read(PMEMblkpool *pbp, void *buf, long long blockno); int pmemblk_write(PMEMblkpool *pbp, const void *buf, long long blockno); The pmemblk_read() function reads the block with block number blockno from memory pool pbp into the buffer buf. Reading a block that has never been written by pmemblk_write() will return a block of zeroes. The pmemblk_write() function writes a block from buf to block number blockno in the memory pool pbp. The write is atomic with respect to other reads and writes. In addition, the write cannot be torn by program failure or system crash; on recovery the block is guaranteed to contain either the old data or the new data, never a mixture of both. On success, the pmemblk_read() and pmemblk_write() functions return 0. On error, they return -1 and set errno appropriately. libpmemblk(7) and The contents of this web site and the associated GitHub repositories are BSD-licensed open source.
https://pmem.io/pmdk/manpages/linux/v1.9/libpmemblk/pmemblk_read.3/
CC-MAIN-2022-05
refinedweb
174
60.85
200%-300% adsorption rate super dry desiccant,paint drying agent US $0.0001-20 / Piece 500 Kilograms (Min. Order) Sodium salt dispersing agent G-5040 for water based paint US $1.4-1.5 / Kilograms 1000 Kilograms (Min. Order) Oil Well Cement Dispersing Agent US $1953-2149 / Ton 1 Ton (Min. Order) ACP Low-temperature Foaming Agents For EVA, PE and Rubber ACP-W US $3.1-3.2 / Kilograms 1000 Kilograms (Min. Order) N-1000 TPR White Foaming Agent US $3-4.5 / Kilogram 100 Kilograms (Min. Order) Import Export Agents Wanted US $0.01-1 / Piece 1 Cubic Meter (Min. Order) Shenzhen import export sourcing agent representative agent wanted US $0.1-0.1 / Piece 1 Piece (Min. Order) Alibaba 1688 sourcing import export agents wanted Business partner US $1-108 / Piece 1 Piece (Min. Order) China dropshiping agent wanted Zhejiang yiwu public import export agent US $100-500 / Twenty-Foot Container 1 Twenty-Foot Container (Min. Order) new products and companies looking for agents in africa,import agent,import export agents wanted US $205-238 / Unit 1 Unit (Min. Order) Guangzhou General Trade Import Export Agents Wanted for Buyers US $1-50 / Cubic Meter 1 Cubic Meter (Min. Order) Responsibly China import export agents wanted service US $1-10 / Piece 1 Piece (Min. Order) 201 most Professional import export agents wanted in yiwu US $0.1-1 / Piece 10 Pieces (Min. Order) 1.5% Commission Reliable High Quality Import Export Agents Wanted US $0.1-100 / Piece 1 Piece (Min. Order) Yiwu Import Export Agents Wanted with More Years Experience,Souring/Purchasing/Buying Agent US $0.1-0.9 / Piece 1 Piece (Min. Order) yiwu import export sourcing agent representative agent wanted US $0.1-1 / Piece 1 Piece (Min. Order) specialty cargo agent import export agents wanted / Carton 1000 Cartons (Min. Order) electronic import export agents wanted US $0.1-0.2 / Bag 1 Bag (Min. Order) Hot sale import export agents wanted nap205-16 US $0.5-0.55 / Set 1 Set (Min. Order) Import export agents wanted US $0.1-1 / Piece 1 Carton (Min. Order) import export agents wanted 1 Unit (Min. Order) Best Service Shanghai purchasing and delivery agent one-stop service china import export agents wanted with great price US $4-8 / Kilogram 1 Kilogram (Min. Order) Professional China sourcing and delivery agent import export agents wanted\tnap205-16 with lowest cost US $4-8 / Kilogram 1 Kilogram (Min. Order) Hardware Yiwu agent Market sourcing agent wanted 1688 agent US $10-1000 / Set 1 Set (Min. Order) Reliable China import export agent and purchasing agent in yiwu US $0.1-1 / Piece 1 Piece (Min. Order) More than 10 years professional China buying agent, one stop export service, sourcing, shipping agent US $0.1-1 / Unit 100 Units (Min. Order) No.1 Dollar store items purchasing import and export agent in China Yiwu market with 2% low commission US $0.1-1 / Pack 1 Pack (Min. Order) Yiwu International Trade City Sourcing Agent Wanted US $5.0-10.0 / Piece 1 Piece (Min. Order) Yiwu Goods Buying Agent Professional China Business Agent Trade Shipping Agent Wanted with Low Commission US $0.01-0.02 / Piece 1 Piece (Min. Order) Professional agent wanted in yiwu market sourcing and purchasing agent service US $0.01-0.1 / Carton 1 Carton (Min. Order) China import and export agent buying agent yiwu agent wanted best price US $0.1-10 / Unit 1 Pack (Min. Order) Yiwu International Trade City Buying Agent Buying Agent US $0.5-100 / Piece 1000 Pieces (Min. Order) Yiwu Air-filled Toys Trading Agent Famous Purchase Agent US $1.56-5.69 / Piece 1 Carton (Min. Order) Sales Agents Wanted / Pack 12 Packs (Min. Order) Overseas Purchasing Agents, Help You Purchasethe Goods What You Want US $500-1000 / Twenty-Foot Container 1 Twenty-Foot Container (Min. Order) agent wanted in europe looking for agent representative US $1-5 / Piece 1 Piece (Min. Order) - About product and suppliers: Alibaba.com offers 534 import export agents wanted products. About 34% of these are general trade agents, 14% are sea freight, and 8% are freight agents. A wide variety of import export agents wanted options are available to you, such as coating auxiliary agents, plastic auxiliary agents, and petroleum additives. You can also choose from caffeinated, normal. As well as from free samples. There are 529 import export agents wanted suppliers, mainly located in Asia. The top supplying countries are China (Mainland), Turkey, and Japan, which supply 94%, 2%, and 1% of import export agents wanted respectively. Import export agents wanted products are most popular in North America, Western Europe, and Domestic Market. You can ensure product safety by selecting from certified suppliers, including 102 with Other, 53 with ISO9001, and 12 with GMP certification. Buying Request Hub Haven't found the right supplier yet ? Let matching verified suppliers find you. Get Quotation NowFREE Do you want to show import export agents wanted or other products of your own company? Display your Products FREE now!
http://www.alibaba.com/showroom/import-export-agents-wanted.html
CC-MAIN-2018-26
refinedweb
841
60.92
Timer Utility for Android We launched LenX last week and got a lot of feedback. One of them was to include a timer utility to set the exposure time. I looked up a bit and found out that the best way to do this was to use Handler and create a separate thread. Usage of the TimerUtility class: - Call a fixed method of my activity after certain time interval - Pause the timer if pause button is pressed - Resumer the timer when resume button is pressed The first part was pretty easy. Create a Runnable which invokes the method. Use a Handler to process this Runnable instance using postDelayed method and provide the time interval in milliseconds. For the second part, I looked around a bit and found out that I can remove the Runnable using ‘removeCallbacks’ method. Now, I was wondering what to do for the third part. I could simply use postDelayed again to process the Runnable, but I wanted the appropriate time interval. To overcome this, I started to save the system time when it started, paused, resumed etc and calculated elapsed time and used this elapsed time in postDelayed and processed the Runnable. TimerUtility Class public class TimerUtility { private int time_in_ms; private final Context context; private final MyActivity mAct; private Handler handler; private final Runnable runnable; private long startTime, pauseTime, elapsedTime, remainingTime, resumeTime; public TimerUtility(Context con) { context = con; mAct = (MyActivity)context; runnable = new Runnable() { @Override public void run() { mAct.onTimerStop(); } }; } public void setTime(int timeInMS) { time_in_ms = timeInMS; } public void startTimer() { startTime = System.currentTimeMillis(); resumeTime = startTime; elapsedTime = 0; remainingTime = time_in_ms; handler = new Handler(); handler.postDelayed(runnable, time_in_ms); } public void pauseTimer() { pauseTime = System.currentTimeMillis(); elapsedTime = pauseTime - resumeTime + elapsedTime; remainingTime = time_in_ms - elapsedTime; handler.removeCallbacks(runnable); } public void resumeTimer() { resumeTime = System.currentTimeMillis(); handler.postDelayed(runnable, remainingTime); } } We also added some animation with the timer, but that content is for some other post. I have added a simple working demo showing the usage of TimerUtility on GitHub. You can fork it here. P.S. So much to do with LenX. I am overwhelmed, but it’s fun! Playing around with Android UI Articles focusing on Android UI - playing around with ViewPagers, CoordinatorLayout, meaningful motions and animations, implementing difficult customized views, etc.
https://jayrambhia.com/blog/android-timer
CC-MAIN-2022-05
refinedweb
370
55.13
Introduction to Postgres List Schemas The database administrator and manager need to be aware of all the environment of the database server they are using. In the case of PostgreSQL, the server can handle data of multiple databases at a single time. The database administrator needs to know about all the databases and the tables and schema related data about the database server. In this article, we will learn how we can check and view the schema related information in PostgreSQL. We will begin with knowing what schema is in the database. In any database, all the information about the objects being managed in it is stored in the collection of the views called schema. The information schema remains stable and is portable as it is defined inside the SQL standards. However, the system catalogs are variable as they contain the specific information and are modeled after the implementation for PostgreSQL.The schema is accessible to the first user of the database and has all the privileges to handle and operate on schema including dropping it. Datatypes – Postgres List Schemas The views of information schema use a special type of datatypes which are simple domains that are generated over the built-in ones. These data types are not to be used in our outer work related to our databases. It is exclusively used by information schema view only. However, in cases where the information is fetched from information schema then you need to handle them in your application. All columns in information schema views can belong to one of the following datatypes. MetaCommands Instead of using raw SQL queries for listing the data from the database, we can use metacommands which are short and precise and can be used with the help of psql. Psql evaluates these metacommands and even translates them to SQL raw commands sometimes provided if they issued in the system tables of the server. Metacommands are recognized by a backslash and the command keyword followed by the parameters if any if you want to pass to the query. Most of the PostgreSQL servers have three default databases when they are created which are namely template0, template1, and Postgres. Template0 and template1 are the basic databases that are internally used by the command CREATE DATABASE for its usage. These two databases are called skeleton databases. The default database which is SELECTed and shown to you is the Postgres database. After that, you can create databases of your choice and switch to them to create and manipulate tables in your databases. All databases can be retrieved and listed using the metacommand \list or \l and can be switched from one to other using \connect or \c. We can list out all the tables using the metacommand \dt command. How to Use Postgres List Schemas? Now, we will see how we can list databases using the psql command.\list or \l can be used. Open your PostgreSQL command prompt and then type SQL to get its command prompt. No type \list and press enter. These are the output that you will see “Three default databases of PostgreSQL”. Code: sudo su - postgres psql Output: Let us create one new database named demo by using createdb command. Exit the psql by typing \q and then just type createdb demo and press enter. Then again enter \list and press enter to list out all the databases after typing psql to get the command prompt of psql. The output will be as follows – Code: \q createdb demo psql \list Output: Schemas In any PostgreSQL database, there are three types of schemas present in it which are information schemas, temporary schemas and default pg_* schemas. Other than the user-defined and public schemas, one more type of schema present in PostgreSQL is the pg_catalog schema. This schema contains the information about and the system tables, operators, data types and functions present in the current database. To list out all the user-related schemas, we will create a query to retrieve from pg_catalog schema. Code: SELECT * FROM pg_catalog.pg_namespace; Output: The field nspname displays the names of the schemas. These are all the schemas present in our database right now. The npsowner field stores the user id which owns that schema. We can see that all schemas are owned by the user with id 10. To get the information about the user with id 10 we can query on pg_user table. Code: SELECT * FROM pg_catalog.pg_user where usesysid = 10; Output: Now we can say that user with usesysid =10 is postgres which owns all the above-retrieved schemas. Now, if we want to retrieve name os schema and the person owning it in a single output then can create a join on pg_namespace and pg_user as shown below. Code: SELECT s.nspname AS table_schema, u.usename AS OWNER FROM pg_catalog.pg_namespace s JOIN pg_catalog.pg_user u ON u.usesysid = s.nspowner ORDER BY table_schema; Output: Conclusion PostgreSQL databases provide us with metacommands that are compact and immensely useful for database administrators and managers to check the database environments and structure related information in a faster and effective manner during their daily routines. Schemas can be retrieved from the system tables of pg_catalog schema which is present in PostgreSQL databases. pg_namespace and pg_user are two main tables that convey schema related information to us. Recommended Articles This is a guide to Postgres List Schemas. Here we discuss an introduction to Postgres List Schemas, with appropriate syntax, command and examples. You can also go through our other related articles to learn more –
https://www.educba.com/postgres-list-schemas/?source=leftnav
CC-MAIN-2020-50
refinedweb
925
63.7
Mechanical Engineering Archive: Questions from January 27, 2013 - Part A) Determination of internal axial loads The axially loaded bar is fixed atAand loaded as shown. Draw a free-body diagram and determine the support reaction atA. On paper, draw a free-body diag2 answers - A Mass of 350 kg is lifted by 2 cables connecting at the same point as shown: a) determine the tensions on each cable when the system is in equilibrium b) Use the polygon of forces to show that the sy9 answers - A Crate containing 40 bricks, each of mass 1.3kg, is placed on a storage framework as shown. A) Calculate the reaction force in each of supports A and B B) Calculate the moment of the force exerted by4 answers Draw the circuit on your solutions and use whatever meihod you wish lo solve for vx. but make sure the steps of the method are clearly shown. Take vs to be a 9 V battery. Also, if the battery is rated1 answer - I just need help finding the power and the power balance Draw the circuit on your solution with vs = 24 V. Use the voltage division concept plus equivalent resistance concepts to find the voltage vo across the pair of 12 Ohm resistors. Also find the power g2 answers - Derive the specific gravity equation (Equation 1) and include the derivation in the report appendix. Be sure to refer to the derivation in the body of the main text. The derivation is to be complete a3 answers - 3 answers - The velocity of a particle moving in the x-y plane is given by 6.12i + 3.24j m/s at time t=3.65s. Its average acceleration during the next 0.02s is 4i+6j m/s^2. Determine the velocity v of the particl6 answers - The pilot of an airplane carrying a package of mail to a remote outpost wishes to release the package at the right moment to hit the recovery location A. What angle ? with the horizontal should the pi7 answers - Specific gravity : W/(W?w). W is the weight of the substance in air, w is the weight of the substance suspended in water. how do i derive the specific gravity equation. i do not understand the other4 answers - The winding drum D is drawing in the cable at an accelerated rate of 5m/s^2. Determine the cable tension if the suspended crate has a mass of 800 kg.4 answers - For the compound gear train shown in Figure 1, determine the pitch diameters d2, d3 and d4 to achieve a velocity ratio of 0.25 and the distance between output shafts is l = 2in. The pinion gear has al2 answers Figure P10. 54 indicates various defects and discontinuities in cast products. Review each defect and offer solutions to avoid it. FIGURE P10. 543 answers - Mega Man throws a rock at Giga Goliath with a sling of radius R = 3.0 ft. Starting from rest, he whirls it in the x?y plane around the z axis one revolution plus 236.0 degrees more and then releases i2 answers - A room is heated by an iron that is left plugged in. Is this a heat or work interaction ? Take the entire room, including the iron, as the system. A room is heated as a result of solar radiation co2 answers - Race car A is traveling on a straight portion of the track while race car B is traveling on a circular portion of the track. At the instant shown, the speed of A is increasing at the rate of 10m/s^2,2 answers - To study the performance of a race car, a high speed camera is positioned at point A. The camera is mounted on a mechanism which permits it to record the motion of the car as the car travels on a stra2 answers - aluminum pipe The aluminum pipe shown below is used to support a load of 150 kip. Determine the maximum displacement at the top of the pipe if the load is: (a) applied gradually and (b) applied suddenly by releasin1 answer - Is the average run length performance of a control chart a more meaningful measure of performance than the type I and type II error probabilities? What information does ARL convey that the statistica2 answers - 5 answers - Just answer part c & d. Please Figure P10. 54 indicates various defects and discontinuities in cast products. Review each defect and offer solutions to avoid it. FIGURE P10. 541 answer Assume that the top of round sprue has a diameter of 3 inch and is at a height of 6 inch from the runner. Based on Eq. (10. 5), plot the profile of the sprue diameter as a function of its height. Assu1 answer A beam with rectangular cross section is subjected to the load shown in the picture, F = 5 kips, E = 1. 75 times 103 ksi, Izz = 2. 25 in4. Determine: The reactions at A and C. The flexural and shear1 answer The pictured section of a gas pipeline is rigidly fixed at A and is subjected to a 9 kN load in the -y direction at C. The outer diameter of the pipe is 200 mm and the inner diameter is 176 mm. Determ1 answer Suppose that the stress field in an elastic body is given by: sigma ij = Find the body force distribution required to maintain equilibrium. Determine the principal stress at the point (x1, x2, x3) =1 answer The shaft shown below is made from a steel tube (with outer diameter d0 = 1 in) which is bonded to a brass core (with outer diameter di = 0. 5 in). If a torque of 250 lb-ft is applied at its end and b1 answer A 12 ft long, A-36 steel W 8 times 31 member is to be used as a pin connected column. Determine the largest axial load it can support before it either begins to buckle or the steel yields. Note: E = 21 answer - how is the sketch tab and associated commands different from the feature tab and associated commands4 answers - I need a solution for the following Thermodynamic problem! Thank you Refrigerant-410a in a piston/cylinder arrangement is initially at 15?C with x=1. It is then expanded in a process so that P=C/v to1 answer - With a beam, such as a laser of optical power P(opt), incident on the receiver, its temperature T(s), increases above that of the chamber walls held at a uniform temperature, T(surr)=77 K. With the o1 answer - The 2- collar is free to slide along the smooth shaft. Determine the acceleration of collar if collar is subjected to an upward acceleration of 3.4 .0 answers - A particle moves along a curve as shown in the figure. Its distance in meters from along the curve from the x-axis is given by s = t^2/6 where t is in seconds. The particle is at A when t = 2.0 and at4 answers A piston cyfinder system containing 0. 5kg of air is compressed from a volume of 0. 35 m3 to a volume of 0. 1 m3. If the initial pressure was 150 kPa and the process can be modeled as a polytropic pro2 answers Using a specific heat ratio of 1. 4, calculate cp and cv of air assuming ideal gas with constant specific heats. Compare these values to the values in Table A-8 in your textbook. At about what tempera1 answer Calculate the change in specific internal energy and enthalpy for a process starting at 300 K and ending at 500 K. Assume that air is behaving as an ideal gas with constant specific heats and use the1 answer - In an experiment to measure the drag coefficient of oil, an object is dropped from rest at time t = 0 in the vertical plane. It falls through a height h before entering a tank of oil as shown in the f1 answer The atmosphere on Maris is comprised of mostly carbon dioxide at a pressure of 600 Pa (that is not a mistake, it is in Pa). The earth's average atmospheric pressure, on the other hand, is about 101. 33 answers - Hello. Two of the books I got from Chegg ended up being the wrong books, so I returned them within the 21 day period. I shipped them out on Wednesday of last week and tomorrow is the last day where I1 answer If one were to make a sculpture of a pencil and fix it (cantilevered) to a metal plate in the ground, it would be necessary to ensure that the central core was made of steel rod. It would also be nece0 answers If the cross sectional area, A = K(5L-3x), where K is constant, determine the elongation of the bar in terms of the constant applied load, P, the length, L, the modulus, E, and the constant, K.1 answer For a given stress field with components written on a fixed othonormal basis, Find the traction, t, acting on a surface with unit normal n = (E1+E2)/ 2. Determine the principal stresses. Determine th0 answers Determine the forces in members RQ, RH, GH, and QP if the truss has a pin joint at N and a roller joint at K. If each link in the truss is made of aluminium (E = 70 GPa) tube (O. D. = 4cm, thickness =0 answers A thin walled cyfindical pressure vessel experienced an internal gas presssure, p. It was simultaneously compressed by an axial force, P = 10kip. What is the maximum pressure that can be generated if0 answers A steel shaft (G = 75 GPa) is subjected to the torques shown below. Determine the maximum torsional shearing stress in the shaft. Calculate the rotation of section A.1 answer - Here is the question statement: If the magnitude of the resultant force is 1300 {\rm N} and acts along the axis of the strut, directed from point A towards O, determine the magnitude of the force acti1 answer - Can two vectors of unequal magnitude add up to give the zero vector? Can three unequal vectors? Under what conditions?4 answers - If you are riding on a train that speeds past another train moving in the same direction on an adjacent track, it appears that the other train is moving backward. Why?2 answers - In archery, should the arrow be aimed directly at the target? How should your angle of aim depend on the distance to the target?2 answers The polyviny chloride bar is subjected to an axial force of 900 lb. If it has the original dimensions shown, determine the changein the angle theta after the load is applied. Epvc = 800 ksi, Vpvc = 0.0 answers - The smooth block B of negligible size has a mass m and rests on the horizontal plane. If the board pushes on the block ac at an angle theta with a constant acceleration a(o) , determine the velocity o0 answers - The smooth block B of negligible size has a mass m and rests on the horizontal plane. If the board pushes on the block ac at an angle theta with a constant acceleration a(o) , determine the velocity o1 answer - A car is to be hoisted by elevator to the third floor of a parking garage, which is 36 above the ground.1 answer - Steam at a rate of 5 lbm/s enters an adiabatic turbine at 800 Psia, 1000 F and leaves at an actual condition of 10 Psia, 320 F. Calculate: a) The power out of the turbine, b) The isentropic efficiency1 answer - A 1 m3 tank containing air at 25oC and 500 kPa is connected through a valve to another tank containing 5 kg of air at 35oC and 200 kPa. Now the valve is opened, and the entire system is allowed to rea3 answers - Ethanol blended with gasoline can be used to power a 'flex-fueled"car. One particular blend that is gaining in popularity is E85, which is 85% ethanol and 15% gasoline. E85 is 80% cleaner burning than0 answers A control chart for the number of nonconforming piston rings is maintained on a forging process with np = 16. 0. A sample of size 100 is taken each day and analyzed. What is the probability that a shi0 answers - Calculate the radius of an silver atom in cm, given that Ag has an FCC crystal structure, a density of 10.5 g/cm3, and an atomic weight of 107.87 g/mol. Can someone please show work and detail kuz0 answers - Imagine that you are working for a company that designs and manufactures writing implements. As part of a new literacy outreach program, your company will be sending mechanical pencils to remote jungl1 answer - The two blocks shown are originally at rest. Neglecting the masses of the pulleys and the effect of friction in the pulleys and between block A and the incline, determine (a) the acceleration of each1 answer - 1 answer - Three arbitrary points are commonly used to find one of the planes in a flatness tolerance zone. T or F1 answer - 2 answers - 4 answers - A flow field may be represented by the velocity components: u=(6x+y2 +z+t)i v = 4z j w = 2z k in units of m/s. At the point (1 m,1 m, 1m) and time = 1 second a) what is the magnitude of the velocit0 answers - Circularity is commonly used on cylindrical part features in applications involving sealing. T or F <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /?>4 answers - When a cylindricity control is used, its tolerance value must be less than the size tolerance. T or F4 answers - The concrete slab of a basement is 11 m long, 8 m wide, and 0.20m thick. during the winter, temperatures are nominally 17 C and 10 C at the top and bottom surfaces respectively. if the concrete has a1 answer - 1 answer - 3 answers - A barrel starts empty, it has a hole in the bottom where the mass flow rate is a function of L (the height of the water) times a constant k. (m2=kL) there is a hose going into the top of the barell, w1 answer - Some hypothetical metal has the simple cubic crystal structure (i.e., atoms positioned at each of the eight corners with atoms touching one another along cube edges). Calculate its atomic weight if it0 answers - With the blocks initially at rest, the force P is increased slowly from zero to 60 lb. Plot the accelerations of both masses as functions of P. image answers - Ethanol blended with gasoline can be used to power a "flex-fueled" car. one particular blend that is gaining in popularity is E85, which is 85% ethanol and 15% gasoline. E85 is 80% cleaner burning tha1 answer - The brakes of a car are applied, causing it to slow down at a rate of 10 ft/s2. Knowing that the car stops in 300 ft, determine (a) how fast the car was traveling immediately before the brakes were1 answer - F1 = 600 N F2 = 900 N Angle 1: 45 degrees (between the two forces) Angle 2: 30 degrees (The angle between the 900 N force and the x-axis)1 answer - F1 = 600 N F2 = 900 N Angle 1: 45 degrees (between the two forces) Angle 2: 30 degrees (The angle between the 900 N force and the x-axis) Find the magnitude and direction.2 answers - The acceleration of a particle is defined by the relation a 5 kt2. (a) Knowing that v 5 28 m/s when t 5 0 and that v 5 18 m/s when t 5 2 s, determine the constant k. (b) Write the equations of moti1 answer - Based on observations, the speed of a jogger can be approximated Problems 617 by the relation v 5 7.5(1 2 0.04x)0.3, where v and x are expressed in mi/h and miles, respectively. Knowing that x 5 0 a1 answer - A nuclear power plant produces 1.2 GW of electric power at a system efficiency of 20%. The plant rejects heat into a river, and it leaves the plant at a relatively warm temperature of 801 answer - In a boat race, boat A is leading boat B by 50 m and both boats are traveling at a constant speed of 180 km/h. At t 5 0, the boats accelerate at constant rates. Knowing that when B passes A, t 5 8 s1 answer - Slider block B moves to the right with a constant velocity of 300 mm/s. Determine (a) the velocity of slider block A, (b) the velocity of portion C of the cable, (c) the velocity of portion D of the c1 answer - 1 answer - 1 answer - 1 answer - 1 answer - 1 answer - 1 answer - A refrigeration system uses R-410a as the refrigerant. The system is evacuated, then charged with refrigerant at a constant temperature of 5?C. The system volume is at 0.015 m3. Determine (a) the pres1 answer - What is the typical rotational frequency "f_not" for a molecule like "N_2" at room temperature (25 C)? --- Assume that "d" for this molecule is " 2 A = 2 *10^-10 ". Take the atomic mass of "N_2" to b1 answer - A system consists of nitrogen (N2) in a piston-cylinder assembly, initially at p1 = 20 lbf/in^2 , and occupying a volume of 2.5 ft^3. The nitrogen is compressed to p2 = 100 lbf/in^2 and a final volume1 answer - Two structural members B and C are bolted to the bracket A. Knowing that the tension in member B is 6kN and that the tension in C is 10 kN, determine graphically the magnitude and direction of the res1 answer - The force F of magnitude 800 N is to be resolved into two components along the lines a-a and b-b. Determine by trigonometry the angle alpha, knowing that the component of F along line b-b is 120 N.1 answer - The acceleration of a particle is defined by the relation a 5 kt^2. (a) Knowing that v=-8 m/s when t=0 and that v=+8 m/s when t=2s, determine the constant k. (b) Write the equations of motion, knowing1 answer - 1...A Frenkel defect involves which of the following? A)A cation interstitial B)A cation vacancy C)An anion interstitial D)An anion vacancy 2...Impurity atoms in ceramic materials may form subst1 answer - A temperature scale is defined by the equation ts/ti = lim pi-0 (ps/pi)=1.36609 as in gas thermomery , but now the reaumur scale is adopted by using the additional relation ts-ti = 80. note subscripts1 answer - 1 answer - Determine the volume, in ft3, occupied by 2 lbm of water at a pressure of 1000 psi and (a) A temperature of 600�F (b) A quality of 80% (c) A temperature of 200�F1 answer - Determine the volume, in ft3, occupied by 2 lbm of water at a pressure of 1000 psi and (a) A temperature of 600�F (b) A quality of 80% (c) A temperature of 200�F0 answers - The acceleration of a particle is defined by the relation a=kt^2. (a) Knowing that v=-8 m/s when t=0 and that v=+8 m/s when t=2s, determine the constant k. (b) Write the equations of motion, knowing a2 answers - A disabled automobile is pulled by means of two ropes. Knowing that the tension in rope AB is 750 Ib, determine by trigonometry the tension in rope AC and the value of alpha so that the resultant forc1 answer
https://www.chegg.com/homework-help/questions-and-answers/mechanical-engineering-archive-2013-january-27
CC-MAIN-2018-26
refinedweb
3,306
67.38
Cheap interpreter, part 1: overview A few months ago, my former boss Neil Mitchell gave a talk entitled "Cheaply Writing a Fast Interpreter". It's a very good talk, and I encourage you to watch it. The basic premise of the talk is that it is given to people who already know many ways to write an interpreter, and the talk itself is presenting the results of a study Neil and his team did to compare a number of different techniques on their performance per cost ratio, where cost is meant in terms of development and maintenance. The results presented should be of great interest to anyone planning to write an interpreter for some practical purpose. I don't plan to write any real interpreter. What made the talk really interesting to me is that I did not know any of the techniques Neil presented, so to me the talk served as a great roadmap of things to go play with. And then write about, of course. This is the first in a series of posts about what I learned. Parts of an interpreter An interpreter is a program that takes in text that forms a valid program in some programming language and executes it according to the semantics of said language. Where the text comes from is not terribly important. Starting with the point where we have some text, the major parts of an interpreter are: - The parser is a function that takes in some "flat" text and produces some form of structured tree. - The optimizer takes in the tree produced by the parser, and transforms it into another tree. There may be any number of intermediate passes over any number of intermediate trees. - The evaluator reads in a tree emitted by the optimizer and actually does stuff as instructed by the input program. Naming is not very consistent across sources I've come across. "Parsing" as a transformation of text to tree is by far the most widely accepted term I've found. Coming in second would be "abstract syntax tree", in that any piece about interpreters will mention the words, though they're not always in agreement on what they mean. As mentioned, there can be any number of different trees in-between the textual representation and the one that eventually gets evaluated, and which one of these trees is the abstract syntax tree is fairly inconsistent. Finally, in some cases the evaluator can modify the tree it is evaluating. This happens in broadly two cases: - If the language being evaluated is dynamic, it will have operations to modify its own tree at runtime. - The evaluator may modify the tree for optimization purposes. This can be called an optimizing evaluator, or a JIT (standing for "just-in-time compiler", because it's fun to make acronyms that don't cover all the words). There are complex interplays between these things; for example, if you have a JIT, or a dynamic language, the role of the optimizer is a bit less clear. How much optimization should you do at compile time if you also have the opportunity to optimize at runtime? If you have a dynamic language, do you optimize the code you start with? What about the code you add at runtime? How do you balance the cost of running unoptimized code with the cost of running the optimizer at runtime? Other questions can crop up, such as how much of the program the optimizer considers. Considering the whole program at once can give the optimizer a better understanding of the program and therefore find better optimizations, but it does not play well with adding code at runtime. It's also a bit impractical as it means any change requires recompiling everything, which can get slow. Compilers Mathematically, a compiler is any program that transforms programs written in language \(A\) into equivalent programs written in language \(B\). Compilers don't require computers at all; the concept can be (and has been) defined purely in terms of Turing machines. There is no restriction that \(B\) must be different from \(A\), or that \(B\) must be a specific language. Still, when hearing "compiler", many programmers will think of a program that generates machine code. In a way, this is just a special case of an interpreter, where the evaluator is the CPU and the interpreter lets us serialize the result of the optimizer to disk rather than running it directly. In a more general sense, compilers will look a lot like interpreters, in that there will be a parser that produces some tree, and then a series of steps that transform a series of trees. The evaluation part is replaced by the emission of a "flat" file that represents code in the target language. Parsing I will not delve into much details on the parsing side in this series, because this exploration was mostly about what happens after parsing. Still, I can give a few pointers. In order to parse a language, one first needs to define a grammar for it, i.e. define how to form correct sentences in that language and what these sentences mean. There may be many ways to do that, but, by and large, the world has settled on something called EBNF to describe useful programming languages. A grammar described in EBNF takes the form of a succession of rules, each of the form: name = production where production is either a literal (or, as a shorthand, a collection of literals in the form of a regular expression) or a combination of literals and other rules. For example, a simple grammar for arithmetic on integers could be described by: expr = term ('+' expr)? term = factor ('*' term)? factor = '(' expr ')' | nat nat = #"\d+" where nat represents natural numbers through a regular expression, '+', '*', '(' and ')' are literal characters, (unquoted) parentheses represent grouping, question mark reprents optionality and | represents disjunction. On the following expression: 4+5*6, this grammar would produce a parse tree along the lines of (using Clojure syntax for trees): [:expr [:term [:factor [:nat "4"]]] "+" [:expr [:term [:factor [:nat "5"]] "*" [:term [:factor [:nat "6"]]]]]] Going from an EBNF grammar to a program that can turn text into parse trees is not exactly trivial, but not very hard either. Different languages have different tools for that, but the one thing they all have in common is that you're expected to have a well-defined EBNF grammar before your start writing out your code. It's probably important to mention that EBNF is not a single agreed-upon syntax for decribing grammars, but a loose set of things that people generally agree on in general. It's more like CSV than JSON. Every tool that reads "EBNF" will read a slightly different flavour of it. Parser generators In ye olden times, the grandparents of parsing technology were the tools known as lex and yacc (and later flex and bison), which are based on domain-specific languages and some notion of separating parsing (forming sentences out of words) from lexing (identifying individual words). The main parsing technology for Java, JavaCC, is a direct descendant and is based on the same ideas. The core principle seemed to be to annotate the EBNF grammar directly with snippets of code, which after a couple decades people realized is a really bad idea because it introduces way too much coupling. More recent approaches tend to have a better separation between producing a parse tree and acting on it, which gives the option of producing a tree once and then having many different uses for it. In the Java world, ANTLR is probably the most-widely used of those. Wheres JavaCC (and yacc and bison before it) require the programmer to write a mix of Java (or C) and EBNF to execute code as the parse progresses, ANTLR takes in what is essentially "just" an EBNF grammar and generates both Java "data" classes to represent the parse tree and Java code to turn a string into said tree. In Clojure, the wonderful instaparse library can directly turn an EBNF grammar into a parse tree; that is, in fact, what I used to produce the tree above: t.core=> (def gram #_=> "expr = term ('+' expr)? #_=> term = factor ('*' term)? #_=> factor = '(' expr ')' | nat #_=> nat = #'\\d+'") #'t.core/gram t.core=> ((insta/parser gram) "4+5*6") [:expr [:term [:factor [:nat "4"]]] "+" [:expr [:term [:factor [:nat "5"]] "*" [:term [:factor [:nat "6"]]]]]] t.core=> Because the language is dynamic and has good builtin default vectors and keywords, there is no code generation required. This is by far the easiest way I know of to get started with writing a parser. Parser combinators From the "purely functional" side comes a different way to approach writing a parser known as "parser combinators". This is essentially a monad-based DSL for parsing, where monadic sequencing is lexical sequencing. Using Haskell notation, it can start with something like: newtype Parser tree = Parser (String -> Maybe (tree, String)) instance Functor Parser where fmap = liftM instance Applicative Parser where pure = return; (<*>) = ap instance Monad Parser where return v = Parser (\s -> Just (v, s)) p >>= f = Parser (\s -> case parse p s of Nothing -> Nothing Just (v, out) -> parse (f v) out) item :: Parser Char item = Parser (\s -> case s of [] -> Nothing (x:xs) -> Just (x, xs)) failure :: Parser a failure = Parser (\s -> Nothing) and then, one can fairly easily build on top of that. For example, a parser that reads three characters and discards the one in the middle could be written as: p_1 :: Parser (Char, Char) p_1 = do x <- item item y <- item return (x, y) These are calld combinators because one can create new parsers by combining existing ones, either among themselves or with existing functions. For example, creating a parser for a sequence of numeric characters can be done with: -- combinator that satisfies a boolean on a character sat :: (Char -> Bool) -> Parser Char sat p = do x <- item if p x then return x else failure -- parser for a single digit digit :: Parser Char digit = sat isDigit -- combinator that takes two parsers and matches the second if the first fails (+++) :: Parser a -> Parser a -> Parser a p +++ q = Parser (\s -> case parse p s of Nothing -> parse q s success -> success) -- combinators that repeat any number of times many :: Parser a -> Parser [a] many p = many1 p +++ return [] many1 :: Parser a -> Parser [a] many1 p = do v <- p vs <- many p return (v:vs) -- Parser for a natural number integer :: Parser Integer integer = do xs <- many1 digit return (read xs) Parser combinators do not require a separate EBNF grammar. It is possible to define the operators in such a way that the grammar, expressed as combinators, reads almost as easily as an EBNF description (adapted for the host programming language, of course). Still, it is sometimes easier to reason about the grammar on paper in EBNF and then use that to guide the code. This approach is most popular in the Haskell and Scala communities, but parser combinator libraries exist in many other languages. What makes grammars hard Writing a grammar can be quite tricky, because one has to come up with rules that are not ambiguous. That is, ideally, one would like that, for any given input, there is either zero or one parse tree, but never more. It is very easy to write "ambiguous" grammars, i.e. ones that can sometimes generate more than one valid parse tree. Another issue is non-termination. This is, in some sense, not different from any recursive code, but it's very easy to end up with a recursive grammar that does not terminate. Take the simple arithmetics grammar, for example. It could have been tempting to just go for something like: expr = expr (('+' | '*') expr)? and that might seem mathematically correct, but a naive derivation would yield a non-terminting program, and this grammar could generate multiple parse trees. It's also not respecting the operator priority between + and *. Both of these issues are somewhat fundamental to the expressive power of grammars. But while they are both properties of the grammar, what's more interesting is to think of them as properties of the language. As the arithmetics example shows, there may be languages for which there are multiple ways to express the grammar, some of which have non-termination issues and some of which don't. A lot has been written about how to design languages and the associated grammars such that they do not end up having non-termination or ambiguity problems, but that is way outside the scope of this blog entry. Languages as trees There is a fairly simple answer, though, which in my eyes make grammars a fairly uninteresting subject. Let's consider the following points: - The goal of a grammar is to turn text into trees. - The meaning of the program depends on the generated tree. Programmers care about the meaning of the program, and the harder it is to infer the tree from the text, the harder it is to understand the code. - The harder it is to infer the tree from the program, the more complicated the grammar will be, and the harder it will be to get right. It follows that the grammar that requires the least effort to understand for users of the language is also the one that requires the least effort to implement, and it is one that has a direct mapping to a tree. In other words, it is a textual representation of a tree. The oldest way to do that is the original Lisp syntax. This is in fact how the Lisp syntax was invented: at the time, they wanted to experiment with language semantics, not with syntax. They did have a ("non-Lisp") syntax defined, and they were planning to implement a proper parser, but given limited resources (both in implementation effort and in runtime cost) they chose to temporarily go for a direct representation of the parse tree using parentheses. They then discovered that this was actually quite a nice way to work and never got around to adding the "real" parser. Parentheses got a bit religious in the Lisp community, but they're really beside the point. What matters is that there is a direct, easy-to-see, unambiguous correspondence between the code and the underlying parse tree. Clojure improved on the old model by realizing that and adding other types of delimiters to "de-overload" the meaning of parentheses. Elixir decided to eschew parentheses in favour of do/end. Parentheses are not the point; direct tree representation is. As the most effective syntax is also the easiest one to parse, I find it really hard to get interested in how to write more complicated parsers for less effective syntaxes. Why make it harder for both the language implementor and the language user? From the next post onward, I will completely ignore parsing and just assume I have a parse tree.
https://cuddly-octo-palm-tree.com/posts/2021-06-19-cwafi-1/
CC-MAIN-2022-40
refinedweb
2,495
56.29
Man Page Manual Section... (1) - page: urlgrabber NAMEurlgrabber - a high-level cross-protocol url-grabber. SYNOPSISurlgrabber [OPTIONS] URL [FILE] DESCRIPTIONurlgrabber is a binary program and python module for fetching files. It is designed to be used in programs that need common (but not necessarily simple) url-fetching features. OPTIONS --help, -h - help page specifying available options to the binary program. --copy-local - ignored except for file:// urls, in which case it specifies whether urlgrab should still make a copy of the file, or simply point to the existing copy. --throttle=NUMBER - if it's an int, it's the bytes/second throttle limit. If it's a float, it is first multiplied by bandwidth. If throttle == 0, throttling is disabled. If None, the module-level default (which can be set with set_throttle) is used. --bandwidth=NUMBER - the nominal max bandwidth in bytes/second. If throttle is a float and bandwidth == 0, throttling is disabled. If None, the module-level default (which can be set with set_bandwidth) is used. --range=RANGE - a tuple of the form first_byte,last_byte describing a byte range to retrieve. Either or both of the values may be specified. If first_byte is None, byte offset 0 is assumed. If last_byte is None, the last byte available is assumed. Note that both first and last_byte values are inclusive so a range of (10,11) would return the 10th and 11th bytes of the resource. --user-agent=STR - the user-agent string provide if the url is HTTP. --retry=NUMBER - the number of times to retry the grab before bailing. If this is zero, it will retry forever. This was intentional... really, it was :). If this value is not supplied or is supplied but is None retrying does not occur. --retrycodes - a sequence of errorcodes (values of e.errno) for which it should retry. See the doc on URLGrabError for more details on this. retrycodes defaults to -1,2,4,5,6,7 if not specified explicitly. MODULE USE EXAMPLESIn its simplest form, urlgrabber can be a replacement for urllib2's open, or even python's file if you're just reading: from urlgrabber import urlopen fo = urlopen(url) data = fo.read() fo.close() from urlgrabber import urlopen local_filename = urlgrab(url) # grab a local copy of the file data = urlread(url) # just read the data into a string * it's a little ugly to modify the default grabber because you have to reach into the module to do it * you could run into conflicts if different parts of the code modify the default grabber and therefore expect different behavior from urlgrabber.grabber import URLGrabber g = URLGrabber() data = g.urlread(url) from urlgrabber.grabber import URLGrabber g = URLGrabber(reget='simple') local_filename = g.urlgrab(url) from urlgrabber.grabber import URLGrabber g = URLGrabber(reget='simple') local_filename = g.urlgrab(url, filename=None, reget=None) AUTHORSWritten by: Michael D. Stenner <mstenner@linux.duke.edu> Ryan Tomayko <rtomayko@naeblis.cx> This manual page was written by Kevin Coyner <kevin@rustybear.com> for the Debian system (but may be used by others). It borrows heavily on the documentation included in the urlgrabber module. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU General Public License, Version 2 any later version published by the Free Software Foundation. RESOURCESMain web site: Index This document was created by man2html, using the manual pages. Time: 15:26:21 GMT, June 11, 2010
https://linux.co.uk/documentation/man-pages/general-commands-1/man-page/?section=1&page=urlgrabber
CC-MAIN-2018-39
refinedweb
570
59.5
This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project. On Mon, Mar 22, 2004 at 09:56:00AM +0100, Falk Hueffner wrote: > Alexandre Oliva <aoliva@redhat.com> writes: > > > On Mar 21, 2004, Roger Sayle <roger@eyesopen.com> wrote: > > > >> On 21 Mar 2004, Alexandre Oliva wrote: > >> +#define REAL_EXP(REAL) \ > >> + ((int)((REAL)->uexp ^ (unsigned int)(1 << (EXP_BITS - 1))) \ > >> + - (1 << (EXP_BITS - 1))) > > > >> I hadn't come across this "(x ^ signbit) - signbit" idiom for > >> implementing sign-extension before. Nice. > > > > Yeah, I found it great as well when I learned about it in the binutils > > list :-) > > > > Maybe the middle-end could recognize such sequences and attempt to > > optimize them into shifts or other forms of sign extension? Maybe > > it already does? :-) Dunno, I haven't checked. > > I don't really like the idiom. It's obfuscated and requires a large > constant, which is costly on some targets. Plain old > (x << EXP_BITS) >> EXP_BITS is much more readable and already gets > recognized by gcc as sign extension. That old familiar shift left, shift right might not work at all. Even if you know the number of bits in x. According to ISO/IEC 9899:1999, shift right of negative signed quantities is implementation defined. $ cat /tmp/sign.c int foo (int x) { return ((x & 0xff) ^ 0x80) - 0x80; } $ gcc -S -O2 -fomit-frame-pointer /tmp/sign.c $ cat sign.s .file "sign.c" .text .p2align 4,,15 .globl foo .type foo, @function foo: movsbl 4(%esp),%eax ret .size foo, .-foo .ident "GCC: (GNU) 3.3 20030226 (prerelease) (SuSE Linux)" -- Alan Modra IBM OzLabs - Linux Technology Centre
https://gcc.gnu.org/ml/gcc-patches/2004-03/msg01833.html
CC-MAIN-2019-39
refinedweb
268
67.45
Old /dpt/ at >>51557857 What are you working on? memifying memelangs. >>51562843 D >OO "Programming" Probably going to start memeing on my image shit again. That said, I just got back from shooting some clay pigeons and that was entertaining. >>51562046 >In Java Swing, what's the best way to lay out a GUI like this? >Like I want some components on one side, and another on the other side. >I had originally done a GridLayout to split the panel then a LEFT FlowLayout and a RIGHT FlowLayout, but if one side has more components then the other it starts to look weird really fast. >>51562896 I thought americans only did school shootings. Nice image OP. OO paradigm is just closures >>51562893 Who are you quoting? >>51562935 Jesus >>51562915 Well, we have probably 400 million guns, so we have to do something with them in-between the high profile shootings. >>51562965 Jesus would program in a functional language Prove me wrong protip: you can't >>51562843 Benchmarking DMA transfer between two GPUs across a NTB link. >>515628431562914 The best way to use Java Swing is by not using Java Swing. >>51562914 Use JavaFX family >>51563194 The best way to use Java.Swing is by not using Java >>51562893 NEET detected >>51562914 Without you illustrating your desired result I can't really tell you anything. You currently (in the picture) have three button like things which could be placed using absolute coordinates. If you want to place them relative to the window size use a GridLayout. But I suggest you play around with the different layouts and get a feel for what they actually are, or read about them more. Then you can make the decision. But if you want someone else to tell you offer a better description. Like throw out 4 different examples of desired situations. >>51563016 jesus was pragmatic, not a time waster which is more programming related, CS or SE? >>51563016 >a functional language In other words not an FP language because FP languages don't function >>51563428 SE >>51563327 which is exactly why he'd use FP >there is one part of program that is full of bugs >impossible to debug unless you know the runes it is written in >the person working on it is lazy well, I hate my job. also boost sucks >>51563469 Nigga probably wrote it that way on purpose. >>51563265 I want the behavior of FlowLayout, but want one set of components to left-justified and the other set to be right-justified. Basically, the components on the left will be "glued" to the left and their position will be relative to the left border (just like a FlowLayout(LEFT)); the components on the right will be "glued" the right and their position will be relative to the right border (like FlowLayout(RIGHT)). Resizing the panel will increase/decrease the spacing between the two sets of components. >>51563469 It's called job security, do you want to be an unemployed poorfag? >>51563450 >not an FP language because FP languages don't function #FUCKNREKTM8 >>51563428 Both are not just programming. They both contain it, but one is more a science and the other is more product development >>51563501 woops. mixed up left and right. >>51562843 That's probably the most appropriate pic to start dpt ever. Let me explain something to the retards that say lisp us bad because parentheses : print(x) (print x) Any difference in the number of parentheses? Ok, now imagine instead of curly braces there's parentheses. void foo() { print(2); } (define (foo) (print 2)) Still same number. >>51563562 >webm >pic >>51563783 >( . Y . ) >>51563537JFrame frame = new JFrame(); JPanel pane1 = new JPanel(); JPanel pane2 = new JPanel(); frame.add(pane1, BorderLayout.WEST); frame.add(pane2, BorderLayout.EAST); >>51563783{void foo() {print 2}} Because this makes sense? >>51563832 I completely forgot about BorderLayout, which is embarrassing since I'm using it for north and center. >>51563787 It's a moving picture. >>51563878 technically it's many pictures, just one after another Trying to create a string array that holds 5 names.#include <iostream> #include <string> using namespace std; int main() { const int names = 5; string theNames[names] = {"", "", "", "", ""}; cout << "names"; cin >> theNames[names]; return 0; } The console command just crashes. >>51563454 >>51563520 is it possible to learn programming or any elements from CS/SE on my own and not have to shell out tens of thousands of dollars to go to some fancy smancy university? I've been trying to get this president's quiz to work. It takes the answer without giving an exception finally but the "correct" variable doesn't get anything added onto when the answer is correct. On Line 61 it always says that the person got 0 correct! >>51563996 >array has positions 0, 1, 2, 3, 4 >let me put something at position 5 >>51564040 It's Line 46 in the pastebin. >>51563062 would you just fuck off? Nobody wants your "lisp" that isn't even a real lisp >>51564067 script-fags actually think that's proper program behavior >>51563062 do you have any code examples >>51563897 That's a creepy lil girl >>51564097 >girl so has the light gone out inside for any other programmers 5 cpus ? >>51564121 that looks like a girl to me >>51564134 Whatever makes you happy, man. >>51564067 What's the best x86 asm IDE? >>51564196 >ASM IDE For my programming class I have to create a program of my choice at a beginner level that requires significant effort. What can I make that is both fun and has a good final product. Thanks. >>51563062 >first, it offers <useless addition to language> Ok? >Second it offers <an old concept> inspired mainly by <an old language>, one of the <oldest> Object-Oriented languages, and by <an old language>, being the first object-oriented language to be standardised. Am I supposed to be impressed? Why don't you invent a time machine instead? There's a reason that nobody writes in Smalltalk or Common Lisp; because they're old languages and modern languages have improved since then. >Double Dispatch Is this just a more restrictive version of multiple dispatch? I don't know why you're trying to spread hype but it isn't working. >>51564038 Sure, you can learn everything on your own. The problem is you need a lot discipline to educate yourself the way a university does. Besides that a university would offer group projects and train you to get into a proper development process for something like SE. A university will also introduce you to things you might not think of yourself. You'll also have to build a good portfolio instead of being able to just wave around a piece of paper. Don't underestimate the discipline part, it's easy to slack or get sidetracked if you're the one that sets the deadlines. >>51564204 Yeah I can't find a good one. SASM is neat but it keeps trying to save my binaries to "/usr/lib/gcc/x86_64-unknown-linux-gnu/5.2.0/../../../../lib/" instead of something sane and from what I can tell I can't change it. >>51564285 Why do you need an IDE to write assembly? Why are you writing large enough in assembly to need an IDE? What the hell are you doing? Racket is so much better than the other lisps it's not even fair >>51564083 It is a Lisp. My primary references in building Valutron are ISO/IEC 13816:2007 (Programming Language ISO LISP), from which I mainly draw from its description of ILOS, the object system it uses, and also Revised [6] Report on the Algorithmic Language Scheme, from which I derive general inspiration as well as the semantics of continuations. >>51564096 Here's a very simple example of VOM, the Valutron Object Model://(); >>51564244? >>51564309 I was using emacs but the major modes for asm sucked balls so I'm looking for something with actually-helpful syntax highlighting. >>51564333 This is not a lisp >>51564337 do your own math homework, fagot >>51564333 mild meme./lolisp lol.fagtron ()>()::::()>()(:)(::)()()>(())() >>51564337 Significant effort, not five minutes of effort >>51564196 vim for nasm >>51563996 re-read how arrays work my friend. >>51564368 () & & ==+%*":#;{} {<>;[] [{} <<>^; >>51564196 Depending on the assembler you're using sublime (text editor) should be enough, unless you're in win in which case I think you should use VS. >>51564354 :-) >>51564244 reverse fizzbuzz >>51564383 Write a screen scraper that looks at gambling sites for arbitrage opportunities. >>51564395o o ¿ \_____/ >>51564402 hahaha great post well meme'd, my lad >>51564406 Where are your s expressions? >>51564040 Can I get some help please? >>51564439 The mistake is on line 45: `if (name == pres)` >>51564466 They're both strings though. >>51564426 u wot m8 >>51563746 How do you do that with arguments? Because if I haveint fooTheStuff(int32 arg, real32 arg2, disgustinglyLongStructName* input, int (*fThe)(disgustinglyLongStructName)){ return fThe(input); } Or just many arguments I'd rather break it up like this.int fooTheStuff(int32 arg, real32 arg2, disgustinglyLongStructName* input, int (*fThe)(disgustinglyLongStructName)){ return fThe(input); } Because this is easier to read for me. But there can be plenty of cases where the former example is there because they straddle my limit for how long I want args to be. I think I'd find this very hard with only parenthesis's. At the very least it doesn't make it as clear to me mentally. I see the braces begin in C and I seem them close. That makes it plenty clear what the function body is. But if I were to have this straddling case I don't feel nearly as sure anymore. What's the case for not using braces? Why not make them optional? I haven't programmed in lisp obviously. >>51564482 I can't believe that somebody would nonmemetically recommend Sublime Text and Visual Studio. >>51563996 >>51564389 I fixed it from crashing by doing this cin >> name[0] >> name[1] >> name[2] >> name[3] >> name[4]; cout << name[0] << name[1] << name[2] << name[3] << name[4]; >>51564475 And == doesn't compare the strings by value, so you lose. >>51564491 Visual Studio is perfectly fine as an IDE. >>51564504 vimDE >>51564491 Why? Both are good >>51564437 Available for use. But I was asked for a code example, and so thought it better to use V-expressions, the algebraic syntax available in Valutron, that I could show where Valutron offers differences. This is all explained in my original post. >>51564488 The thing about Lisp is that its syntax is based around parenthesis so there is no concept of "braces". Like, in JavaScript (I'm using it because its a dynamically typed language with curly braces) it might be:function foo (x, y) { ... } In Lisp it's like this:(define (foo x y) ...) In Lisp you show nesting by indenting things correctly. And if a function takes a lot of long arguments, you indent the arguments to the same position(some function that takes (a lot of) arguments) >>51564538 Please use [ code ] tags. >>51564538 (forgot code tags) >>51564498 Do this insteadint main() { const int names = 5; string theNames[names] = {"", "", "", "", ""}; cout << "names"; for(int i=0; i<names){ //i goes from 0 to 4 cin >> theNames[i]; } return 0; } >>51564543 Clojure noob here doing tutorials. Is this indentation/style OK? I'm never sure when to start a new line for arguments vs leaving them inline.(defn point [x y] [x y]) (defn rectangle [bottom-left top-right] [bottom-left top-right]) (defn width [rectangle] (let [[[x1 y1] [x2 y2]] rectangle] (- x2 x1))) (defn height [rectangle] (let [[[x1 y1] [x2 y2]] rectangle] (- y2 y1))) ))) >>51564618 Just you do you, man. >>51564618 Well first off you indented 'if' in 3 different ways in your example. Consistency is key >>51564602 thanks >>51564637 Makes sense. Is there something like pep8/jslint for Clojure? >>51564618 For function calls I (my personal style) indent every argument to the same column, but for syntactic things like 'if' or 'let', put everything 2 spaces in.))) Note that "(if X true false)" is redundant, just write "X" >>51564700 Seems like a 'good enough' style, and lacking any of my own, I'll adopt it. Thanks >>51564543 I'm not sure I follow. Exactly how does lisp not have a concept of braces? Looking at(define (foo x y) ...) It seems pretty clear to me that the opening paren (first character) is the brace equivalent here. It opens and closes the function. Your second example seems very odd to me. Perhaps you could clarify it by labeling things more clearly. Because as is I can't really say if you're making the point I think you're making. I don't see any nesting going on except maybe(a lot of) Which I can't really understand. (you're allowed to group arguments? Arguments can have names containing spaces?) times 1000000000 db 0 resw 1000000000 who's null terminated NOW, huh C? >>51564700 >Note that "(if X true false)" is redundant, just write "X" Oh, and I know this, but the tutorial that I'm following has Midje tests which check the output for 'true' and 'false', so I have to explicity return those (I think). Actually, now I think about that, I just assumed that to be the case, but false and nil are equivalent, right? And anything not nil/false = true. So the tests should pass either way...? >>51564779 OK, just tested that, and they still pass when not explicity returning true/false. Thanks! >>51564762 I'm sorry. In Lisp, () denotes a "list". To evaluate a Lisp expression that is a list, it looks at the first item of the list. This first item is usually the function name that you are calling, which is why "(f x)" is equivalent to "f(x)" in other languages ("f" is the function being called). Constructs like "if" are also just represented as lists. (if x y z) is essentially the same as "x ? y : z" or "if (x) { y } else { z }". When you define a function, that definition syntax is again just a list. The special symbol "define" means that we are defining something. (define <function signature> <body>) The (a lot of) example I gave was just to demonstrate indentation. In that example, the "some" function would be called. "(a lot of)" would also call the "a" function. >>51564779 Never used "Midje" >>51562843 Working on a HTML 5 chatroom. Well... mostly finished with it now. Will give it a proper URL over the weekend: Still open to suggestions and bug reports, if you have them though. Cheers. >>51564333 >>51564826 I'm not entirely sure how I feel about that. It seems neat on surface to have a syntax to say many different things and just change a keyword (or "symbol" as you call it) but I'm not entirely sure how I feel about it in practice. It's very compact for sure. Something many other languages fail at. I was playing codingame's Clash of Code and just got keked hard by some fag writing Python. I was writing in C and got the task to reverse every word in a sentence (but not the entire sentence itself) and by the time I had finished typing in strtok and setting up my loop the fag was already finished. Fuck scripting langauges. >>51564896 The reason I say "symbol" is because 'define' is just like 'x' and 'f', they're all "symbols". The syntax has hardly any exceptions or inconsistencies. The cool part about lists in Lisp is that in Lisp code you work with data that is of the same form that Lisp code is represented in. Therefore it's very easy to implement a feature so that Lisp code may be generated by other Lisp code during compilation. Macros are what makes Lisp such a powerful language; because the language is so simple, and features may be added easily through macros, you end up with an infinitely powerful and expressive language. >>51564862 Encryption? >>51564955 >C fags BTFO It's Black Friday and I'm feeling the need to find a programming book that's on sale and get it. Damn you capitalism >>51564955 Don't worry. Your code most likely ran faster. And on some level he didn't even complete his goal since he left his users mad at him for making their computers run slow/hot/loud and potentially burning battery for no reason. >>51564618:~$ ./lolisp meme.cj ([][])([][])([]([[[][]]]()))([]([[[][]]]()))([]((()())))([](*()()))([]([[[][]][ ]](((<)(<)))))([]([[]]((()())))) Meme: 111 Total: 749 Total meme percent: 118.55% >>51564700([]((()())))([](*()()))([]([[[][]][]](((<)(<)))))([]([[]]((()())))) Meme: 67 Total: 529 Total meme percent: 101.32% It is less memier, he is correct. >>51565026 >And on some level he didn't even complete his goal since he left his users mad at him for making their computers run slow/hot/loud and potentially burning battery for no reason. Do C users actually think this way? >>51565030 His code didn't include all my functions. I think the meme quotient is the same. >>51565073 Hmm. Will revise. Thank you for your patience and understanding. >>51565083 Is forth the least meme language? Well I've been working for a few hours on this and it's pointless. I wrote a hello world program in C without any libraries, without any uses of #include, without any macros or anything. The source file is 46 bytes. But the compiled binary is, after tinkering around with gcc to get the smallest one possible, 4.4KB. 4.4KB. The equivalent handwritten assembly binary is less than 1KB, but the "optimizing" GCC can't get it under 4.4. Absolutely disgusting. I no longer feel bad when coding C# or Haskell, because C isn't even efficient. It's all just bloat. Bloat on top of bloat on top of more bloat. >>51565102 Oh good lord that's some ugly stuff. >>51565107 Hahaskell* >>51565107 If anyone wants to prove me wrong and figure out how to get GCC to pull it under 1KB, feel free to try. Here's my meme source code that theoretically offers the most possible optimization:void main(){write(1,"Hello, world!"\n",14);} >>51565107 Did you strip it? Did you look at the obj dump? Are you on winblows? >>51565107 Did you at least not link to the standard library >>51565107 have you removed the symbol table? >>51565131 this is not valid C >>51562893 OOP is literally one of the best programming paradigms you just don't understand it >>51565131 (take out that stray " though) >>51565132 Opening it in a hex editor reveals that gcc dumps gallons of null characters and debug data that can safely be deleted without any issue. I cut 60% of the stdlib version's binary's size just be removing the junk data. And this was with the highest level of "optimize for size" option selected. I'm on linux. >>51565151 see >>51565131 >>51565167 You still have to not link to it >>51565159 Yeah I accidentally added an extra " in the string when copying into the reply box. Remove the " after the ! in the code and compile it yourself. It only works on x64 Linux, but it compiles and works just fine there. >>51565166 >one of the best m8 pls >>51564145 so is it a female or not?? hips/legs look suspicious i guess? maybe arms too? but the face doesn't look male I know you're trolling, but there's not a single x86 computer out there that is even slightly impacted by the difference between a 4KB executable and a 1KB executable. >>51565175 Adding in the `-c` option results in a binary file that doesn't even execute. And that binary file is still well over 1KB. Unless I'm missing something here? >>51564333 >dylan with scala-like syntax >""""""""""""""lisp"""""""""""""" >>51563783 absolutely disgusting >>51565107 >Haskell >Compiler is 809 MB installed >Worried about an extra 3KB on a C binary >>51565208 This is /dpt/, bikeshedding is practically all we do. I've always heard that compilers are faster and better coders then humans could possibly be so it isn't worth writing assembly. I tried my hand at assembly and found that to be unilaterally false. Sue me. >>51565211 You have to link the executable, but you can stop it from linking to the standard library >>51565208 what is the 8086? >>51565207 Does it matter to you? If you think it's a girl then that's fine. >>51565181 still not valid C. void main is undefined behaviour on hosted environment. not sure about main with no arguments but I am pretty sure it is not allowed too. you are using a OS dependent function and not even incloding its headers. you could as well post python code and call it C at this point >>51565228 >my assembly for 'hello world' was smaller. Okay, now try with something substantial. >>51565107 >>51562843 C program that prints "my ass is hairy" >>51565259 >compiles just fine >executes just fine >"still not valid C" Interesting articles here: One of the lead developers on Microsoft's 'Midori' research OS has started writing blogs about it. The thing was pretty secretive up until now. Super interesting shit. >>51565235 Compiling with `-nostdlib` results in this error:world.c: In function ‘main’: world.c:1:13: warning: implicit declaration of function ‘write’ [-Wimplicit-function-declaration] void main(){write(1, "Hello, world!\n", 14);} ^ /usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 0000000000400144 /tmp/ccko4EUM.o: In function `main': world.c:(.text+0x19): undefined reference to `write' collect2: error: ld returned 1 exit status *shrugs* >>51565330 Yep, you can't use main() anymore. >>51565228 the "can't beat the compiler" and "premature optimization is the root of all evil" memes are just an excuse for stupid and lazy normies to write bad code. of course you can beat the compiler, it's just a simple tool that has to do a "best effort" within a reasonable time frame and it can't read your mind to find out what optimizations it can do that are specific to the problem you're solving with the code. y/n >>51565228 >found that to be unilaterally false Write an assembly function that averages two integers, in the fastcall convention. Then try__attribute__((fastcall)) int avg (int x, int y) { return (x + y) / 2; } gcc -c avg.c -O2 and tell me all about how much more clever and efficient you are than the compiler. >>51562843 Doing OpenGL uni work in Haskek instead of C with the raw bindings >>51565314 here is a "C" program that compiles fine on my custom "C" compiler and executes fine on my system. binary size is 0 byte, I bet noone can beat that recordfuck you >>51565342 and we aren't even close to getting strong AI so even if the compiler had perfect information about the problem you couldn't make it write a non-trivial program for you in the most efficient way >>51565340 Okay, now I'm interested. >>51565314 This compiles (under gcc at least), is it valid C code?int main() { int(*){} ayyyy lmao } >>51565361 Is the compiler's name touch, by any chance? >>51565342 "Can't beat the compiler" is in terms of translating C to assembly. Doesn't help you one bit if your program is poorly written in the first place. >>51564985 What encryption? >>51565366 >implying strong ai can circumvent rice's theorem >>51565324 >Midori was built out of many ultra-lightweight, fine-grained processes, connected through strongly typed message passing interfaces holy shit, that is disgusting >>51565404 End-to-End >>51565415 What's disgusting about it? >>51565425 Nope. No encryption at all. On either end. Though I do that in other projects. >>51565214 :-) #FROB# >>51565275 that was a great read. >>51565425 What made you ask about encryption anyway? >>51565494 %%FROB^^ >>51565500 >Still open to suggestions >>51565473 >copy-paste previous post >arguments - if you have any left :-) just tripfag so i can filter your faggot ass well fucking shit I did it i created a C program that compiles properly that's under 1KB Granted it segfaults as soon as you try to run it but it fucking works. Here's the glorious source code that, when fed into `gcc -s -nostdlib`, produces an executable of 952 bytes in length:write($1){} Am I a magician yet? >>51565380 >>51565525 What kind of encryption are you talking about here? And wouldn't be easier to just post the suggestion on the board itself? >>51565574 >Click this for noscript browsers The link does not work >>51565594 End-to-End using a password, CryptoJS? Alright, I need help /g/entlemen. Say I want to do something to a variable via multiprocess. In UNIX, I've read that I'd need to use either shm_get() or mmap() but I didn't quite get how these work. Here's what I have#define N 4 int main () { pid_t pids[N] int i; pid_t pid; for(i = 0; i < N; i++) { if((pids[i] = fork()) < 0) { perror("Fork"); abort(); } if(pids[i] == 0) { //do something to a variable //example: x++, but I want x to be visible/shared with all children processes exit(1) } } while(pid = waitpid(-1, NULL, 0)) { if(errno == ECHILD) { break; } } return 0; } Something like that. How exactly can I "share" x with the processes? >>51565601 Just like your browser. Just the way you like it. >>51565617 with shmget or mmap >>51565054 >C users No most certainly not. C programmers might, but it's not a requirement to be a C programmer (sadly). >>51565601 >clicking random links you see on le 4chinz enjoy your free as in freedom malware brah >>51565634 My browser works fine, I can post here just fine, but your link though... >>51565643 The only requirement to be a C programmer is desire to instill a serious sense of consternation is every single one of your clients. When is the major password-leaking bug going to show up? Who knows, and that's half the fun! >>51565655 >that image >>51565655 >ever getting malware through your browser typing in a loonix command != clicking a random link >>51565607 Oh... User accounts you mean? Absolutely not! Went out of my way to devise a scheme to allow (myself and other) users to casual identify each, without using sessions or cookies. I've need to be especially care around networked devices that share the same IP... I've accounted for that, but not sure if that code works yet, because you'd need a fairly rare condition to test the edge case of conflicting machines. >>51565292 do you have a repo for this? I'm interested in following development. >>51565721 What? No. Encrypt messages on the client before sending them to the server and then decrypt them at the receiver using the same password. Just enter it once you enter the room. >>51565726 Unfortunately it is currently proprietary software. Perhaps I can release the source code under a more permissive license in the future. >>51565683 Very funny. If you know how to program C and build your abstractions well this is a non issue. (assuming your platform isn't vulnerable) >>51565759 or just use https encryption. >>51565778 Say no more, I understand. My lolisp and hahaskell are also proprietary as of now. >>51565617 You can use named pipes. man -s2 mkfifo >>51565784 >if you don't make any bugs in your code it's a not issue >>51565784 >If you know how to program C and build your abstractions well this is a non issue. Mostly, but there have been very few big projects that never see severe vulnerabilities. >Very funny. I know, I enjoy a bit of light trolling. >>51565810 I dream that your race mixing is an elaborate troll, but then I remember you use a trip as well, so clearly you are a niggerlover. What shame. >get challenge to grab hex number from stdin and convert to decimal then print >OK, sounds easy to me >write a three liner, seven if you count includes + main >best winning entry is 15 characters, written in Ruby why the fuck is the number of characters at all relevant i guess if your code can't fit in a fucking tweet then it's shit, right >tfw "#include <stdio.h>" by itself already makes you lose to keked languages I CAN'T WAKE UP >>51565840 Git gud >>51565888 why bother when one of your language's all but mandatory includes already precludes you from winning anything >>51565888 >best entry for getting the current time. >>51565540 Er, is there actually a way to get this to not segfault? It seems like there should be but I'm stumped. >>51565793 >lolisp and hahaskell You got my attention at "loli" >>51565827 >I dream that your race mixing is an elaborate troll, but then I remember you use a trip as well, so clearly you are a niggerlover. If there are two things I am direly serious about, they are liberty and nigger-loving. >>51565759 >>51565785 The only real way to do it, is https. But for this, I don't want any encryption at all. But I do want cogent machine id's without using cookies or database backed sessions. Not sure if that's possible over http though. :/ >>51565936 There's a lot of really good stuff on there though >>51565997 just have a little bit of client side code that generates a unique ID for the machine, and tells the server. >>51562843 trying to rewrite the fucking datastax cassandra driver so it works on net.core and not just net.framework FUCK THIS >>51566042 Those are really cool. Thanks for sharing. What's something fun to do? Write imageboard/textboard software in JSP? >>51565984 What're you up to on this fine friday, GTP >>51566187 being a tripcode >>51566243 and what're YOU doing this fine friday r8 my function/* TODO: Determine empirically vertices.size() as a function of Num_Divisions * so that std::vector size is set with constructor */ GraphicArray_VCN make_parametric_surface(ParametricFunction f, ParametricFunction f_normal, const UV_Bounds& uv_bounds, std::size_t Num_Divisions) { std::vector<Vertex> vertices; std::vector<Vertex> normals; for (int i = 1; i < Num_Divisions; i++) { double u0, u1 = /* range mapping cut for post length limit */ for (int j = 1; j < Num_Divisions; j++) { // v changes while u kept constant double v0, v1 = /* range mapping cut for post length limit */ Vertex corner1 = f(u0, v0); Vertex corner2 = f(u1, v0); Vertex corner3 = f(u0, v1); Vertex corner4 = f(u1, v1); vertices.push_back(corner1); vertices.push_back(corner3); vertices.push_back(corner2); vertices.push_back(corner2); vertices.push_back(corner3); vertices.push_back(corner4); // // N = cross( dF/du, dF/dv ); Vertex corner1_normal = f_normal(u0, v0); Vertex corner2_normal = f_normal(u1, v0); Vertex corner3_normal = f_normal(u0, v1); Vertex corner4_normal = f_normal(u1, v1); normals.push_back(corner1_normal); normals.push_back(corner3_normal); normals.push_back(corner2_normal); normals.push_back(corner2_normal); normals.push_back(corner3_normal); normals.push_back(corner4_normal); } } std::vector<Vertex> colors(vertices.size()); for (auto& vertex : colors) { vertex.x = color.x; vertex.y = color.y; vertex.z = color.z; } return GraphicArray_VCN(vertices, colors, normals); } >>51566432 function/10 now, you help me out should i score blow or not i kinda need to save but i would quite enjoy some white. Code this for me, monkeys >the program takes 4 float numbers >multiply 3 of them by 0,23 >multiply one of the by 0,3 >add the numbers after multiplied >if >= 7 = yay >else = bah >>51566187 Not much, kinda dicking around right now. >>51566432 seems hard great job >>51566490 no going out? no drinking? no drugs? >>51566472 If you can't do this, drop out. You're just wasting your money. why does this give me a error when naming the enemies? >>51566529 How are you naming them? >>51566472public class Nigger { public static final synchronized strictfp String foo(float a, float b, float c, float d) { a *= 0.23f; b *= 0.23f; c *= 0.23f; d *= 0.3f; return (a + b) + (c + d) >= 7.0f ? "yay" : "bah"; } } >>51566499 No, no, and no. I'm actually trying to do that codegolf challenge where you use the palette of one image to generate another. I have a slow going solution, but we'll see if it works. >>51565166 >one of h-how many different paradigms are there? I didn't think there was a particularly large count. >>51566568 >h-how many different paradigms are there? Millions. >>51566564 Gotcha. Gay, gay and gay. Nah just kidding. I'm off to get some blow, have a couple drinks with my buddy then I'll be back to shitpost some more if I can stand. Good luck. >>51566561 That's a class not a complete program. You're not handling arguments. (Though he wouldn't know the difference.) >>51566568 6 googolplex quadrillion >>51566515 i'm not in CS or anything like it, just way to lazy to this in excel >>51566561 i'm not a coder but 100% sure that won't compile >>51566564 if your're calculating the distance, don't use a square root. It's unnecessary and actually impacts computation time heavily. >>51565166 I wish someone who understood OOP who's of the opinion that it's good could explain to me why it's good in a sane way. Because it's not a paradigm made for human computers and I'm interested in alien technology >>51566583 Enjoy your drug dependence, brain damage, and life of regret. >>51566601 >just way to lazy to this in excel That's a shitton of lazy right there. >>51566630 i didn't even typed the "to DO this" top kek >>51566626 It's the weekend. I have a monday to friday job which I work 43 hours a week, quite well. But I appreciate your concern, you have a wonderful night mr no self control judgmental kuk >>51566586 >>51566601 sure it would, try this:public class Nigger { public static final synchronized strictfp String foo(float a, float b, float c, float d) { a *= 0.23f; b *= 0.23f; c *= 0.23f; d *= 0.3f; return (a + b) + (c + d) >= 7.0f ? "yay" : "bah"; } public static void main(final String[] args) { final Scanner in = new Scanner(System.in); final String[] numberStrings = { "FIRST", "SECOND", "THIRD", "FOURTH" }; final float[] input = new float[numberStrings.length]; for(int i = 0; i < numberStrings.length; ++i) { System.out.print("ENTER THE "); System.out.print(numberStrings[i]); System.out.print(" NUMBER"); System.out.println(); input[i] = in.nextFloat(); } System.out.println(foo(input[0], input[1], input[2], input[3])); in.close(); } } >>51566683 dear god, how do you even code in that shitty language? give me two minutes and i code that in python >>51566702 it's how you build scalable Enterprise™ solutions fgt >>51564040 >>51564439 I don't think that's how you use oop m8. Rewriting a game engine i started working on last year Pretty clean atm Simple point of sale web app >>51566726 >Buttboi Well, it's plugging away right now. Rather naive solution, but I'm actually interested to see how shit the results are. >>51566741 Keep on working at it, Buttboisenpai >>51566614 in real life you use objects. like someone built a car for you (if you own a car), you probably didn't build yours from scratch. and it has a relatively simple interface for you to use it, with the gas pedal and steering wheel and such. when you want to start the engine, you just turn the key and it does all sorts of things automatically so you don't have to worry about the spark plug and whatnot. now take this concept of objects that you can use with a relatively simple interface into the programming world. that's Object Oriented Programming™. >>51561893 Still wondering about this. >>51566702 >two minutes well? Well shit up my ass and call me charlie, it worked! This is American Gothic using the Mona Lisa palette. However, since it works in strips, you can see how it was getting to the dregs of the mona lisa palette in the second half of the image. >>51566779 already did it, used it and deleted just a simple function, even a mechanical computer can do it >>51566547 i have it in a string under the main code >>51566838 i would still like to see it for curiosity's sake >>51566432 with sample surface that didn't render completely correct. Gonna test with a sphere next, I don't think my function is meant to handle 360-revolutions. >>51566779 Guess he didn't show. Here's something I did in 30 sec.import sys a=float(sys.argv[1])*0.23 b=float(sys.argv[2])*0.23 c=float(sys.argv[3])*0.23 d=float(sys.argv[4])*0.3 sum=a+b+c+d if sum>=7: print("yay") else: print("bah") >>51566683 >return (a + b) + (c + d) >= 7.0f ? "yay" : "bah"; dog shit tier code nice readability nerd lmao!!! >>51566885 It's actually very good readability. He even placed parens around the additions to make it super clear. I wish everyone I worked with made things this clear. >>51566885 >public static final synchronized strictfp String i was being facetious in case he would actually copy it for homework or something >>51566875 jesus christ, that is a beautiful piece of code >>51566894 the parens were to keep better accuracy of the float additions so you get (a + b) + (c + d) instead of ((a + b) + c) + d >>51566934 Ah that's also an excellent reason to write it that way. Though I think that due to the way processors work the compiler would make the same thing because it doesn't want order dependencies. >>51566875 fixeda = float(input("1: ")) b = float(input("2: ")) c = float(input("3: ")) d = float(input("4: ")) sum1 = a * 0.23 sum2 = b * 0.23 sum3 = c * 0.23 sum4 = d * 0.3 sum_final = sum1 + sum2 + sum3 + sum4 if sum_final >= 7: print "yay" print sum_final else: print "bah" print sum_final >>51566833 I think better color matching is a recursive problem >average the colors on each half of the farmer's wife >average the colors on each half of the mona lisa >find out which half is closer to which >do the same for each quarter I'm pretty sure this has some side effects, but I'm not sure what. Also, it becomes a bit more difficult for images with sizes that aren't perfect powers of two. Also for fast averaging of colors, you'll need to take different sample rates for different pixel sizes. Obviously when you're comparing the two full halves, you don't want to take EVERY pixel when you're determining average color. Take, say, every 10th pixel. >>51566547 this is the main >>51566963 >>51566472 >the program takes 4 float numbers Takes, not asks for input. >>51566561 >public static final synchronized strictfp String foo lol What's with all these "programmers" that don't follow established design patterns? >>51566983 if a programmer types a input line of code thats because hes taking data from you you have a moral duty to give that data to him, so the program can continue on his task >>51566972 >I think better color matching is a recursive problem Probably. Many people also worked center-out, which pushes all the left-over shit-colors off the center of focus. That said, I managed to come up with a similar result to that first run in about 1/8th the time, because this solution doesn't check the entire palette, but now just takes a random sampling off the full palette (say 5k colors) and picks the best. Still has the problem of leaving the shit colors, but much faster and nearly the same quality. >>51566976 Still don't see where you're trying to set the name. >>51566754 But you're ignoring everything that makes it bad and saying it's good. Your program has one goal. Take data and turn it into other data. There's no other way to do things right now. You can't give your program an object. You can't cram a car into your computer. What you give it is data in some form. You take that information and do something with it and place it (in memory) to another form which is a desired result. Nowhere along this process is an "object" as object orientation describes it appropriate representation. Even such a thing as function association is inappropriate and superfluous. got most of my Forth interpreter working still need to add error checking and symbol definition (lol) but after that it's just adding more standard functions >>51567042 there as a string, //Game variables String[] enemy = { "Skeleton", "Zombie", "Archer", "Viking", "Wolf", "Villager" }; int maxEnemyHealth = 100; int enemyAttackDamage = 25; >>51562843 >>51567074 That has nothing to do with the Enemy class, though, I'm drunk as hell and don't even know what language you're in but {} looks wrong to me for a string array. Might help if you posted the error message as well. >>51566529 If you really want help copy and fill out this form please:Error message: Line number: Pastebin with associated file: Desired result: >>51566951 i don't think it would. it has to be the equivalent computation, even without strictfp. maybe in some JVMs it would be allowed to have something like -ffast-math, not sure if it's mandated in the standard. >foo(0.1f, 0.1f, 0.1f, 0.1f) >return (a + b) + (c + d); >0.09900001 >return a + b + c + d; >0.099 Somebody explain this Spring for Java bullshit to me. I'm a professional developer and only have the vaguest idea of what problem it solves. >>51567133a *= 0.23f; b *= 0.23f; c *= 0.23f; d *= 0.3f; before the return statement >>51567064 murrican detected you can have an "imaginary" object that only exists in cyber-space and it'll work perfectly fine. i'm not talking about putting an actual, physical car inside your computer. >>51567141 >People realize issues with what they're doing >People aim to fix these issues >Don't attack underlying problems >Users end up confused as to what the point of it all is >Doesn't matter for marketing people. >>51567172 >I meant an idea in my head not a physical car >I interface to my computer like Neo and the matrix Anon do you really think that was a relevant point to bring up. How about you respond to the data oriented argument I've made which invalidated Object oriented programming just fine on its own. >>51566472def thing(a, b, c, d): result=.23*(a+b+c)+.3*d return 'yay' if result>=7 else "bah" Of course I could smash this all into one line or use some lower-level pleb-tier language, but then I'd lose muh readability. >>51567133 Fair enough. Didn't consider that. Your results are computed with optimizations on right? So, I don't exactly understand the link between the XML and Java activities for Android Studio. I have some EditText fields for Activity 1 with id entername and enteremail. I want to pass something in those field to Activity 2, I'm using this code right now.Intent success = new Intent(this, RegisterSuccess.class); success.putExtra("email","enteremail"); success.putExtra("name","entername"); startActivity(success); After passing the Strings from the EditText in Activity 1 to Activity 2, how would I display those Strings on screen in a TextView? >>51567214 you can categorize your data, group them together and put them in an object. if you want a hamburger you don't start up a farm and raise cows, grow wheat etc and micro-manage the flow of the ingredients/data until you've made the finished burger, no you just buy a ready-made burger or at least ingredients that have been pre-processed to some degree. the same concept can be applied to any "object", real or virtual. data-oriented programming is good for performance and catering to the hardware. but from a human's perspective it's not as elegant as OOP. >>51567104 those are what the enemies are supposed to be, it comes up as a java lang error. it is java. >>51567260 with strictfp in the method declaration the result will be the same on any computer and the results are like in >>51567133 even with strictfp >>51567214 also >>I interface to my computer like Neo and the matrix other parts of the program interface with the object of course hey guys, I'm on a mac and want to make my background the live stream from the ISS. I know it can be done with VLC, on windows, but It looks like I'm going to have to come up with something myself. I know python and some applescript. Does anyone have any ideas/ know a direction to point me in? That's all I need to get started. Why doesn't this work? my_processes = [x for x in psutil.process_iter() if os.path.split(x.cmdline()[0])[1] == 'firefox.exe'] >>51567382 >>51567297 Post the error messages people, "it doesn't work" would make your ticket be closed with "invalid" in 2 seconds. >>51567412Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> my_processes = [x for x in psutil.process_iter() if os.path.split(x.cmdline()[0])[1] == 'cmd.exe'] File "<pyshell#6>", line 1, in <listcomp> my_processes = [x for x in psutil.process_iter() if os.path.split(x.cmdline()[0])[1] == 'cmd.exe'] IndexError: list index out of range >>51567367 You can do the same with VLC on your Mac. >>51567382 >>51567432 Write it out in multiple lines and see where it goes wrong and why. >>51567412 # [Ljava.lang.String;@42a57993 appeared ! # shows this instead of one of the random enemies >>51567482 ok ;_; i am back. who would like a line. How can people stand using dynamic type checking? On top of making your program more prone to containing bugs, it also makes them infinitely harder to track down. I've saved probably 20% of the normal amount of time I would have used writing code and spent 50% more time debugging. >>51567552 hey are you that guy that posted with his first name some months ago? i don't remember the name but i know he did coke i've been missing him t'bh >>51567574 I dunno my first name is Jeff, was it him? >>51567566 C++ is the least type safe language i can stand to use >>51567566 If it takes you that long to debug, your program is too complex or you aren't familiar enough with dynamic languages yet. Write unit tests to make up for the lack of typechecking. Also, having an interpreter at your disposal can make it really easy to find problems with your code. >>51567566 >On top of making your program more prone to containing bugs [citation needed] >it also makes them infinitely harder to track down. [citation needed] >>51567611 it's very possible. i had a hunch that it was a single-syllable name starting with j. damn that's neat that you're still around and still interested in programming. good luck m8 and keep up the good work! >>51567620 >relying on unit tests >>51567293 Data oriented programming is the straightest way through the program. It enables the program to be the theoretically best program on the machine. If you want the best program in OOP you really have to dig deep into complicated stuff that just isn't there in a data oriented design. I respect the OOP programmers who can do this immensely but since the argument for OOP tends to be convenience. And the few instances where it could potentially "simplify things" is in places where your program doesn't have many requirements on it (since where it matters OOP is going to be an issue because of performance) almost any programming style works fairly well for those problems. That's not where a programmer faces his issues. And when the programmer face these issues (as we do for one reason or another) the OOP will likely cost more than non-OOP in one way or another. Either the solution isn't great, you have a "de-OOP" layer where you allow access in a non-OOP way or change the data around to fit the part of the program you'd rather not OOP because of the issues. Or you will have to structure your OOP to fit the data oriented design. And at that point the OOP will clearly have been a hindrance. Because really, you can't work with computers without understanding the memory in some form. Doesn't matter what abstraction layer is in front of it. You have to understand what it looks like to do the right things. At some point you did touch that data and change it the way you wanted it to. If not you then it was your library that did it. After that you deal with references in some form or another. You want this part of the code to know about the data which you touched before. The object abstraction doesn't remove any of the work. And without knowing what work has been done you can't make any judgement about the next step to take. I'm too tired to be writing stuff like this. Hopefully it makes some sense. tl;dr is that the cases I've seen OOP work (stringently) are few. Apparently a 2-pass method provides spooky output. >>51567022 A very good approach is to match one image's histogram to the other. >>51567661 What did this person you remember do? Only recently (3 months) have I been able to afford this shit again, since I came into a quite comfortable job. Do you recall this name from the /g/ Infect thing? >>51567617 I can handle using C, but that's about it. I mostly mean compile-time type checking as opposed to type safety, though. >>51567620 >Write unit tests to make up for the lack of typechecking Except if one thing goes wrong because of how a (standard library) function interacts with user input and I am not aware of that no unit test will properly cover that. Type checking limits the amount of possible states in a program, unit testing cannot do the same. >>51567622 >[citation needed] my current project :^) >>51567708 Unit tests are an industry-wide standard practice at this point. How else can you be certain that your code works? How do you know you introduced a significant change without breaking anything in a 2 million LOC project? I can't say I can take anything you say all that seriously if you think unit tests are anything besides a good thing. >>51567791 it was in /dpt/. i think he posted with Jeff or something like that in the name field instead of Anonymous. iirc he did some beginner programming stuff and talked about coke in an excited manner. >>51567839 >Except if one thing goes wrong because of how a (standard library) function interacts with user input and I am not aware of that no unit test will properly cover that. Type checking limits the amount of possible states in a program, unit testing cannot do the same. ONLY unit tests can cover that. Compile time checking doesn't help you at all with program logic especially not cases dependent on user input. >>51567869 Nope, wasn't me. I was the dude who made Infect. I do enjoy cocaine though, but I've been programming since my single-digit ages. drugs are overrated, 2bh. >>51567845 it's absolutely plebeian to put so much focus on the tests when you should just write the code properly in the first place. design your program well and step through the logic of each individual part. then you test the program as a whole or a major component of it, not each individual function. how do you even know that the unit test covers everything? if you're able to know that a unit test is good to go, then how can you not know if a function is good to go? or do you write a unit test for the unit test for the unit test etc? but i guess if you're the data-oriented fag you have no concept of encapsulation. >>51567923 use the drug, don't let it use you, tbqh. >>51567899 ah ok. might have been jake, jeffrey, joe or something like that >>51567899 Are you the feminist guy? >>51567939 jeffrey is short for jeff, but i appreciate you spelling it correctly. not of this tri-syllable bullshit "jeffery" or GOD forbid, geoffery. you seem like a cool guy though, nice to meet you. >>51567954 Fuck no. I have an ex wife who quite openly identifies as a cunt. >>51567923 what do you guys use to WAKEMEUPINSIDE? coffee kinda sucks. i've been trying alpha wave binaural beats and they do work, i get super productive but only for like a few hours and then i get super sleepy and sleep way too much. >>51567890 No I mean that a standard library function has multiple return types, for example (as is the case with some of the functions I'm using). Type checking would prevent that from happening (or verify that I am using the return type correctly if I'm explicitly casting the values). Instead, dynamically typed languages defer the bug to runtime. A unit test cannot simulate every single runtime variable so it will never have the kind of coverage that a type checker would. >>51567928 >how do I know my program is bug free? >write unit tests >but I never write code with bugs!!!!!!!!!!!!!!!!!!!!!!!!!!!!! none of you fuckers have never written anything bigger than your comp sci 102 term project >>51567966 may i suggest cocaine kidding. adderall is good for programming, but honestly.. just drink a lot of water, get rest, relax, have neat ideas and be passionate. the feeling you get when you accomplish your goal is better than any line i've ever done. >>51567966 >coffee kinda sucks I drink 100 cups a day. And I know, caffeine is a drug, but really? >>51567983 >if i write unit tests it will make my shitty python all fine and dandy! >>51567973 No, type checking wouldn't help with that. >A unit test cannot simulate every single runtime variable Of course it can, there aren't an infinite number of cases. >>51567928 >just write the code properly in the first place. ^) >>51568036 if it doesn't work, go back and debug it. put some print statements in the appropriate places to check what's going on. don't need a unit test for that. OOOH great example of a bug exclusive to dynamic type checking right here: >using `let` >switch functionality to something that should require `let*` >identifier collision with 2 identifiers of completely different types >program uses the wrong identifier, rather than warning me of a type error ahead of time (which would let me know that it is using the wrong variable) >>51568021 a normal function has a^b combinations of inputs and outputs, where a is the number of values of the input type and b is the number of values of the output type. in a dynamically typed language, a and b become the number of possible values in the entire language, which is damn near infinite if you ask me. >>51568057 >if it doesn't work, go back and debug it. put some print statements in the appropriate places to check what's going on Unit tests are just automating that process. >>51567995 if i drink more than 1-2 cups a day i quickly get burnt out and feel like shit and need a cup just to feel somewhat normal >>51568092 and the coffee barely helps in the first place. like now i've just been wasting time on the internet, mostly on 4chan >>51568014 Good code needs unit tests too. >>51568065 >in a dynamically typed language, a and b become the number of possible values in the entire language No. Dynamically typed languages still knows about all possible types (it obviously has to, since it dispatches to different code depending on the type tag), it's a finite and quite small number, definitely feasible to enumerate and test all cases. >>51568057 Yes, let's check the entire application manually by adding print statements in the whole code and going through it line by line with every change we make. That'll save us time! >>51568141 no you just check the most recently changed part because you know that everything else works 100%. >>51568155 do you even write code >>51568155 But you don't know if there are any regression bugs due to your changes, running tests that take a few seconds vs going in and adding print statements every time should be a no-brainer. >>51568170 not everyone writes sloppy, retarded code that needs to have 80% of dev time allocated to doing unit tests, pedro >>51568114 >coffee barely helps in the first place don't remind me. >>51568155 Kid, give it a few years before you chime in >>51568193 ok kid there is nothing wrong with python it's literally the best computer programming language >>51568186 >>51568274 CS101 script kiddies who can make simple loops and think know how to make real software detected >>51568342 normies that think it's a good thing to write a septillion unit tests, then spend close to zero effort on writing the actual program, and then testing and rewriting the code a septendecillion times until the code reaches the bare minimum to satisfy the possibly flawed unit tests detected pls make new thred New shitty thread: >>51568507 so perl is neat, but i'm now learning that nobody uses it anymore. what are the "hip" alternatives, and where do they shine. python and ruby come to mind, but i know little about them. Basically, what scripting language should i really focus on learning?
https://4archive.org/board/g/thread/51562843/daily-programming-thread
CC-MAIN-2018-34
refinedweb
9,690
72.16
Top: Multithreading: rwlock #include <pasync.h> class rwlock { rwlock(); void rdlock(); void wrlock(); void unlock(); } class scoperead { scoperead(rwlock&); ~scoperead(); } class scopewrite { scopewrite(rwlock&); ~scopewrite(); } Rwlock (read/write lock) is a variation of mutex with a possibility to control critical sections more efficiently. Unlike the simple mutex, rwlock allows multiple reader threads to enter the critical section, and only one writer thread at a time. Reading and writing in this context means access to a resource or compound data shared between threads. Reader threads must lock the critical section with rdlock() and the writers must lock it with wrlock(). Both leave the critical section with unlock(). This class incorporates POSIX rwlock interface on UNIX and library's own implementation on Windows and MacOS X. When using the rwlock class on Linux, you need to define a symbol _GNU_SOURCE either in the command line, or anywhere in your source before including any system headers. Analogously to scopelock (see mutex), scoperead and scopewrite are fully-inline'd utility classes provided for exception-safe locking of operator blocks. Please, see Portability and performance issues for additional notes on rwlock implementation. rwlock::rwlock() creates a rwlock object. void rwlock::rdlock() locks the object for reading. Multiple threads can enter the critical section through rdlock(), however, if the object is already locked for writing, all reader threads wait until the writer leaves the critical section. void rwlock::wrlock() locks the object for writing. If there are readers inside the critical section, the writer waits until all threads leave and unlock the object. Only one writer at a time can enter the critical section. void rwlock::unlock() unlocks the object. Both readers and writers must use this method when leaving the critical section. scoperead::scoperead(rwlock& rw) creates a scoperead object and calls rdlock() for the object rw. scoperead::~scoperead() calls unlock() for the rwlock object specified during construction and destroys the scoperead object. scopewrite::scopewrite(rwlock& rw) creates a scopewrite object and calls wrlock() for the object rw. scopewrite::~scopewrite() calls unlock() for the rwlock object specified during construction and destroys the scopewrite object. See also: thread, mutex, trigger, semaphore, Examples
http://www.melikyan.com/ptypes/doc/async.rwlock.html
crawl-001
refinedweb
356
56.55
Let's face it, embedding scripts in your React app just makes you feel like you need a shower. So when Active Campaign comes along with a form you embed you feel a lot of, "Get outta here!" Even better you have to build it to match a pre-defined style. Yeah, I feel ya. Realizing we have to deal with this beast we are left with 2 options after we create the form in Active Campaign: 1. Style the form within Active Campaign. This will most likely mean investing hours of your life fighting with the limited options and custom styles. Sure do able, but for most of us developers out there, this is super frustrating. As you are not just trying to make that more look decent, it needs to match your exact syles, and oh yeah render properly within your site. For those of you brave enough to travel this path, may the force be with you. If you do, here are my tips: - Either use the form for just the form input and submit elements or for the entire form section you are working to build. No gray area here. Limited, or all in. - Don't wait to dive into the custom styles. It's really the only way you are going to get anywhere. Get the tags set up that you need, stay organized and might against all urges to reach for the !important... we all know that ends no place good. When you have your form ready, for the sake of organization give that thing its own React component. It will need to be a React.Component so that you can utilize the componentDidMount function. Here is where you will inject the Active Campaign provided script into the page. You will end up with something like: class ActiveCampaignForm extends Component { componentDidMount() { const script = document.createElement('script'); script.src = ''; script.async = true; document.body.appendChild(script); } render() { <div className="_form_1" /> } } In the above script.src is the script provided by Active Campaign and the element rendered is a div with the id of your Active Campaign form you are embedding. If you try to style the div or rendered form here in your component. Good luck. When the form fully renders from the Active Campaign script it will overrule all you have here. It is custom styles within Active Campaign for nothing. Now, if your form is pretty basic, no super custom styling, this may be the perfect solution for you. Enjoy it while it lasts. This is also a decent solution to prove that you have all wired correctly in Active Campaign... list, emails, post-submit form, all that good stuff. Just don't get too attached if you have custom styling tasks in your future. 2. Build your own form in React. Post to the URL of the Active Campaign form. Ok, now we are talking. Full control of your form and styling all within your component. Beyond that, you can keep the user within the experience of your site and not have to bounce then into Active Campaign. To do this, again, give this beast its own component. It will help with organization, writing tests, plus I like things to have one purpose. Now, Active Campaign is not going to give you what you need easily. But all the information you will need is baked into the block of "Full Embed" code that they provide. Within that look for the form, you will need the URL the form submits to as well as all the hidden inputs. Here is what this is going to look like: class ActiveCampaignForm extends Component { constructor(props) { super(props); this.state = { formSubmitted: false, }; this.onSubmit = this.onSubmit.bind(this); } onSubmit(event) { event.preventDefault(); const data = new FormData(event.target); fetch('', { method: 'POST', body: data, mode: 'no-cors', }) .then(response => { this.setState({ formSubmitted: true }); setTimeout(() => { this.setState({ formSubmitted: false }); }, 5000); }) .catch(error => console.log('Request failed', error)); } render() { const { formSubmitted } = this.state; return ( <div> <h5>Join our mailing list!</p> { formSubmitted && ( <p> <strong>THANK YOU</strong> for joining our mailing list! <br /> Check your inbox for a confirmation. </p> )} { !formSubmitted && ( <form onSubmit={this.onSubmit}> <input type="hidden" name="u" value="1" /> <input type="hidden" name="f" value="1" /> <input type="hidden" name="s" /> <input type="hidden" name="c" value="0" /> <input type="hidden" name="m" value="0" /> <input type="hidden" name="act" value="sub" /> <input type="hidden" name="v" value="2" /> <input type="text" name="email" placeholder="ex: hello@youareawesome.com" required /> <input type="submit" value="Submit"> </form> )} </div> ); } } In the above, I simply built the form I wanted out exactly how I wanted it. Added an onSubmit handler to submit the values entered and set it to send to the URL I found in the provided "Full Embed" code from Active Campaign. A few things to note: - I hit a CORS issue that prevented the fetch from occurring. There may be other ways to solve this, I just reach for adding mode: 'no-cors'to the fetch options to get passed that issue. - I opted to add a state here to know if the form was submitted, formSubmitted. I did this so that I could display a message to the user so that they knew their sign up was successful. - The catch fo when an error occurs on the submit should really be more sophisticated than a console.log, but hey, we all start somewhere. In my case I'm going to update this to Sentry.captureException(error);. Now you are off. You have the best of both worlds, a form you can easily and fully style exactly how you need to and the convenience of using an Active Campaign form tied to a list. Discussion (1) This was exactly what I needed to modify my previous subscription form for ActiveCampaign. I can't image why it took them for this kind of code to be not in their documentations for their clients.
https://dev.to/saragibby/better-way-to-embed-active-campaign-forms-into-react-n9n
CC-MAIN-2022-05
refinedweb
996
74.9
! Enable!. In previous previews of Microsoft Ajax 4, we introduced the DataView control. It’s a simple but powerful control that takes advantage of the client templating engine we built for it. You point it at a template, and some data, and it instantiates the template for each item in the data. The templating engine lets you use ‘placeholders’ and create ‘live bindings’ between the rendered DOM elements and the data, as well as allow you to attach other ajax components and controls. I want to focus on one of the new features added to the DataView in preview 5, but first, I feel obliged to introduce the DataView control from a basic level, since most of you probably don’t know about it yet. Simple DataView Example As a simple example – lets make up some data. Normally this would come from a web service or some other source, not hard coded, of course. var stockData = [ { symbol: "DJIA" , change: 79.88, value: 9627.48 }, { symbol: "NASDAQ", change: 23.63, value: 2084.02 }, { symbol: "AAAA" , change: -0.22, value: 27.56 }, { symbol: "BBBB" , change: -1.46, value: 82.12 }, { symbol: "CCCC" , change: 0.67 , value: 7.56 } ]; We want to show this stock data in a table, and probably do some formatting to show the values as currency, etc. Without a templating engine, you’d basically either have to painstakingly create DOM elements by hand, or build up a string and use innerHTML. Neither technique is easy to maintain, or are designable by designer tools. Worse, building a string and using innerHTML could net you some XSS vulnerabilities. This is where the templating engine in Microsoft Ajax 4 comes in. <table id="stocks" class="stocks sys-template"> <tr> <td>{{ symbol }}</td> <td>{{ value.localeFormat("c") }}</td> <td>{{ change.localeFormat("c") }}</td> <td>{{ (change/value).format("p2") }}</td> </tr> </table> In the simple form, {{ foo }} represents a placeholder where the value of a field named ‘foo’ from the data items will be. What language is this stuff? Just javascript. So as you can see, this take advantage of the formatting methods in Microsoft Ajax to convert the values to currency. You could write any ole javascript here, of course (unobtrusive javascript alert: yes, you can do it that way too, more on that later). The class “sys-template” is setup to have display:none, so that this chunk of HTML doesn’t actually show up in the markup. That’s the template – it represents what each item should look like. Now to put it to use with the DataView control: function pageLoad() { $create(Sys.UI.DataView, { data: stockData }, null, null, $get("stocks")); } That’s it. The DataView control is given the data, and the template. Everything is hooked up. Here is the result (css not shown): One obvious improvement we could make to this sample is to dynamically style the rows so that stocks going up are green, down, red. You can in fact do that, but I digress. This is just the most basic use of a DataView. I haven’t even mentioned live bindings. And even in preview 4 you could reuse templates across multiple dataviews, and set the placeholder to be something other than the default. Here is an excellent article by Jim Wang which covers some of the other things you could do in Preview 4, including selecting items, and integrating with an ADO.NET DataService. Preview 5 – Dynamic Templates and Dynamic Placeholders Preview 5 introduces a new feature to the DataView control that allows you to dynamically determine the template used for each data item, as well as dynamically determine the placeholder that anchors where it will be inserted. This means each data item can potentially render completely differently, and render into completely different areas of the page, all the while being under the control of a single DataView! What does this mean? Well, say you have a single set of data returned by a service of some kind. But you don’t want to simply list this data all in one place. Some needs to go there, and some over there, depending on the state of each item. A typical example of this might be a data set of forum posts, where some of them are marked as ‘sticky’, and so should be listed first, but the sticky ones aren’t necessarily first in the list of data. How would you normally deal with that? Separate the sticky items into their own data set, or query for them separately? If you are using stored procedures, maybe that means creating a new one or modifying an existing one to support the filtering. Why go through such hoops and database-level manipulations when this is purely a UI problem? If it can’t be solved by your UI tools, perhaps you’re blurring your separation of concerns. So as an experiment, I imagined a list of bloggers. Each blogger may or may not be on Twitter, right? But I want the tweeting and non-tweeting bloggers to be listed separately. Furthermore, the way I display a tweeting blogger and a non-tweeting blogger may be very different. For one, I want to display some of the latest tweets from the tweeting bloggers, and display their Twitter avatar. Mind you, it is certainly possible to use dynamically determined css classes, and to dynamically show/hide regions of content within a template, based on the data item. But that only gets you so far. Sometimes, the differences are too much to neatly define a single template that can represent either kind of data item. This particular example could have been done either way. Maybe I just wasn’t creative enough :) First – let’s define our bloggers. var bloggerList = [ { name: "InfinitiesLoop", author: "Dave Reed", uri: "", twitter: "infinitiesloop" }, { name: "Computer Zen", author: "Scott Hanselman", uri: "", twitter: "shanselman" }, { name: "Random Thoughts", author: "Bob", uri: "" }, { name: "Tales from the Evil Empire", author: "Bertrand Le Roy", uri: "", twitter: "bleroy" }, { name: "The Gu", author: "Scott Guthrie", uri: "", twitter: "scottgu" }, { name: "Some blog", author: "Mr. IDontTwitter", uri: "" }, { name: "Jim Wang's Blog", author: "Jim Wang", uri: "", twitter: "turanuk" }, { name: "James Senior", author: "James Senior", uri: "", twitter: "jsenior" } ]; Each blogger has a blog name, author name, uri, and if they have one – a twitter id. Important to note – the non-twittering bloggers are not at the beginning of the array, they are mixed in with the others. For brevity I’m going to show the declarative way of attaching a DataView control, even though we feel most developers would prefer to keep this stuff separated from their markup. Everything you see here can be done in pure code (imperatively). And we are actively working on some very interesting improvements that make the imperative ways much, much easier than they are in Preview 5, so stay tuned, you won’t want to miss it. Both declarative and imperative approaches are in the sample download at the end of this post. Let’s first define the overall structure we want: <div id="bloggers" class="bloggers" sys:attach="dv" dv:data="{{ bloggerList }}" dv: <div class="notwitter"> Non-twittering Bloggers <ul> <li id="normalph"></li> </ul> </div> <div class="hastwitter"> Twittering Bloggers <ul> <li id="twitterph"></li> </ul> </div> </div> Two divs, one for each kind of blogger. And placeholders for where each should be rendered. A DataView is attached declaratively with sys:attach=”dv” (the ‘dv’ comes from an xml namespace declared on the documents body tag and maps the namespace ‘dv’ to the Sys.UI.DataView class, ‘dv’ is not magical). As each blogger is processed, the ‘itemRendering’ event is fired before anything is instantiated for it. We’ve hooked up a handler for it: function itemRendering(dv, args) { var blogger = args.get_dataItem(); if (blogger.twitter) { args.set_itemTemplate("twitterblogger"); args.set_itemPlaceholder("twitterph"); } else { args.set_itemTemplate("normalblogger"); args.set_itemPlaceholder("normalph"); } } If the blogger has a Twitter id, we set the template to the ‘twitterblogger’ template and tell it to render where the ‘twitterph’ element is. Otherwise, we use the ‘normalblogger’ template and render them where the ‘normalph’ element is. For a ‘normal’ blogger, we just want to render a link to their blog and their name: <ul class="sys-template" id="normalblogger"> <li> <a sys:{{ name }}</a> <span>author: {{ author }}</span> </li> </ul> Pretty simple. For a tweeting blogger, we want to do something slightly different, plus we want to show their last 5 tweets for good measure. JSONP Another feature in Microsoft Ajax 4, I should mention, is JSONP support. And good thing too, because it makes this demo way cooler. Twitter happens to have a JSONP service, and the DataView integrates nicely with the networking support in Microsoft Ajax, giving it JSONP support, too. So getting tweets for someone is just a matter of creating a DataView with the JSONP address as the ‘dataProvider’. So our Blogger DataView is going to actually contain a nested DataView. Here is the ‘twitterblogger’ template: <ul class="sys-template" id="twitterblogger"> <li> <a sys:{{ name }}</a> <span>{{ author }}</span> <ul class="tweets sys-template" sys:attach="dv" dv:autofetch="true" dv: <li> <img class="avatar" sys: {{ text }} </li> </ul> </li> </ul> So, our blogger entry has a nested UL, to which we attach another DataView with the JSONP Twitter url as the target provider. The data returned from Twitter also has information about the Twitter user, like their avatar, so we may as well show that, too. The ‘getTwitterUrl’ call demonstrates that you aren’t limited to just data – you can do stuff with it too. That method simply takes the blogger’s Twitter id and constructs the JSONP service url for their last 3 tweets. That’s it! Here it is in action: Download the sample code here. Also, be sure and check out these other awesome posts about Microsoft Ajax 4. - Bertrand demonstrates how to use templates recurisvely with the DataView to display hierarchical data. - Jim Wang shows how to make MS Ajax 4 compatible with ASP.NET 3.5's UpdatePanel, and some simple ado.net integration. These are based on previous preview releases. - Preview of the DataView (based on Preview 4) by Encosia A sneak peak at ASP.NET AJAX 4.0's client-side templating Encosia - Damien White has an excellent series of articles (based on preview 4) DataView: Sys.Observer: Bindings: - I blogged about another feature in Microsoft Ajax 4, Sys.Observer (based on preview 3 but relevant). Another important difference between the 2.0 and 3.5 versions -- this time, I'm a contributing author. :) My first major technical publication, hopefully more to come. I'm that weird guy on the right....
http://weblogs.asp.net/InfinitiesLoop?PageIndex=2
CC-MAIN-2014-52
refinedweb
1,776
64.1
I am currently working on a simple .csv reader/writer class for an app that I am building and would like some advice or input. The current code seems to work well but I am fairly new to using external files with my programs so I'd like to hear if there is any newer or more efficient way to do this than what I have posted or if there are any major flaws that I have missed. Thanks. Code:import java.io.*; import java.util.ArrayList; public class CSVData { public ArrayList<String[]> readCSV(String filename) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(filename)); ArrayList<String[]> rows = new ArrayList<String[]>(); String line = reader.readLine(); while(line != null) { String[] row = line.split(","); for (int x = 0; x<row.length; x++) { row[x] = row[x].trim(); } rows.add(row); line = reader.readLine(); } return rows; } public void writeCSV(ArrayList<String[]> data, String filename) throws Exception { FileWriter writer = new FileWriter(filename); for (int x = 0; x < data.size(); x++) { String[] line = data.get(x); for (int y = 0; y < line.length; y++) { if (y < line.length-1) { writer.append(line[y]+",\t"); } else { writer.append(line[y]); } } writer.append("\n"); } writer.flush(); writer.close(); } }
http://forums.devshed.com/java-help-9/java-csv-reader-writer-advice-823245.html
CC-MAIN-2015-18
refinedweb
201
67.55
On Sun, 2011-12-18 at 10:43 -0800, Tom Rosmond wrote: > I am trying to run this little makefile on my Scientific Linux > workstation: > all: > ifeq ($(HOST),cedar) > @echo $(HOST) > endif > > and I get this error message when running 'make': > > [2006]cedar /home/rosmond: make > ifeq (cedar,cedar) > /bin/sh: -c: line 0: syntax error near unexpected token `cedar,cedar' > /bin/sh: -c: line 0: `ifeq (cedar,cedar)' > make: *** [all] Error 2 > > It seems to be trying to execute the file as a shell script. I have the > necessary 'tab' prefixes in the lines of the 'all' rule. That's exactly what's happening. All lines prefixed by a TAB characters are passed to the shell. Make doesn't interpret those lines at all except for expanding variable references; everything else is assumed to be shell syntax and is given to the shell to run. This is one of the most fundamental concepts in make: makefiles are a combination of makefile syntax and shell syntax, and understanding which syntax goes where and when it is evaluated by make, or by the shell, is critical for being able to create correct makefiles. Cheers! -- ------------------------------------------------------------------------------- Paul D. Smith <address@hidden> Find some GNU make tips at: "Please remain calm...I may be mad, but I am a professional." --Mad Scientist
http://lists.gnu.org/archive/html/help-make/2011-12/msg00038.html
CC-MAIN-2016-40
refinedweb
218
62.72
Type-safe Web with Kotlin Can everything in our web application be reusable and statically type checked? Everything, from markup to client scripting. Andrey Breslav tells how it is indeed possible with Kotlin. You may have heard about Kotlin. It is a modern programming language that compiles to JVM byte codes and JavaScript. It is designed for industrial use, which means maintainability: static typing enables error detection and automated refactoring, type inference makes for clean and readable code and powerful abstractions facilitate library development. A language isn’t much good if you can’t use it for the web, so in this article, we’ll discuss web programming in Kotlin. Sure, you can write the same servlets as in Java, and you can use jQuery in Kotlin too, but there’s something else we’ll focus on. But first, let me make a quick detour and tell you a few things about how people make web applications nowadays. Even a moderate web application involves many technologies, quite a few of which are associated with its own language. It’s usually a minimum of five languages involved: - HTML for markup; - CSS for styling; - Java for server-side business logic (we will limit ourselves to the Java platform in this article); - JSP or some other template engine for templating; - and, finally, JavaScript for client-side scripting. So, we have five languages there. If this fact alone makes you a little uncomfortable, read on and we’ll come back to it, but first, let’s have a look at the very core: HTML and CSS. One very special thing about HTML and CSS is that they are not programming languages, but rather something more like data formats. In particular, neither of these two languages have any means of abstraction or code reuse. (To be fair, we should note that HTML can reuse CSS definitions, but there’s no reuse of CSS inside CSS and no reuse of HTML inside HTML.) I’ll say it again: two of the most popular languages in the world allow no code reuse whatsoever. The software engineering alarms inside your head should have gone off by this point; does it mean that we copy-and-paste that markup all the time? Exactly. Many people recognize that this is a problem. Solutions come in the form of better languages. For example, most template engines provide some means of markup reuse (although it’s a pain in many cases). And there are LESS and SASS that bring to CSS such bleeding-edge features like named constants for example. Let me explain. If you are using plain CSS, every time you describe, say, a color, Cantaloupe, for example, you enter a literal constant #ffcc66 (or #fc6). Perhaps you have 36 occurrences of this constant all over your CSS. Now, you want to change some of them to something else and you’re not liking your job so much this afternoon. Obviously the right way to handle this is to define named constants corresponding to the roles of that color, so that the value needs to be changed only once per role. A named constant abstracts over a value and allows for code reuse. CSS does not have named constants. We have to use some preprocessor like LESS to properly reuse our CSS code. There are whole websites that generate CSS for you. You say something like “I want a button of that shape and that color,” and get a CSS snippet. So far so good. But then you copy-and-paste that snippet to your stylesheet. There’s no library that defines a component named Button with well-typed properties shape and color, CSS simply does not support that. Instead, there’s a bunch of text fields somewhere on the web that does what a library should do: provides a higher level of abstraction. But importantly, it can’t provide code reuse. To summarize: web programming lacks means of abstraction and code reuse. On top of that, when your application gets bigger (and this is when development costs start to matter), other problems come into play: the only way to catch bugs in web applications is testing. Even very stupid bugs, like misspelling a name. Don’t get me wrong: one has to test, there’s no way around it. But there are somewhat trivial safety properties that show up all over the place, and writing tests for all of them is just too much work. Having to test for trivial things a lot is too expensive. Trivial errors should be detected automatically by the compiler. Yes, I’m talking about static typing. Dynamic languages are cool, but I also know that modern static languages are even cooler, as they give you nearly the same flexibility, but in addition they give you safety. In a static language you can have automated refactorings, accurate code completion and other IDE features that save you time and effort en masse. You may have seen it coming: Kotlin is a statically typed language that has very good means of abstraction and code reuse, so why don’t we use Kotlin instead of those five languages mentioned above? The rest of this article will describe how this can be done. We will focus on principles and not any particular implementation, but I’ll give you a reference so that you have something to get your hands on. Kara is an open source web framework written entirely in Kotlin. It unifies many aspects of a web application in the form of DSL-like APIs, so that every bit of your markup or any other code is statically checked and can be reused. Again, this article is not about this particular framework, but I’ll occasionally use examples from Kara to illustrate the principles under discussion. Birds-eye view First, let’s see what it means to “unify many aspects of a web application in the form of an API”. Listing 1shows what this mark up looks like in Kara. Kara mark up html { head { title(“Example”) } body { ul { li { +“Item 1” } li { +“Item 2” } } } } Ends This code creates a tree of tags that can be serialized to textual form upon request. You can see it is almost HTML, only with curly brackets instead of angle ones (and somewhat fewer of them). In fact, this is just a bunch of function calls, absolutely normal code written in Kotlin. It is called a type-safe builder, very much like builders Groovy is famous for, but statically checked. If you, for example, put a li outside ul, you’ll have a compilation error: body { li { ... } // Compilation error here } Builders can handle everything your templates do. Firstly, they can generate arbitrarily complex HTML by using loops. For example, to generate a list of colors, we can write: ul { for (color in listOf(“red”, “green”, “blue”)) { li { +color } } } You can also reuse parts of your markup by simply extracting code into functions, for example a function that renders a list of strings, as shown here: <pre>fun BodyTag.list(vararg items: String) { ul { for (x in items) li { +x } } } body { list(“red”, “green”, “blue”) list(“cyan”, “magenta”, “yellow”) } Ends We’ll get to how it works later, but now let’s see what a stylesheet looks like. ul { listStyleType = circle margin = 10.px } This even looks very much like CSS, but again, it is type-safe meaning we cannot use an undefined attribute or put a wrong value in. What’s even more important is that it is code, which means that we can use arbitrarily complex arithmetic and/or named constants. val BASE_MARGIN = 5.px // named constant ul { listStyleType = circle margin = BASE_MARGIN * 2 // arithmetic } It also means that we can extract a part of this code into a function, as shown here. // Define a function fun StyledElement.doubleMargin() { margin = BASE_MARGIN * 2 } ul { listStyleType = circle doubleMargin() // use the function } Ends So, we clearly get reuse and type-safety. Now, let’s start digging to understand how all this works. Inside a Builder Now we’re ready to see how type-safe builders work. Let me first remind you that it is not a built-in language construct, but rather a normal Kotlin API. To make this API look like a declarative DSL we need two things: lambdas and extension functions. Lambdas Lambdas are sometimes called anonymous functions. In other words, they are expressions whose values are functions. To filter a list, you need to pass in a predicate, i.e. a piece of code that tells the filter() function which elements to keep and which to remove: users.filter({u -> u.age >= 21}) In Kotlin, lambdas are delimited by curly braces; inside a lambda an arrow (“->”) separates a list of parameter names from the body. In the example above the lambda expression {u -> u.age >= 21} corresponds to a function that takes one parameter named u (its type is inferred from the context) and returns a boolean result of comparison. This function is passed as a parameter to the filter() function. The filter() function is good at explaining what lambdas are for, but is too complex to be the first example to explain, so we will take a simple function now: let(1 + 2, { x -> println(x * x) }) The let() function is very simple: it takes its first argument and passes it to the second argument (which is a lambda). The example above prints “9”. There is a nice syntactic rule that allows you to write the last lambda outside of the parentheses: let(1 + 2) { x -> println(x * x) } This code is doing exactly the same as the previous example, but the lambda now looks more like a body of some “language construct”. We borrowed this syntactic convention from Groovy where it works very well. Now let’s look at how let() is defined. First, a simple version that works only with numbers: fun let(x: Int, f: (Int) -> Unit) { f(x) } The body of let is rather trivial: simply apply f() to x. Let’s take a close look at the declaration of f: f: (Int) -> Unit Since this is a parameter whose value is a function, it has a special kind of type, a function type. Function types have the form of (parameter types) -> return type, so f() takes one parameter of type Int and returns a value of type Unit (which means “no interesting value”, very much like void). This is why we can call it as f(x) inside let() and this is why we can pass a lambda as its value. Now, let’s make our function more useful and allow any type T, not only Int, for parameter: fun <T> let(x: T, f: (T) -> Unit) { f(x) } We simply declared a generic parameter T and used it instead of Int. No big deal. Functions like let(), that take other functions as an arguments, are called higher-order functions, and they are very important as means of abstraction. Now, we move on to our next subject: extension functions. Extension functions In mainstream languages, extension functions were introduced by C#. Their essential purpose is to extend an API of a class or interface, without it having to change (and thus, own) its class or interface. For example, it means that you can create an extension function that returns the last character of a string: fun String.last(): Char { return this.charAt(this.size - 1) } This function is defined somewhere outside the String class, and it does not change the class in any way, but the language allows you to call it as if it were a member: println(“abc”.last()) // prints “c” In fact, you are looking at a simple static utility method, like dozens of those you have in your Java projects: public class StringUtil { public static char last(String s) { return s.charAt(s.length() - 1) } } Out last() defined above is compiled to exactly this, but the syntax is nicer and it enables discovery by code completion. In Kotlin, an extension function shows up when you hit Ctrl+Space after a dot. But let’s take a closer look: what turns a function into an extension is the “String.” in front of its name? This means that this function can be called on strings. To access the string it is called on, we can use “this” keyword, as if we were inside the class (but no privileges like access to private members). Of course, “this” can be omitted (and it is important for builders): fun String.last(): Char { return charAt(size - 1) } Now we have the two components, lambdas and extensions ready. Let’s mix them to get a builder. The mix To approach it gently, we’ll start by slightly changing our let() function from above by calling the new version “with”. Let’s turn let()’s parameter f into an extension: fun <T> with(x: T, f: T.() -> Unit) { x.f() } The change is very small. We write “T.() -> Unit” instead of “(T) -> Unit”, and f() turns into an extension function, so that we can call it as “x.f()”. Now let’s look at how we can use this new function: with(StringBuilder()) { this.append(“Hello”) } We then need to create a new StringBuilder object (there’s no new operator in Kotlin) and pass it to with(). The lambda sees this StringBuilder under the name “this” and calls its append(). Of course, “this” can be omitted: with(StringBuilder()) { append(“Hello”) } Now you can see that the lambda (the “body” of with()) has a different context: it can call methods of StringBuilder() without explicitly mentioning the receiver. Arbitrary constructs may be used as well. with(StringBuilder()) { append(“List:n”) for (x in list) { append(x) append(“n”) } } This is almost a builder already as we have all the components. Now, let’s use them and create a real builder for a tiny subset of HTML. HTML Builder The key thing with builders is tracking context. As we have seen in the with() function, the context can be tracked by using extension lambdas. So, with(x) {…} makes x the context of whatever comes inside the curly braces. Let’s use the same principle to build a tree of HTML tags. For simplicity we will use only three tags: body, ul and il, and text elements (representing free text inside an HTML page). First, we’ll have an abstract class Element representing any element of an HTML document (a tag or text): abstract class Element { val children = ArrayList<Element>() } All it does is holds its children. Now, Body and Text are derived from it, as shown here: open class Body: Element() { fun text(s: String) { children.add(Text(s)) } ... } class Text(val text: String): Element() Ends We are now ready to create a root function for our builder, the one that creates a root tag. And in our case it is body(): fun body(init: Body.() -> Unit): Body { val body = Body() body.init() return body } Calling this function is analogous to calling “with(Body()) {…}”, but it’s shorter and cleaner: body { text(“Hello”) // adds a new Text element to body’s children list text(“world”) // adds another Text element to the children list } Now, let’s add the UL tag: class UL: Element() { ... } UL should be available inside Body, so we need to add the corresponding builder function to the Body class: open class Body: Element() { ... fun ul(init: UL.() -> Unit) { val ul = UL() children.add(ul) ul.init() } } Ends The ul() function is analogous to body(), with one difference: it does not return a new tag element, but rather adds it to the children list of Body: body { text(“List:”) ul { // a new instance of class UL is added to body.children } } In the same manner we can have LI inside UL: class UL: Element() { fun li(init: LI.() -> Unit) { val li = LI() children.add(li) li.init() } } class LI: Body() Ends The pattern is the same: create a new LI, initialize it with the lambda passed to li() function, and add to the children list of UL. Note that LI extends Body and hence gets all of its members: you can create text elements and lists inside LI (but not directly inside UL): body { text(“List:”) ul { li { text(“First”) } li { text(“Second”) } } } Last question: how does Kotlin know that li() calls correspond to UL, while ul() corresponds to body()? This is crucial for our builder, because we want elements added to appropriate children lists and form a proper tree. The answer is roughly that it looks for the innermost “this” that is applicable, so when you say li(), the compiler looks up the syntax tree and finds the nearest “this” that has a li(). If there’s no such “this”, i.e. you are trying to add a LI directly to Body, the compiler reports an error. Add a few hundred tags and you have a complete DSL for HTML templates. In fact, it is rather easy to generate all those tag classes once and for all, and this is one of the things done by creators of Kara. The CSS is done analogously. Now let’s revisit the reuse examples that were left unexplained in the first section: fun Body.list(vararg items: String) { ul { for (x in items) li { +x } } } body { list(“red”, “green”, “blue”) list(“cyan”, “magenta”, “yellow”) Ends The trick is, again, that an extension function tracks the context for you: when you call list(), the compiler looks for the nearest “this” that has such a member, or if there’s no member, such an extension. When list() is invoked in this example it takes the current Body instance as its receiver parameter, and passes it to the ul() call. Summary Contemporary web programming lacks means of reuse and abstraction as well as type safety. Contemporary web developers deserve better. The situation can be improved by using a modern programming language such as Kotlin and leveraging its type system and abstractions. We demonstrated this approach by creating a type-safe builder DSL inside Kotlin to handle HTML generation, outlined how other aspects of a web application can be addressed in similar ways. A full-scale implementation of the concepts presented above is being created in the Kara project. Examples used in this article are available on GitHub here and here.
http://jaxenter.com/type-safe-web-with-kotlin-106187.html
CC-MAIN-2015-18
refinedweb
3,063
69.62
- >...]] DESCRIPTION¶Updates).¶<repository> <refspec>... The <src> is often the name of the branch you would want to push, but it can be any arbitrary "SHA-1 expression", such as master~4. The object referenced by <src> is used to update the <dst> reference on the remote side. Whether this is allowed depends on where in refs/* the <dst> reference lives as described in detail below, in those sections "update" means any modifications except deletes, which as noted after the next few sections are treated differently. The refs/heads/* namespace will only accept commit objects, and updates only if they can be fast-forwarded. The refs/tags/* namespace will accept any kind of object (as commits, trees and blobs can be tagged), and any updates to them will be rejected. It’s possible to push any type of object to any namespace outside of refs/{tags,heads}/*. In the case of tags and commits, these will be treated as if they were the commits inside refs/heads/* for the purposes of whether the update is allowed. I.e. a fast-forward of commits and tags outside refs/{tags,heads}/* is allowed, even in cases where what’s being fast-forwarded is not a commit, but a tag object which happens to point to a new commit which is a fast-forward of the commit the last tag (or commit) it’s replacing. Replacing a tag with an entirely different tag is also allowed, if it points to the same commit, as well as pushing a peeled tag, i.e. pushing the commit that existing tag object points to, or a new tag object which an existing commit points to. Tree and blob objects outside of refs/{tags,heads}/* will be treated the same way as if they were inside refs/tags/*, any update of them will be rejected.. Hooks and configuration can also override or amend these rules, see e.g. receive.denyNonFastForwards in githooks(5). The special refspec : (or +: to allow non-fast-forward updates) directs Git to push "matching" branches: for every branch that exists on the local side, the remote side is updated if a branch of the same name already exists on the remote side. tag <tag> means the same as refs/tags/<tag>:refs/tags/<tag>. -> This option overrides this restriction if the current value of the remote ref will the remote ref is updated only if the "lease" is still valid. --force-with-lease alone, without specifying the details, will protect all remote refs that are going to be updated by requiring their current value to be the same as the remote-tracking branch we have for them. -). If <expect> is the empty string, then the named ref must not already exist.. A general note on safety: supplying this option without an expected value, i.e. as --force-with-lease or --force-with-lease=<refname> interacts very badly with anything that implicitly runs git. -f, --force This flag disables these checks, and can cause the remote repository to lose commits; use it with care.). See the <refspec>... section above for details. --repo=<repository> -u, --set-upstream --[no-]thin -q, --quiet -v, --verbose --progress --no-recurse-submodules, --recurse-submodules=check|on-demand|only|no --[no-]verify -4, --ipv4 -6, --ipv6¶The (space) + - * ! = summary For a failed update, more details are given: rejected remote rejected remote failure from to reason NOTE ABOUT FAST-FORWARDS¶When¶git push git push origin The default behavior of this command when no <refspec> is given can be configured by setting the push option of the remote, or the push.default configuration variable. For example, to default to pushing only the current branch to origin use git config remote.origin.push HEAD. Any valid <refspec> (like the ones in the examples below) can be configured as the default for git push origin. git push origin : git push origin master git push origin HEAD git push mothership master:satellite/master dev:satellite/dev See the section describing <refspec>... above for a discussion of the matching semantics. git push origin master:refs/heads/experimental git push origin :experimental git push origin +dev:master:
https://manpages.debian.org/unstable/git-man/git-push.1.en.html
CC-MAIN-2020-40
refinedweb
689
51.18
(For more resources related to this topic, see here.) Mission Briefing In this project we will be creating a HUD that can be used within a Medieval RPG and that will fit nicely into the provided Epic Citadel map, making use of Scaleform and ActionScript 3.0 using Adobe Flash CS6. As usual, we will be following a simple step—by—step process from beginning to end to complete the project. Here is the outline of our tasks: Setting up Flash Creating our HUD Importing Flash files into UDK Setting up Flash Our first step will be setting up Flash in order for us to create our HUD. In order to do this, we must first install the Scaleform Launcher. Prepare for Lift Off At this point, I will assume that you have run Adobe Flash CS6 at least once beforehand. If not, you can skip this section to where we actually import the .swf file into UDK. Alternatively, you can try to use some other way to create a Flash animation, such as FlashDevelop, Flash Builder, or SlickEdit; but that will have to be done on your own. Engage Thrusters The first step will be to install the Scaleform Launcher. The launcher will make it very easy for us to test our Flash content using the GFX hardware—accelerated Flash Player, which is what UDK will use to play it. Let's get started. Open up Adobe Flash CS6 Professional. Once the program starts up, open up Adobe Extension Manager by going to Help | Manage Extensions.... You may see the menu say Performing configuration tasks, please wait.... This is normal; just wait for it to bring up the menu as shown in the following screenshot: Click on the Install option from the top menu on the right—hand side of the screen. In the file browser, locate the path of your UDK installation and then go into the Binaries\GFx\CLICK Tools\ folder. Once there, select the ScaleformExtensions.mxp file and then select OK. When the agreement comes up, press the Accept button; then select whether you want the program to be installed for just you or everyone on your computer. If Flash is currently running, you should get a window popping up telling you that the program will not be ready until you restart the program. Close the manager and restart the program. With your reopened version of Flash start up the Scaleform Launcher by clicking on Window | Other Panels | Scaleform Launcher. At this point you should see the Scaleform Launcher panel come up as shown in the following screenshot: At this point all of the options are grayed out as it doesn't know how to access the GFx player, so let's set that up now. Click on the + button to add a new profile. In the profile name section, type in GFXMediaPlayer. Next, we need to reference the GFx player. Click on the + button in the player EXE section. Go to your UDK directory, Binaries\GFx\, and then select GFxMediaPlayerD3d9.exe. It will then ask you to give a name for the Player Name field with the value already filled in; just hit the OK button. UDK by default uses DirectX 9 for rendering. However, since GDC 2011, it has been possible for users to use DirectX 11. If your project is using 11, feel free to check out and use DX11. In order to test our game, we will need to hit the button that says Test with: GFxMediaPlayerD3d9 as shown in the following screenshot: If you know the resolution in which you want your final game to be, you can set up multiple profiles to preview how your UI will look at a specific resolution. For example, if you'd like to see something at a resolution of 960 x 720, you can do so by altering the command params field after %SWF PATH% to include the text —res 960:720. Now that we have the player loaded, we need to install the CLIK library for our usage. Go to the Preferences menu by selecting Edit | Preferences. Click on the ActionScript tab and then click on the ActionScript 3.0 Settings... button. From there, add a new entry to our Source path section by clicking on the + button. After that, click on the folder icon to browse to the folder we want. Add an additional path to our CLIK directory in the file explorer by first going to your UDK installation directory and then going to Development\Flash\AS3\CLIK. Click on the OK button and drag—and—drop the newly created Scaleform Launcher to the bottom—right corner of the interface. Objective Complete — Mini Debriefing Alright, Flash is now set up for us to work with Scaleform within it, which for all intents and purposes is probably the hardest part about working with Scaleform. Now that we have taken care of it, let's get started on the HUD! As long as you have administrator access to your computer, these settings should be set for whenever you are working with Flash. However, if you do not, you will have to run through all of these settings every time you want to work on Scaleform projects. Creating our HUD Now that Flash is set up, let's actually create our HUD menu. Engage Thrusters Now let's start create our HUD menu! Inside the main menu of Adobe Flash, create a new ActionScript 3.0 project by going to Create New | ActionScript 3.0. In the PROPERTIES section of the Properties inspector, set the Size to 1280 x 720 by clicking on the existing numbers and typing in the new values and then hitting Enter. Above the stage, find the zoom scaling that currently says 100% and change it so that you can see everything within the white box. Alternatively, you can use Ctrl + 1. Access the Library section by clicking on the tab next to the Properties tab. Outside of Flash, go to the project's assets folder. Select all of the files and drag—and—drop them into the Library tab. Wait for the import dialog to finish and you should see all of the files placed there. From there, go to the Timeline section at the bottom of the screen and create a new layer by either clicking on the new layer button at the very bottom—left corner of the program or by right—clicking on Layer1 and selecting New Layer. Double—click on the layer on the top and change its name to ActionScript. Double—click on the other layer and give it the name of Lifebar. Create two more layers, one above the Lifebar layer with the name of Overlay and one below with the name of Background. You can drag—and—drop layers to put them where you want them. Click on the first keyframe of the Background layer. Drag—and—drop the Lifebar_background.png image to the top—left corner of the stage. Continue to place the Lifebar_overlay.png file in the Overlay layer and the Lifebar_health.png file into the Lifebar layer between them. Now, we won't be touching the overlay or backgrounds anymore, so on both of those layers click on the dots under the little lock for those layers, to lock them so that we can't change it anymore. You can notice where to click and where the locks are in the following screenshot: Next, in order to reference our lifebar in code, we need to have some way to reference it. In order to do that, we're going to have to make our graphic into a movie clip. Thankfully, it's very easy. Click to select and then right—click on the lifebar object and select Convert to Symbol... (or press F8). There, in the Name section, type in lifebarMC and confirm that the Type value is Movie Clip. Once that is set, click on OK. Click on the Properties tab with the lifebar selected. In the textbox that has the instance's name in it, change the value to lifebar. Click on the Lifebar layer and then click on our health image. Then select the Free Transform tool by either clicking on the third icon on the Tools panel or by pressing the Q key (the icon selected in the following screenshot on the far right). You should see a white circle in the middle of our image; this is the point at which scaling will begin. Click and drag that circle to the far left of the image on the x axis and to the middle of the image on the y axis. If you'd like to see how scaling changes depending on where the white dot is, press Ctrl + T to open up the transform tool and change the value of the X scaling. Just make sure it's set to 100 before you move to the next step. Save your project by going to File | Save, and type in a name of your choice (I used hotshot_hud). Click on the stage once again and access the Properties inspector. Under Publish in Class, type in the same name (hotshot_hud). Afterwards, click on the pencil beside it and you should see the following warning: Click on the Test with: GFxMediaPlayerD3d9 button to start up our program. After it has run, close it along with the console window that opened up with it. Click on the pencil icon again and it may ask what to open with. Select Flash Professional and click OK. You should see some code in the pop—up window already written for us. Save that file (by hitting Ctrl + S) with the filename given to you, in the same folder as the .fla file (hotshot_hud). Replace the text in the file with the following code snippet: package { // Needed for the stage importflash.display.MovieClip; // Allows us to use Scaleform importscaleform.gfx.Extensions; //Allows us to use the Event.ENTER_FRAME event listener importflash.events.Event; // Declaring the Document class public class hotshot_hud extends MovieClip { // Variables that we will be using to show the // player's current and max health public static var currentHealth:int = 100; public static var maxHealth:int = 100; //Constructor will be called the first frame of the game public function hotshot_hud() { // Enables Scaleform Extensions.enabled = true; // Adds an event so that the Update function will // be called every single frame. addEventListener(Event.ENTER_FRAME,this.Update); } // Code that we want to run every frame of the game function Update(event:Event) { // Update our life's scale to reflect the current // ratio of currentHealth to maxHealth lifebar.scaleX = currentHealth/maxHealth; } } ) Save your project by hitting Ctrl + S on both files and then click on the Test with: GFxMediaPlayerD3d9 button on the Scaleform Launcher to start up our program. Objective Complete — Mini Debriefing In a very simple way, we have created a good—looking HUD within Flash that we will be using in UDK with a few short steps! Importing Flash files into UDK Now that we have our content, let's bring it in! Engage Thrusters Let's now start importing Flash files into UDK. UDK can only import Flash files that are within a specific folder. Inside your file browser, go to the folder with your .fla and .as files. In that folder, you should see a file with a .swf extension. Copy that file and go to your UDK installation folder (UDKGame\Flash\) and create a new folder called Hotshot. Inside that folder, paste the .swf Flash movie file. You must put Flash files within the UDKGame\Flash\ folder or a subfolder of that folder. You can name the subfolder however you'd like. Start up UDK again. Open up the Content Browser window and click on the Import button. Find the movie file and click OK. You will notice that the Import dialog already sets the package name to Hotshot, so just say OK and save this package. With the movie selected, open up Kismet. Create a Level Loaded event by right—clicking and going to New Event | Level Loaded. To the right—hand side of that, create an Open GFx Movie action by right—clicking and gong to New Action | GFx UI | Open GFx Movie. Connect the Loaded and Visible outputs from the Level Loaded event to the In input of the Open GFx Movie action. Create a player variable for Player Owner by right—clicking and going to New Variable | Player | Player, and in the Properties window uncheck the All Players option. Create a new object variable for Movie Player by right—clicking on the pink arrow and selecting Create New Object Variable. Go back into the Content Browser window and select the SwfMovie that we imported previously. Back in Kismet, click on the Open GFx Movie action to see its properties; and click on the green arrow in the Movie property to see the value SwfMovie'Hotshot.hotshot_hud' be filled in. Next, create a Get Property action by right—clicking and going to New Action | Object Property | Get Property. Under the Target section, create another Player 0 variable. In the Int section, create a new integer variable. Click on the action to access its properties. Under Property Name, type Health. Connect the Success output of the Open GFx Movie action to the In input of the Get Property action. Create a delay of 0.2 seconds in the connect by right—clicking on the black square on the In input of the Get Property action and selecting Set Activate Delay. To the right—hand side of that, create a GFx SetVariable action by right—clicking and going to New Action | GFx UI | GFx SetVariable. Connect the Value section to the Int section we created in the Get Property action and the Movie Player section of the GFx SetVariable action to the Movie Player section of the Open GFx Movie action. In the action's properties, set the Variable value to hotshot_hud. currentHealth. Connect the Out output of the Get Property action to the In input of the GFx SetVariable action. Then connect the Out output of the GFx SetVariable action to the In input of the Get Property action. For a view of the entire Kismet sequence, please look at the following screenshot: Build your project by going to Build | Build All. Save your game by going to File | Save All, and run our game by going to Play | In Editor. Objective Complete — Mini Debriefing And with that, our HUD is now fully functional. As our player gains and loses health, the HUD will coincide with that value. Dropping the Kismet we created into a level will work when the HUD's visuals make a lot of sense. Or not...but it still works perfectly. Mission Accomplished One can clearly see after this mission how useful having Scaleform is and how powerful a tool it can be. Specifically, we just set Flash up so that we could implement something using Scaleform by adding the Scaleform Launcher to Flash, and imported the Scaleform libraries for our use. After that, we imported custom art assets into Flash and created a Document class to hold our code, which will update our health in every frame. Once we published our project, we went back into UDK and imported the file into a level and added Kismet to load the movie and use it as our main HUD, giving us a much more polished HUD than we created previously. Also, it gave you a taste of what can be done using Scaleform, which can be easily expanded upon. Let's take one final look at what we have accomplished: Summary In this article we learned about how to create an HUD that can be used within a Medieval RPG and will fit nicely into the provided Epic Citadel map making use of Scaleform and ActionScript 3.0 using Adobe Flash CS6. Resources for Article : Further resources on this subject: - Configuration and Handy Tweaks for UDK [Article] - Creating Virtual Landscapes [Article] - Unreal Development Toolkit: Level Design HQ [Article]
https://www.packtpub.com/books/content/creating-custom-hud
CC-MAIN-2015-22
refinedweb
2,686
71.34
You need to know about React JS ReactJS is a javascript library, so no, it’s not a framework. Its primary purpose is to assist in creating interactive and stateful UI components that developers can reuse. If you consider a software design pattern like MVC (Model–view–controller), you can consider React as the application’s view. React can also work on the server-side and render a page on the server before displaying it to the client. To work with ReactJS, we need a package manager like NPM or Yarn to install all the files en dependencies required. We can use the command create-react-app to quickly start developing our application since it creates an environment with all the basics that we need. We have to set the name of the application when using that command. npx create-react-app my-first-reactapp cd my-first-reactapp npm start //If using npm yarn start //If using yarn React Environment Setup in this section, we will learn how to set up an environment for the successful development of ReactJS application. Pre-requisite for ReactJS - NodeJS and NPM - React and React DOM - Webpack - Babel React Features Currently, ReactJS gaining quick popularity as the best JavaScript framework among web developers. It is playing an essential role in the front-end ecosystem. The important features of ReactJS are as following. - JSX - Components - One-way Data Binding - Virtual DOM - Simplicity - Performance Virtual DOM One of the main characteristics of ReactJS is that it makes a copy of the DOM (Document Object Model) called ‘Virtual DOM (VDOM)’ to work within your application. React makes updates to the UI much faster and fluid by updating just the components that need to be updated and not the whole page. JSX all of the React components have a render function. The render function specifies the HTML output of a React component. JSX(JavaScript Extension), is a React extension that allows writing JavaScript code that looks like HTML. In other words, JSX is an HTML-like syntax used by React that extends ECMAScript so that HTML-like syntax can co-exist with JavaScript/React code. JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the same file where you write JavaScript code, then the preprocessor will transform these expressions into actual JavaScript code. Just like XML/HTML, JSX tags have a tag name, attributes, and children. <header> <Component1 /> { console.log(“Data Validation”); } </header> Component One of the Key elements of React is Components. If you’re going to work with this library, you need to think about components and how they will interact with each other. import React from “react”; const Component1 = () =>{ return ( <h1> This is a basic component </h1> ); }; export default Component1; Functional Component a functional component is also known as a stateless component because they do not hold or manage the state. It can be explained in the below example. Class Component The class component is also known as a stateful component because they can hold or manage local state. It can be explained in the below example. React Events just like HTML, React can perform actions based on user events. React has the same events as HTML: click, change, mouseover, etc. Adding Events React events are written in camelCase syntax: onClick instead of onclick. React event handlers are written inside curly braces: onClick={shoot} instead of onClick="shoot()". <button onClick={shoot}>Take the Shot!</button>
https://masudranawd2019.medium.com/you-need-to-know-about-react-js-8c9e7aaaf5cb?responsesOpen=true&source=user_profile---------1-------------------------------
CC-MAIN-2022-33
refinedweb
577
54.22
Back to index 00001 /* x86-64-specific implementation of profiling support. 00002 Copyright (C) 2002 Free Software Foundation, Inc. 00003 This file is part of the GNU C Library. 00004 Contributed by Andreas Jaeger <aj@suse.de>, 2002. <sysdep.h> 00022 00023 /* We need a special version of the `mcount' function since for x86-64 00024 so that we do not use __builtin_return_address (N) and avoid 00025 clobbering of register. */ 00026 00027 00028 /* We must not pollute the global namespace. */ 00029 #define mcount_internal __mcount_internal 00030 00031 void mcount_internal (u_long frompc, u_long selfpc); 00032 00033 #define _MCOUNT_DECL(frompc, selfpc) \ 00034 void mcount_internal (u_long frompc, u_long selfpc) 00035 00036 00037 /* Define MCOUNT as empty since we have the implementation in another 00038 file. */ 00039 #define MCOUNT
https://sourcecodebrowser.com/glibc/2.9/sysdeps_2x86__64_2machine-gmon_8h_source.html
CC-MAIN-2016-44
refinedweb
124
56.66
The network utilities function library is a set of OmniMark functions that provides functions for: Some network applications send or receive messages that contain numbers in binary form. Computers often represent numbers in binary form as 32-bit values. 32-bit numbers consist of 4 bytes or octets. Different kinds of computers may put these bytes in different orders. When a 32-bit number is transmitted from one computer to another (usually as part of a larger message), both computers must agree on the order of the bytes. Network ordering is a standard way of ordering the bytes in a 32-bit binary number. It means that the first byte will be the most significant (or highest order) byte of the number, and the last will be the least significant (or lowest order) byte. (To convert integers to and from the native binary format, see the "b" format command and the binary operator.) This function library includes the following files: The OMNETUTIL library is packaged as a module. To use OMNETUTIL, you must import the OMETUTIL module into your program using a statement like this: import "omnetutil.xmd" prefixed by netutil. Note that the prefix "netutil.", which is attached to all functions, constants, and opaque data types exported by this library, is set in this statement and can be changed. For readability, we recommend that you always use the standard prefix when importing modules supplied by OmniMark.
http://developers.omnimark.com/docs/html/library/51.htm
CC-MAIN-2017-34
refinedweb
237
54.63
Angular is a new version of the AngularJS framework, developed by Google. It comes with a complete rewrite, and various improvements including optimized builds and faster compile times. In this Angular 5 tutorial, we are going to build a notes app from scratch. If you’ve been waiting to learn Angular 5, this tutorial is for you. The final source code for the app can be found here. There are two major versions of the framework: AngularJS (version 1) and Angular (version 2+). Since version 2, Angular is no longer a JavaScript framework, so there’s a huge difference between them, warranting a fundamental name change. Should I Use Angular? It depends. Some developers will tell you that it’s better to use React and build your own components without much additional code. But that may be a problem, too. Angular is a fully integrated framework that allows you to start working on your project quickly without thinking about which libraries to select and how to deal with everyday problems. I think of Angular as being for the front-end, as RoR is for the back-end. TypeScript If you don’t know TypeScript, don’t be scared. Your JavaScript knowledge is enough to learn TypeScript quickly, and most modern editors are quite effective in helping with that. The most preferable options nowadays are VSCode and any of the JetBrains IntelliJ family (e.g., Webstorm or, in my case, RubyMine). For me, it’s preferable to use a smarter editor than vim, as it will give you an extra heads-up on any mistakes in the code as TypeScript is strongly typed. Another thing to mention is that Angular CLI with its Webpack takes care of compiling TS to JS, so you shouldn’t let the IDE compile it for you. Angular CLI Angular now has its own CLI, or command line interface, which will do most of the routine operations for you. To start using Angular, we have to install it. It requires Node 6.9.0 or higher as well as NPM 3 or higher. We are not going to cover their installation for your system, as it’s better to find up-to-date documentation for installation on your own. Once they are both installed, we are going to install Angular CLI by running the following: npm install -g @angular/cli After the installation is successful,] 🔍 Resolving packages... [2/4] 🚚 Fetching packages... [3/4] 🔗 Linking dependencies... warning "@angular/cli > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]". warning "@angular/cli > @angular-devkit/schematics > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]". [4/4] 📃 Building fresh packages... success Saved lockfile. ✨ Done in 44.12s. Installed packages for tooling via yarn. Successfully initialized git. Project 'getting-started-ng5' successfully created. After that’s done, we can ask. If we navigate our browser to that link, it will be displayed as pictured here: So, what is actually happening here? Angular CLI runs webpack dev server, which renders our app on the next free port (so that you can run multiple apps on the same machine), with live reload. It also watches for every change in the project source and recompiles all changes, after which it asks the browser to reload the open page. So by using Angular CLI, we are already working in a development environment without writing a line of configuration or actually doing anything. But we’re just getting started here… Components We have our empty app running. Let’s talk about app composition in Angular. If you have some background in AngularJS, you know there were controllers, directives, and components that were somehow like directives but simpler, to allow you to upgrade to Angular 2. For those who don’t have that wonderful experience of having to choose between them and figure out what goes where, don’t worry. It’s mostly just components nowadays. The component is the most basic building block in the Angular world. Let’s look at the code that was generated for us by Angular CLI. First, here’s index.html: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>GettingStartedNg5</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html> It looks like the kind of markup you see every day. But there’s a special tag, app-root. How does Angular make this work, and how can we know what’s happening inside it? Let’s open the src/app directory and see what’s there. You can look at the ng new output form earlier here or open it in your chosen IDE. You will see that we have app.component.ts there with the next bit (this may vary depending on how recent your version of Angular is): import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; } @Component(...) here looks like a function call… What is it? This is TypeScript decorator, and we will talk about that a bit later. For now, let’s just try to understand what it’s doing, with passed parameters like selector being used to generate our component declaration. It’s just going a lot of boilerplate work for us and giving back our component declaration in its working form. We don’t have to implement additional code to support any of the decorator’s params. It’s all handled by the decorator. So, generally, we call it factory methods. We already saw app-root in our index.html. Here’s how Angular knows how to find the component corresponding to our tag. Obviously, templateUrl and styleUrls define where Angular should take our markup and CSS from. There are a lot more params for the component decorator, and we are going to use some of them in our new app, but if you want a full reference, you can always look here. Let’s look into that component’s markup: <!--The content below is only a placeholder and can be replaced.--> <div style="text-align:center"> <h1> Welcome to {{ title }}! <> So, aside from embedding the Angular Logo as an SVG, which is pretty neat, this seems like typical everyday markup as well. Aside from one thing ( Welcome to {{ title }}!), if we look at our component code again, we will see title = 'app';. So, if you already have some practice in template languages or have worked with AngularJS, it’s pretty obvious what’s happening here. If you don’t know, this is called Angular Interpolation, by which the expression inside the double curly braces is being pulled from our component (you can think of {{ title }} as a simplified form of {{ this.title }}) and displayed on our markup. We’ve now seen all the parts of our auto-generated Angular app that actually take place in the page displayed in our browser. Let’s recap how it actually works: Angular CLI runs Webpack, which is compiling our Angular app into JavaScript bundles and injecting them into our index.html. If we take a look at the actual code in our browser using the inspect feature, we see something like this: Every time we change our code, Angular CLI will recompile, re-inject if needed, and ask our browser to reload the page if it’s open. Angular does it quite quickly, so in most cases, while you’re switching your windows from the IDE to the Browser, it’ll already be reloaded for you. So, let’s start moving toward our goal and, for a start, let’s switch our project from CSS to Sass and open our .angular-cli.json and edit styles and styleExt properties thusly: "styles": [ "styles.scss" ], [...] "defaults": { "styleExt": "scss", "component": {} } We also need to add the Sass library to our project and rename styles.css to styles.scss. So to add Sass, I am using yarn: yarn add sass yarn add v1.3.2 [1/4] 🔍 Resolving packages... [2/4] 🚚 Fetching packages... [3/4] 🔗 Linking dependencies... [...] [4/4] 📃 Building fresh packages... success Saved lockfile. success Saved 1 new dependency. └─ [email protected] ✨ Done in 12.06s. yarn add [email protected] --dev ✨ Done in 5.78s. I also want to use Twitter Bootstrap on our project, so I also run yarn add [email protected] and edit our styles.scss to include this: /* You can add global styles to this file, and also import other style files */ @import "../node_modules/bootstrap/scss/bootstrap"; body { padding-top: 5rem; } We need to edit index.html to make our page responsive by changing the meta for our markup to this: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> And now we can replace app.component.html with this: <!-- Fixed navbar --> <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top"> <a class="navbar-brand" href="#">Angular Notes</a> </nav> <div class="container-fluid text-center pb-5"> <div style="text-align:center"> <h1> Welcome to {{title}}! </h1> </div> </div> And now, if we open our browser, we see the following: And that’s it for the boilerplate. Let’s move on to creating our own components. Our first component We are going to display notes as cards in our interface, so let’s start by generating our first component, representing the card itself. For that, let) If we look into src/app/card/card.component.ts, we can see they are almost the same code, as we have in our AppComponent, with one small difference: [...] @Component({ selector: 'app-card', [...] export class CardComponent implements OnInit { constructor() { } ngOnInit() { } } I like to mention, at this point, that it’s considered good practice to preface our component selectors with a common prefix, and by default, it’s app-. You can change it to the prefix of your preference by editing the prefix property in .angular-cli.json, so it’s preferable to do so before using ng generate for the first time. So, we have a constructor for our component as well as an ngOnInit function for it. If you’re curious why we did that, you can read about it in Angular’s documentation.. We’ll talk about inputs and component communication pretty soon, but for now, let’s just remember that it is preferable to use the constructor for constants, like things that are actually being hard-coded into your component, and ngOnInit for everything that depends on external data. Let’s populate our CardComponent implementation. To start with, let’s just add some markup to it. Default contents for markup are something like this: <p> card works! </p> Let’s replace it with code so it will behave like a card: <div class="card"> <div class="card-block"> <p class="card-text">Text</p> </div> </div> Now is a good time to display the card component, but this raises additional questions: Who will be responsible for displaying the cards? AppComponent? But AppComponent will be loaded before anything else in the app, so we have to consider it to be tidy and small. We’d better create one more component to take care of storing a list of cards and displaying it on our page. As we described our component’s responsibilities, it is clear that this is supposed to be a Card List Component. Let’s ask Angular CLI to generate it for us:, let’s take a look at the thing that we ignored after generating our first component. Angular CLI tells us that it updated app.module.ts for us. We’ve never looked into it, so let. We can read more about both of them in the documentation. AppComponent was here before we started to generate any code, so our new components actually populated the module in two places: First, they are imported from their definition files, and then, they are included in the declarations array of if your app is not working, for no apparent reason, don’t forget to check your console. Let’s populate our card list component markup ( src/app/card-list/card-list.component.html): <div class="container-fluid text-center pb-5"> <div class="row"> <app-card</app-card> <app-card</app-card> <app-card</app-card> </div> </div> If we open it in our browser, we’ll see something like this: Currently, we display our cards out of the hard-coded markup. Let’s bring our code one step closer to a real case scenario by moving the hard-coded array of cards into our application: export class AppComponent { public cards: Array<any> = [ {text: 'Card 1'}, {text: 'Card 2'}, {text: 'Card 3'}, {text: 'Card 4'}, {text: 'Card 5'}, {text: 'Card 6'}, {text: 'Card 7'}, {text: 'Card 8'}, {text: 'Card 9'}, {text: 'Card 10'}, ]; } We have our initial list, but still, we need to pass it to the component and render it there. For that, we need to create our first input. Let’s add it to our CardList component: import {Component, Input, OnInit} from '@angular/core'; [...] export class CardListComponent implements OnInit { @Input() cards: Array<any>; [...] We imported Input from the Angular code and used it as a decorator for class-level variable cards with type Array of objects of any kind. Ideally, we shouldn’t use any, but should use strict typing so that we can define something like an interface card, which will contain all the properties of our card, but we will get that working later—for now, we’re using any just to get a fast and dirty implementation underway. Now, we have our card array in our CardList. How can we display it instead of our current markup? Let’s take a look at the new code in our card list component: <app-card</app-card> This is something new for us, an attribute name that starts from an asterisk. What does it mean? It’s a default convention for naming Angular structural directives. Structural directives control the structure of our template. The asterisk here is actually “syntax sugar,” and you can read further to understand how it works. but for your current example, it’s enough to understand what will happen when we add it to our component. So ngFor a repeater directive and it will repeat our app card for every element in the array of cards. If we look at the browser, we see this next: Something isn’t right; we have our array of cards, but we are getting an empty page. We defined our array of cards on the AppComponent level, but we haven’t passed it to CardList input. Let’s edit our AppComponent template to do that. <app-card-list [cards]="cards"></app-card-list> This syntax—the attribute in square brackets—tells Angular that we would like to one-way bind our component variable cards to our Card List component [cards] input. As soon as we do that, we get this: Of course, we want to display the actual contents of our card array, and for that, we need to pass the card object to the card component as well. Let’s extend our Card List component: <app-card</app-card> And if we look in the browser right now, we’ll get the next error in the JS console: Can't bind to 'card' since it isn't a known property of 'app-card'.. Angular is telling us that we still need to define our input in the Card component. So we can edit thusly: import {Component, Input, OnInit} from '@angular/core'; [...] export class CardComponent implements OnInit { @Input() card:any; [...] And let’s add our card text property to the Card component template: [...] <p class="card-text">{{ us class="card"> <div class="card-block"> <input placeholder="Take a note..." class="form-control"> </div> </div> Next, add this to the component decorator: [...] @Component({ selector: 'app-new-card-input', [...] host: {'class': 'col-4'} }) [...] And add our new component to the AppComponent template: [...] <div class="container-fluid text-center pb-5"> <div class="row justify-content-end"> <app-new-card-input></app-new-card-input> </div> </div> <app-card-list [cards]="cards"></app-card-list> Let’s take a look at the browser. The problem is that our new component isn’t doing anything. Let’s make it work—let’s start by adding a variable that will hold our new card: [...] export class NewCardInputComponent implements OnInit { [...] public newCard: any = {text: ''}; [...] How do we populate it with our input? If you’ve worked with AngularJS before, you may know the concept of two-way data binding. Or, you might have seen it in all those fancy AngularJS demos, where you input value to input and it updates the page content for us. Here’s an interesting tidbit: Two-way data binding is no longer with us in Angular. But that doesn’t mean we have lost access to the behavior. We already saw and used [value]="expression", which binds the expression to the input element’s value property. But we also have (input)="expression", a declarative way of binding an expression to the input element’s input event. Together, they can be used thusly: <input [value]="newCard.text" (input)="newCard.text = $event.target.value"> So, every time our newCard.text value changes, it’ll be passed to our component input. And every time the user inputs data into our input and the browser outputs input $event, we assign our newCard.text to the input value. One more thing before we implement it: This input looks like a little much, doesn’t it? Actually, Angular gives us a little syntax sugar for it, which we can use here, so I started from a different angle to explain how this sugar works. <input placeholder="Take a note..." class="form-control" [(ngModel)]="newCard.text"> This syntax, ([]), called banana in a box or ngModel, is the Angular directive that takes care of getting value out of events and all that. So we can just write simpler code that takes our value and binds it to both the value of the input and our variable in code. Unfortunately, after we added ngModel, we are getting the error, Can't bind to 'ngModel' since it isn't a known property of 'input'.. We need to import ngModel to our AppModule. But from where? If we check the documentation, we can see that it’s in the Angular Forms module. So we need to edit out AppModule thusly: [...] import {FormsModule} from "@angular/forms"; @NgModule({ [...] imports: [ BrowserModule, FormsModule ], [...] Working with native events So we have our variable populated, but we still need to send that value to the card list in AppComponent. For communicating data to the component Angular, we must have input. It seems that to communicate data outside the component, we have output, and we use it in the same way we would use input—we; we also define something called EventEmitter because the component output is supposed to be an event, but we shouldn’t think about it the same way we did those old JavaScript events. They aren’t bubbles. You don’t need to call preventDefault in every event listener. To send data from the component, we should use its payload. So we need to subscribe to the events—how do we do that? Let’s change the AppComponent template: <app-new-card-input (onCardAdd)="addCard($event)"></app-new-card-input> We are also binding an expression to the event onCardAdd, just as we mentioned in our NewCardInput component. Now we need to implement the addCard method on our AppComponent. [...] export class AppComponent { [...] addCard(cardText: string) { this.cards.push({text: cardText}); } But we’re still not outputting it from anywhere. Let’s try to make it happen when the user hits the enter key., we check that the key pressed was Enter and our newCard.text has something in it. After that, we can call our addCard method, in which we output Angular onCardAdd with text from our card and reset the card text to an empty string so the user can continue to add new cards without editing the old card’s text. Working with Forms There are a couple of approaches to working with forms in Angular—one is template-driven and we are already using the most valuable part of it: ngModel for two-way binding. But forms in Angular are not only about model values, but also about validity. Currently, we check for validity of NewCardInput in our HostListener function. Let’s move it to a more template-driven form. For that, we can change the template for our component: <form novalidate # <input placeholder="Take a note..." class="form-control" name="text" [(ngModel)]="newCard.text" required> </form> Here’s another syntax sugar from Angular. The hash #form is a template reference variable that we can use to access our form out of our code. Let’s use it to make sure, we can access any element marked by template reference value—in this case, our form, and we actually declare it as our Component public variable form, so we can write this.form.valid. Working with template driven forms is absolutely the same as we did before with simple HTML forms. If we need something more complex, there is a different kind of form for that case in Angular: reactive. We’ll cover what they react on after converting our form. For that, let’s add a new import to our, we are using dependency injection for FormBuilder on our constructor and building our form with it. The text there is a name of our field, an empty string is the initial value, and Validators.compose obviously allow us to combine multiple validators on a single field. We use .value and .setValue('') to access value for our field. Let’s look at our markup for this new way of working with forms: <form [formGroup]="newCardForm" novalidate> <input placeholder="Take a note..." class="form-control" name="text" formControlName="text"> </form> We are using FormGroupDirective to tell Angular what form group Angular needs to look in for its definition. By using formControlName, we are telling Angular what field in the reactive form we should use. For now, the main difference between the previous approach with template-driven forms and the new approach with reactive forms is in more coding on the reactive side. Is it really worth it, if we don’t need to define the form dynamically? It absolutely is. To understand how it may be helpful, let’s discuss why this approach is called “reactive” in the first place. Let’s start by adding additional code to our New Card Input we input new value into our input: RxJS So what’s actually happening here? We are seeing RxJS in action. Let’s discuss it. I guess you all know at least something about promises and building asynchronous code. Promise handling a single event. We ask the browser to make POST, for example, and it returns us a promise. RxJS operates with Observables, which handle streams of events. Think about that like this: We have just implemented code that is called on every change of our form. If we process user changes with promises, only the first user change will be processed before we need to resubscribe. The Observable, at the same time, is able to process every event in a virtually endless stream of “promises.” We can break that by getting some error along the way or by unsubscribing from the Observable. What is takeWhile here? We are subscribing to our Observables in our components. They are used in different part of our app, so they may be destroyed along the way—for example, when we use components as pages in our routing (and we’ll talk about routing later in this guide). But while the promise in place of the Observable will run only a single time and will be disposed after that, the Observable is built to last as long as the stream is updating and we don’t unsubscribe. So our subscription needs to be unsubscribed (if we are not looking for memory leaks) like this: const subscription = observable.subscribe(value => console.log(value)); [...] subscription.unsubscribe(); But in our app, we have a lot of different subscriptions. Do we need to do all of that boilerplate code? Actually, we can cheat and use the takeWhile operator. By using it, we make sure that our stream will stop emitting new values as soon as this.alive becomes false and we just need to set that value in the onDestroy function of our component. Working with back-ends Since we’re not building the server side here, we are going to use Firebase for our API. If you actually do have your own API back-end, let’s configure our back-end in development server. To do that, create proxy.conf.json in the root of the project and add this content there: { "/api": { "target": "", "secure": false } } For every request from our app to its host (which, if you remember, is Webpack dev server), the /api route server should proxy the request to. For that to work, we need to add one more thing to our app configuration; in package.json, we need to replace the start command for our project: [...] "scripts": { [...] "start": "ng serve --proxy-config proxy.conf.json", Now, we can run our project with yarn start or npm start and get proxy configuration in place. How can we work with the API from Angular? Angular gives us HttpClient. Let’s define our CardService for our current application: import { Injectable } from '@angular/core'; import {HttpClient} from '@angular/common/http'; @Injectable() export class CardService { constructor(private http: HttpClient) { } get() { return this.http.get(`/api/v1/cards.json`); } add(payload) { return this.http.post(`/api/v1/cards.json`, {text: trim(payload)}); } remove(payload) { return this.http.delete(`/api/v1/cards/${payload.id}.json`); } update(payload) { return this.http.patch(`/api/v1/cards/${payload.id}.json`, payload); } } So what does Injectable here mean? We already established that Dependency Injection helps us to inject our components with services we use. For getting access to our new service, we need to add it to the provider list in our AppModule: [...] import { CardService } from './services/card.service'; [...] @NgModule({ [...] providers: [CardService], Now we can inject it in our AppComponent, for example: import { CardService } from './services/card.service'; [...] constructor(private cardService: CardService) { cardService.get().subscribe((cards: any) => this.cards = cards); } So let’s configure Firebase now, creating a demo project in Firebase and hitting the Add Firebase to your app button. Then, we copy credentials that Firebase shows us into the Environment files of our app, here: src/environments/ export const environment = { [...] firebase: { apiKey: "[...]", authDomain: "[...]", databaseURL: "[...]", projectId: "[...]", storageBucket: "[...]", messagingSenderId: "[...]" } }; We need to add it to both environment.ts and environment.prod.ts. And just to give you some understanding of what Environment files are here, they are actually included in the project on compilation phase, and .prod. the part being defined by the --environment switch for ng serve or ng build. You can use values from that file in all parts of your project and include them from environment.ts while Angular CLI takes care of providing content from the corresponding environment.your-environment.ts. Let’s add our Firebase support libraries: yarn add [email protected] angularfire2 yarn add v1.3.2 [1/4] 🔍 Resolving packages... [2/4] 🚚 Fetching packages... [3/4] 🔗 Linking dependencies... [...] success Saved lockfile. success Saved 28 new dependencies. [...] ✨ Done in 40.79s. And now let’s change our CardService to support Firebase: import { Injectable } from '@angular/core'; import { AngularFireDatabase, AngularFireList, AngularFireObject } from 'angularfire2/database'; import { Observable } from 'rxjs/Observable'; import { Card } from '../models/card'; @Injectable() export class CardService { private basePath = '/items'; cardsRef: AngularFireList<Card>; cardRef: AngularFireObject<Card>; constructor(private db: AngularFireDatabase) { this.cardsRef = db.list('/cards'); } getCardsList(): Observable<Card[]> { return this.cardsRef.snapshotChanges().map((arr) => { return arr.map((snap) => Object.assign(snap.payload.val(), { $key: snap.key }) ); }); } getCard(key: string): Observable<Card | null> { const cardPath = `${this.basePath}/${key}`; const card = this.db.object(cardPath).valueChanges() as Observable<Card | null>; return card; } createCard(card: Card): void { this.cardsRef.push(card); } updateCard(key: string, value: any): void { this.cardsRef.update(key, value); } deleteCard(key: string): void { this.cardsRef.remove(key); } deleteAll(): void { this.cardsRef.remove(); } // Default error handling for all actions private handleError(error: Error) { console.error(error); } } We see something interesting here, on the first model for the card being imported. Let’s take a look at its composition: export class Card { $key: string; text: string; constructor(text: string) { this.text = text; } } So we are structuring our data with classes and, aside from our text, we add key$ from Firebase. Let’s change our AppComponent to work with that service: [...] import { AngularFireDatabase } from 'angularfire2/database'; import {Observable} from 'rxjs/Observable'; import { Card } from './models/card'; [...] export class AppComponent { public cards$: Observable<Card[]>; addCard(cardText: string) { this.cardService.createCard(new Card(cardText)); } constructor(private cardService: CardService) { this.cards$ = this.cardService.getCardsList(); } What is cards$? We mark our observable variables by adding $ to them to make sure we treat them as we should. Let’s add our cards$ to the AppComponent template: [...] <app-card-list [cards]="cards$"></app-card-list> In return, we get this error in the console: CardListComponent.html:3 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. Why so? We are getting observables from the Firebase. But our *ngFor in the CardList component waits for the array of objects, not observable of such arrays. So we can subscribe to that observable and assign it to a static array of cards, but there is a better option: <app-card-list [cards]="cards$ | async"></app-card-list> The async pipe, which is practically another syntax sugar that Angular gives to us, does the same thing we discussed—subscribe to the Observable and return its current value as a result of evaluation of our expression. Reactive Angular – Ngrx Let’s talk about our application state, by which I mean all properties of our application that define its current behavior and state literally. State is a single, immutable data structure—at least the way Ngrx implements it for us. And Ngrx is an “RxJS powered state management library for Angular applications, inspired by Redux.” Ngrx is inspired by Redux. “Redux is a pattern for managing application state.” So it’s more like set of conventions (for those of you who ever heard of convention over configuration in Ruby on Rails, you will see some similarities a bit later) that allow us to answer the question of how our application should decide it needs to display some interface element (like a collapsible sidebar) or where it is supposed to store its session state after it receives it from the server. Let’s see how this is achieved. We talked about State and its immutability, which means we can’t change any of its properties after creating it. This makes it all but impossible to store our application state in our State. But not completely—every single state is immutable, but the Store, which is our way of accessing State, is actually an Observable of the states. So State is a single value in a stream of Store values. In order to change the app’s state, we need to make some Actions that will take our current State and replace it with a new one. Both are immutable, but the second is based on the first, so instead of mutating values on our State, we create a new State object. For that, we use Reducers as pure functions, meaning that for any given State and Action and its payload reducer, it will return the same state as in any other call of that reducer function with same parameters. Actions consist of action type and optional payload: export interface Action { type: string; payload?: any; } For our task, let’s view how the action for adding a new card could be: store.dispatch({ type: 'ADD', payload: 'Test Card' }); Let’s see a reducer for that: export const cardsReducer = (state = [], action) => { switch(action.type) { case 'ADD': return {...state, cards: [...cards, new Card(action.payload)]}; default: return state; } } This function is being called for every new Action event. We’ll cover Action dispatching a bit later. For now, let’s say that if we dispatch our ADD_CARD action, it’ll get into that case statement. What is happening there? We are returning our new State based on our previous State by using TypeScript spread syntax, so we don’t have to use something like Object.assign in most cases. We never should change our state outside of those case statements, or it will make life miserable as we waste time searching for the reason why our code is behaving unpredictably. Let’s add Ngrx to our application. For that, let’s run next in our console: yarn add @ngrx/core @ngrx/store ngrx-store-logger yarn add v1.3.2 [1/4] 🔍 Resolving packages... [2/4] 🚚 Fetching packages... [3/4] 🔗 Linking dependencies... [...] [4/4] 📃 Building fresh packages... success Saved lockfile. success Saved 2 new dependencies. ├─ @ngrx/[email protected] └─ @ngrx/[email protected] └─ [email protected] ✨ Done in 25.47s. Now, add our Action definition ( app/actions/cards.ts): import { Action } from '@ngrx/store'; export const ADD = '[Cards] Add'; export const REMOVE = '[Cards] Remove'; export class Add implements Action { readonly type = ADD; constructor(public payload: any) {} } export class Remove implements Action { readonly type = REMOVE; constructor(public payload: any) {} } export type Actions = Add | Remove; And our Reducer definition ( app/reducers/cards.ts): import * as cards from '../actions/cards'; import { Card } from '../models/card'; export interface State { cards: Array<Card>; } const initialState: State = { cards: [] } export function reducer(state = initialState, action: cards.Actions): State { switch (action.type) { case cards.ADD: return { ...state, cards: [...state.cards, action.payload] }; case cards.REMOVE: const index = state.cards.map((card) => card.$key).indexOf(action.payload); return { ...state, cards: [...state.cards.slice(0, index), ...state.cards.slice(index+1)] }; default: return state; } } Here we can see how you can use spreads and native TypeScript functions like map to drop the element off our list. Let’s go one step further and make sure that if our application state will contain more than one type of data, we are composing it from a separate isolated state for each kind. For that, let’s use module resolution using ('; export interface State { cards: fromCards.State; } export const reducers: ActionReducerMap<State> = { cards: fromCards.reducer } export function logger(reducer: ActionReducer<State>): any { // default, no options return storeLogger()(reducer); } export const metaReducers: MetaReducer<State>[] = !environment.production ? [logger] : []; /** * Cards Reducers */ export const getCardsState = createFeatureSelector<fromCards.State>('cards'); export const getCards = createSelector( getCardsState, state => state.cards ); We also include a logger for our Ngrx in the development environment and create a selector function for our card array. Let’s include it in our AppComponent: import { Component } from '@angular/core'; import { CardService } from './services/card.service'; import { Observable } from 'rxjs/Observable'; import { Card } from './models/card'; import * as fromRoot from './reducers'; import * as cards from './actions/cards'; import { Store } from '@ngrx/store'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { public cards$: Observable<Card[]>; addCard(card: Card) { this.store.dispatch(new cards.AddCard(card)); } constructor(private store: Store<fromRoot.State>) { this.cards$ = this.store.select(fromRoot.getCards); } } Now, we see how we dispatch our actions using our store. But this code is still non-usable, as we don’t include our reducers (reducer and metaReducer) into our app. Let’s do it by changing our AppModule: [...] import { StoreModule } from '@ngrx/store'; import {reducers, metaReducers} from './reducers/index'; [...] imports: [ [...] StoreModule.forRoot(reducers, { metaReducers }), [...] And now it’s working. Kind of. Remember, we happen to have Firebase integrated into our App. Now it’s lost due to the highly maintainable Ngrx store. That is, it is stored nowhere. We can use something like ngrx-store-localstorage to store our data the browser’s localStore, but how about working with APIs? Maybe we can add our previous API integration into our Reducer? But we can’t, as our Reducer function is supposed to be a pure function. So, “evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices”… What can we do with that? The answer is actually right in that definition. Side-effects of Ngrx to the rescue. Ngrx effects So what is a side effect? Its piece of code that catches our Actions more or less the same way as our reducers do, but instead of changing something in our state, they actually send API requests and, on the result, dispatch new Actions. As always, it’s simpler to show you than to tell you. Let’s make our new configuration support Firebase. For that, let’s install the effects module: yarn add @ngrx/effects [...] success Saved 1 new dependency. └─ @ngrx/[email protected] ✨ Done in 11.28s. Now we will add new actions to our Card Actions for loading support ( src/app/actions/cards.ts): [...] export const LOAD = '[Cards] Load'; export const LOAD_SUCCESS = '[Cards] Load Success'; export const SERVER_FAILURE = '[Cards] Server failure'; [...] export class Load implements Action { readonly type = LOAD; } export class LoadSuccess implements Action { readonly type = LOAD_SUCCESS; constructor(public payload: any) {} } export class ServerFailure implements Action { readonly type = SERVER_FAILURE; constructor(public payload: any) {} } [...] export type Actions [...] | Load | LoadSuccess | ServerFailure So we have three new actions, one for loading the card list and two for dealing with successful and unsuccessful responses. Let’s implement our effects ( src/app/effects/cards.ts): import {Injectable} from '@angular/core'; import {Actions, Effect} from '@ngrx/effects'; import {CardService} from '../services/card.service'; import { of } from 'rxjs/observable/of'; import * as Cards from '../actions/cards'; import {exhaustMap, map, mergeMap, catchError} from 'rxjs/operators'; @Injectable() export class CardsEffects { @Effect() loadCards$ = this.actions$ .ofType(Cards.LOAD).pipe( mergeMap(action => { return this.cardService.getCardsList().pipe( map(res => new Cards.LoadSuccess(res)), catchError(error => of(new Cards.ServerFailure(error))))} ) ); @Effect({dispatch: false}) serverFailure$ = this.actions$ .ofType(Cards.SERVER_FAILURE).pipe( map((action: Cards.ServerFailure) => action.payload), exhaustMap(errors => { console.log('Server error happened:', errors); return of(null); })); constructor( private actions$: Actions, private cardService: CardService) {} } So we have injectable CardsEffects, which use the @Effect decorator for defining effects on top of our Actions and filtering only necessary actions by using the ofType operator. You may use ofType to create an effect that will be fired on multiple action types. But for now, we only need two out of our three actions. For the Load action, we are transforming every action into a new observable on the result of our getCardList method call. In the case of success, the observable will be mapped to a new action LoadSuccess with a payload of our request results, and in the case of error, we’ll return a single ServerFailure action (mind the of operator there—it converts a single value or array of values to the observable). So our Effects dispatch new Actions after making something that depends on the external system (our Firebase, to be precise). But within the same code, we see another effect, which handles the ServerFailure action using the decorator parameter dispatch: false. What does this mean? As we can see from its implementation, it also maps our ServerFailure action to its payload, and then displays this payload (our server error) to console.log. Clearly, in that case, we should not change state contents, so we don’t have to dispatch anything. And that’s how we make it work without any need for empty actions. So, now that we’ve covered two of our three actions, let’s move on to LoadSuccess. From what we know so far, we are downloading a list of cards from the server and we need to merge them into our State. So we need to add it to our reducer ( src/app/reducers/cards.ts): [...] switch (action.type) { [...] case cards.LOAD_SUCCESS: return { ...state, cards: [...state.cards, ...action.payload] } [...] So same story as before, we open our object and card array in it by using the spread operator and join it with the spread payload (cards from the server, in our case). Let’s add our new Load action to our AppComponent: [...] export class AppComponent implements OnInit { public cards$: Observable<Card[]>; addCard(card: Card) { this.store.dispatch(new cards.AddCard(card)); } constructor(private store: Store<fromRoot.State>) { } ngOnInit() { this.store.dispatch(new cards.Load()); this.cards$ = this.store.select(fromRoot.getCards); } } That should load our cards from Firebase. Let’s take a look at the browser: Something is not working. We are clearly dispatching the Action, as can be seen from our logs, but no server request is here for us. What’s wrong? We forgot to load our Effects to our AppModule. Let’s do that: [...] import { EffectsModule } from '@ngrx/effects'; import { CardsEffects } from './effects/cards.effects'; [...] imports: [ [...] EffectsModule.forRoot([CardsEffects]), And now, back to the browser… Now it’s working. So that’s how you integrate effects into loading data from the server. But we still need to send it back there on our card creation. Let’s make that work as well. For that, let’s change our CardService createCard method: createCard(card: Card): Card { const result = this.cardsRef.push(card); card.$key = result.key; return card; } And add an effect for the Adding card: @Effect() addCards$ = this.actions$ .ofType(Cards.ADD).pipe( map((action: Cards.Add) => action.payload), exhaustMap(payload => { const card = this.cardService.createCard(payload); if (card.$key) { return of(new Cards.LoadSuccess([card])); } }) ); So, if the card is to be created, it’ll get $key from Firebase and we’ll merge it into our card array. We also need to remove the case cards.ADD: branch from our reducer. Let’s try it in action: For some reason, we are getting duplicated data on the card add operation. Let’s try to figure out why. If we look closely at the console, we’ll see two LoadSuccess actions first being dispatched with our new card as it is supposed to be, and the second one is being dispatched with both of our cards. If not in effects, where in our action is it being dispatched? Our Load effect on cards has this code: return this.cardService.getCardsList().pipe( map(res => new Cards.LoadSuccess(res)), And our getCardsList is observable. So when we add a new card to our card collection, it is output. So either we don’t need to add that card on our own, or we need use a take(1) operator in that pipe. It’ll take a single value and unsubscribe. But having live subscription seems more reasonable (presumably, we will have more than one user in the system), so let’s change our code to deal with the subscription. Let’s add a non-dispatching element to our effect: @Effect({dispatch: false}) addCards$ = this.actions$ .ofType(Cards.ADD).pipe( map((action: Cards.Add) => action.payload), exhaustMap(payload => { this.cardService.createCard(payload); return of(null); }) ); Now we only need to change the reducer LoadSuccess to replace cards, not combine them: case cards.LOAD_SUCCESS: return { ...state, cards: action.payload }; And now it’s working as it should: You can implement remove action the same way now. As we get data out of that subscription, you only have to implement the Remove effect. But I will leave that to you. Routing and modules Let’s speak about our application composition. What if we need an About page in our application? How can we add that to our current codebase? Obviously, the page is supposed to be a component (as anything else in Angular, mostly). Let’s generate that component. ng g component about --inline-template --inline-style [...] create src/app/about/about.component.ts (266 bytes) update src/app/app.module.ts (1503 bytes) And add the next markup to it: [...] @Component({ selector: 'app-about', template: ` <div class="jumbotron"> <h1 class="display-3">Cards App</h1> </div> `, [...] So now, we have our About page. How we can access it? Let’s add some more code to our AppModule: [...] import { AboutComponent } from './about/about.component'; import { MainComponent } from './main/main.component'; import {Routes, RouterModule, Router} from "@angular/router"; const routes: Routes = [ {path: '', redirectTo: 'cards', pathMatch: 'full'}, {path: 'cards', component: MainComponent}, {path: 'about', component: AboutComponent}, ] @NgModule({ declarations: [ [...] AboutComponent, MainComponent, ], imports: [ [...] RouterModule.forRoot(routes, {useHash: true}) What is MainComponent here? For now, just generate it the same way we did with AboutComponent and we’ll populate it later. As for route structure, it more or less speaks for itself. We define two routes: /cards and /about. And we make sure that empty path redirects for /cards. Now let’s move our cards handling code to MainComponent: import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Card } from '../models/card'; import * as fromRoot from '../reducers'; import * as cards from '../actions/cards'; import { Store } from '@ngrx/store'; @Component({ selector: 'app-main', template: ` <div class="container-fluid text-center pb-5"> <div class="row justify-content-end"> <app-new-card-input (onCardAdd)="addCard($event)"></app-new-card-input> </div> </div> <app-card-list [cards]="cards$ | async"></app-card-list> `, styles: [] }) export class MainComponent implements OnInit { public cards$: Observable<Card[]>; addCard(card: Card) { this.store.dispatch(new cards.Add(card)); } constructor(private store: Store<fromRoot.State>) { } ngOnInit() { this.store.dispatch(new cards.Load()); this.cards$ = this.store.select(fromRoot.getCards); } } And let’s remove it from AppComponent: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor() { } ngOnInit() { } } And from markup as well: <!-- Fixed navbar --> <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top"> <a class="navbar-brand" href="#">Angular Notes</a> <ul class="navbar-nav mr-auto"> <li class="nav-item" [routerLinkActive]="['active']"> <a class="nav-link" [routerLink]="['cards']">Cards</a> </li> <li class="nav-item" [routerLinkActive]="['active']"> <a class="nav-link" [routerLink]="['about']">About</a> </li> </ul> </nav> <router-outlet></router-outlet> As you can see, we added some more things. First of all, we added router directives for RouterLinkActive, which is setting a class when our route is active, and routerLink, which replaces href for us. And here is routerOutlet, which tells Router where to display its contents on a current page. So, combining those, we now have the menu on every page, along with two pages with different content: For more details, please read the Router Guide. As our application grows, we may start thinking of optimization. For example, what if we like to load the About component for default and only load additional components after the user implicitly asks for it by clicking on the Cards link. For that, we can use lazy loading of modules. Let’s start by generating CardsModule: ng g module cards --flat create src/app/cards.module.ts (189 bytes) By using the flat flag, we are telling Angular to not create the separate directory for our module. Let’s transfer all card-related things into our new module: import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CardService } from './services/card.service'; import { CardComponent } from './card/card.component'; import { CardListComponent } from './card-list/card-list.component'; import { NewCardInputComponent } from './new-card-input/new-card-input.component'; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import { AngularFireModule } from 'angularfire2'; import { AngularFireDatabaseModule } from 'angularfire2/database'; import { AngularFireAuthModule } from 'angularfire2/auth'; import { StoreModule } from '@ngrx/store'; import { EffectsModule } from '@ngrx/effects'; import { reducers } from './reducers'; import { CardsEffects } from './effects/cards.effects'; import { environment } from './../environments/environment'; import { MainComponent } from './main/main.component'; import {Routes, RouterModule, Router} from "@angular/router"; const routes: Routes = [ {path: '', redirectTo: 'cards', pathMatch: 'full'}, {path: 'cards', component: MainComponent}, ] @NgModule({ imports: [ CommonModule, FormsModule, ReactiveFormsModule, StoreModule.forFeature('cards', reducers), EffectsModule.forFeature([CardsEffects]), RouterModule.forChild(routes), AngularFireModule.initializeApp(environment.firebase), AngularFireDatabaseModule, AngularFireAuthModule, ], providers: [CardService], declarations: [ CardComponent, CardListComponent, NewCardInputComponent, MainComponent ] }) export class CardsModule { } Previously, we saw a lot of forRoot calls in our import, but here, we call for a lot of forFeature or forChild. That’s how we tell our components that we are extending our configuration, not creating it from scratch. Let’s see what is still in our AppModule: [...] import { reducers, metaReducers } from './reducers/root'; const routes: Routes = [ {path: '', redirectTo: 'about', pathMatch: 'full'}, {path: 'about', component: AboutComponent}, { path: 'cards', loadChildren: './cards.module#CardsModule'} ] @NgModule({ declarations: [ AppComponent, AboutComponent, ], imports: [ BrowserModule, RouterModule.forRoot(routes, {useHash: true}), StoreModule.forRoot(reducers, { metaReducers }), EffectsModule.forRoot([]), ], bootstrap: [AppComponent] }) export class AppModule { } Here, we still define EffectsModule.forRoot or it won’t work in our loaded module (as it will be nowhere to add on lazy load). We also see new syntax here for the router loadChildren that tells our router to lazy load CardsModule located in the ./cards.module file when we ask for the cards route. And we include meta reducers from the new ./reducers/root.ts file—let’s take a look at it: import {ActionReducer, ActionReducerMap, createFeatureSelector, createSelector, MetaReducer} from '@ngrx/store'; import {storeLogger} from 'ngrx-store-logger'; import {environment} from '../../environments/environment'; export interface State { } export const reducers: ActionReducerMap<State> = { } export function logger(reducer: ActionReducer<State>): any { // default, no options return storeLogger()(reducer); } export const metaReducers: MetaReducer<State>[] = !environment.production ? [logger] : []; On a root level, we currently don’t have any state, but we still need to define the empty state so we can extend it in the progress of lazy loading. That also means that our state of cards has to be defined somewhere else, and for this example, we define it in src'; import * as fromRoot from './root'; export interface CardsState { cards: fromCards.State; } export interface State extends fromRoot.State { cards: CardsState; } export const reducers = { cards: fromCards.reducer } /** * Cards Reducers */ export const getCardsState = createFeatureSelector<CardsState>('cards'); export const getCards = createSelector( getCardsState, state => state.cards.cards ); So we extend our root state by cards key. And that gives us key nesting duplication at the end (as both a module and an array called cards). If we open our app now and look into the network tab of the developer console, we’ll see that cards.module.chunk.js is being loaded only after we click on the /cards link. Preparing for production So let’s build our app for production use. And for that, let’s run the build command: ng build --aot -prod 65% building modules 465/466 modules 1 active ...g/getting-started-ng5/src/styles.scssNode#moveTo was deprecated. Use Container#append. Date: 2018-01-09T22:14:59.803Z Hash: d11fb9d870229fa05b2d Time: 43464ms chunk {0} 0.657b0d0ea895bd46a047.chunk.js () 427 kB [rendered] chunk {1} polyfills.fca27ddf9647d9c26040.bundle.js (polyfills) 60.9 kB [initial] [rendered] chunk {2} main.5e577f3b7b05660215d6.bundle.js (main) 279 kB [initial] [rendered] chunk {3} styles.e5d5ef7041b9b072ef05.bundle.css (styles) 136 kB [initial] [rendered] chunk {4} inline.1d85c373f8734db7f8d6.bundle.js (inline) 1.47 kB [entry] [rendered] So what’s happening here? We are building our application to static assets that could be served from any web server (if you want to serve from subdirectory ng build, have the option --base-href ). By using -prod, we are telling AngularCLI that we need the production build. And --aot is telling it that we like to have ahead-of-time compilation. In most cases, we prefer that, as it allows us to get the smaller bundle and faster code. Also, keep in mind that AoT is way too strict on your code quality, so it may produce errors that you haven’t seen before. Run the build earlier so it’s easier to fix. I18n Another reason to build our app is how Angular handles i18n or, speaking in plain terms, internationalization. Instead of dealing with it at runtime, Angular does it at compilation. Let’s configure it for our app. For that, let’s add the i18n attribute to our AboutComponent. <div class="jumbotron"> <h1 class="display-3" i18n>Cards App</h1> </div> By using that, we are telling the Angular compiler that the tag’s contents need to be translated. It’s not the Angular directive, and it is removed by the compiler in the process of compilation and replaced by the translation for a given language. So we marked our first translated message, but what next? How can we actually translate that? For that, Angular offers us the ng xi18n command: ng xi18n cat src/messages.xlf <?xml version="1.0" encoding="UTF-8" ?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source- <body> <trans-unit <source>Cards App</source> <context-group <context context-app/about/about.component.ts</context> <context context-3</context> </context-group> </trans-unit> </body> </file> </xliff> So we have a translation file mapping out our messages to their actual locations in the source code. Now, we can give the file to PhraseApp. Or, we can just add our translation manually. For that, let’s create a new file in src, messages.ru.xlf: <?xml version="1.0" encoding="UTF-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2"> <file original="ng2.template" datatype="plaintext" source- <body> <trans-unit <source xml:Cards App</source> <target xml:Картотека</target> </trans-unit> </body> </file> </xliff> We now can serve our app—in Russian, for example—by running this command ng serve --aot --locale=ru --i18n-file=src/messages.ru.xlf. Let’s see if it works: Now, let’s automate our build script so we can make our app build in two languages on every production build and call its corresponding directories en or ru. For that let’s add the build-i18n command to the scripts section of our package.json: "build-i18n": "for lang in en ru; do yarn run ng build --output-path=dist/$lang --aot -prod --bh /$lang/ --i18n-file=src/messages.$lang.xlf --i18n-format=xlf --locale=$lang --missing-translation=warning; done" Docker Now let’s package our app for production use, and use Docker for that. Let’s start with Dockerfile: #### STAGE 1: Build ### ## We label our stage as 'builder' FROM node:8.6-alpine as builder ENV APP_PATH /app MAINTAINER Sergey Moiseev <[email protected]> COPY package.json . COPY yarn.lock . ### Storing node modules on a separate layer will prevent unnecessary npm installs at each build RUN yarn install --production && yarn global add gulp && mkdir $APP_PATH && cp -R ./node_modules .$APP_PATH WORKDIR $APP_PATH COPY . . ### Build the angular app in production mode and store the artifacts in dist folder RUN yarn remove node-sass && yarn add node-sass && yarn run build-i18n && yarn run gulp compress #### STAGE 2: Setup ### FROM nginx:1.13.3-alpine ENV APP_PATH /app MAINTAINER Sergey Moiseev <[email protected]> ### Copy our default nginx config RUN rm -rf /etc/nginx/conf.d/* COPY nginx/default.conf /etc/nginx/conf.d/ ### Remove default nginx website RUN rm -rf /usr/share/nginx/html/* EXPOSE 80 ### From 'builder' stage copy over the artifacts in dist folder to default nginx public folder COPY --from=builder $APP_PATH/dist/ /usr/share/nginx/html/ CMD ["nginx", "-g", "daemon off;"] So we are using a multistage build for our app with a Node-based image, and then we build the server package with an Nginx-based image. We also use Gulp to compress our artifacts, as Angular CLI no longer does it for us. I find that strange, but okay, let’s add Gulp and compression scripts. yarn add [email protected] [email protected] --dev [...] success Saved 2 new dependencies. ├─ [email protected] └─ [email protected] ✨ Done in 10.48s. Lets add gulpfile.js in our app root: const gulp = require('gulp'); const zip = require('gulp-gzip'); gulp.task('compress', function() { for (var lang in ['en', 'ru']) { gulp.src([`./dist/${lang}/*.js`, `./dist/${lang}/*.css`]) .pipe(zip()) .pipe(gulp.dest(`./dist/${lang}/`)); } }); Now we only need our Nginx config to build our container. Let’s add it to nginx/default.conf: server { listen 80; sendfile on; default_type application/octet-stream; client_max_body_size 16m; gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.0; # This allow us to gzip on nginx2nginx upstream.; root /usr/share/nginx/html; location ~* \.(js|css)$ { gzip_static on; expires max; add_header Cache-Control public; } location ~ ^/(en|ru)/ { try_files $uri $uri/ /index.html =404; } location = / { return 301 /en/; } } So we are serving our build application from directories en or ru and by default, we are redirecting from root URL to Now we can build our app by using the docker build -t app . command: docker build -t app . Sending build context to Docker daemon 347MB Step 1/17 : FROM node:8.6-alpine as builder ---> b7e15c83cdaf Step 2/17 : ENV APP_PATH /app [...] Removing intermediate container 1ef1d5b8d86b Successfully built db57c0948f1e Successfully tagged app:latest And then we can serve it using Docker from a local machine by running docker run -it -p 80:80 app. And it’s working: Mind the /en/ in URL. Summary Congratulations on completing this tutorial. You can now join the ranks of other Angular developers. You’ve just created your first Angular app, used Firebase as a backend and served it via Nginx in a Docker container. As with any new framework, the only way to get good at it is to keep practicing. Hopefully you’ve come to understand just how powerful Angular is. When you’re ready to proceed, the Angular documentation is a wonderful resource and comes with a whole section on advanced techniques. If you feel like taking on something more advanced, try Working with Angular 4 Forms: Nesting and Input Validation by fellow Toptaler Igor Geshoki. Understanding the basics Why do we use Angular? We use it to develop rich interface client-side applications like single-page applications and mobile applications. The main advantage of Angular is getting a fully integrated web framework that offers its own in-box solutions for building components, routing, and working with remote APIs. What are the advantages of using Angular? The main advantage of using Angular is getting a fully integrated web framework that offers its own in-box solutions for building components, routing, and working with remote APIs. How does a module work in Angular? Modules separate the scope of declarations in them. That allows us to build multiple independent modules for our app and use lazy loading for the modules. The purpose of a module is to declare everything that is used in this module and allow Angular to do ahead-of-time compilation for it. Is Angular MVC-based? Angular is no longer an MVC framework, unlike AngularJS. It’s a component-based framework. Components take the role of controllers here, but only on a very simplified level of abstraction. What is RxJS? RxJS is the Reactive Extensions library for JavaScript, which allows us to operate with Observables, which are streams of events that replace stand-alone promises for us. What is NgRX? NgRX is a pattern for managing application states. It’s an RxJS-powered state management library for Angular applications. It allows us to have a single application state to wire all components together and provide predictable and consistent behavior for our app.
https://www.toptal.com/angular/angular-5-tutorial
CC-MAIN-2019-26
refinedweb
9,891
57.47
The Common Gateway Interface (CGI) is a standard for writing programs that can interact through a Web server with a client running a Web browser. These programs allow a Web developer to deliver dynamic information (usually in the form of HTML) via the browser. A CGI program can be written in any language, including Java, that can be executed by your Web server. CGI programs are commonly used to add search engines, guest-book applications, database-query engines, interactive-user forums, and other interactive applications to Web sites. In very basic terms, a CGI program must interpret the information sent to it, process the information in some way, and generate a response that will be sent back to the client. Most of the input to a CGI program is passed into it through environment variables. This article will demonstrate how to send these environment variables to a Java CGI program. The rest of the input (if any) is passed into a CGI program as standard input that can be read directly by your program. The processing can be as simple as appending information to a file or as complex as requesting data from a database. Since a CGI program can return a myriad of document types, a CGI program must place a short header (ASCII text) on its output so that the client will know how to interpret the information it generates. Most commonly, CGI programs generate HTML. Below, you will find a library of functions including one that generates the appropriate header for HTML. Following the header, a CGI program simply generates the body of the output in its native form. Passing the CGI environment into the Java program Writing a CGI program in Java is fairly easy to do once you understand the issues. First and foremost, you need to wrap the execution of the Java program inside another script. So, the actual script invoked on your Web server will be a Unix shell script or a Windows batch file (or equivalent) that simply passes the CGI environment variables into your Java program. Since Java no longer provides a method to access environment variables directly (the System.getenv() method has been disabled in the latest release of the JDK), I propose passing each CGI environment variable into the Java program using the -D command-line parameter on the Java interpreter. I will show you how to use the -D parameter below. The library of functions I provide below assumes that you have used the approach described above; it uses the System.getProperty() method to access those command-line parameters. If your program needs to use any of the CGI environment variables, you can access them the same way. For example, if you want to access the SERVER_NAME environment variable, you could do so as follows: String server_name = System.getProperty("cgi.server_name"); Be aware that I am not passing all of the CGI environment variables into my Java program. I'm only passing the major ones. I'll leave the inclusion of the others as an exercise for the reader. The following example shows a Unix script file called hello.cgi invoking a Java program called hello. Note that the -D command-line parameter passes the CGI environment variables into the Java program: #!/bin/sh java -Dcgi.content_type=$CONTENT_TYPE -Dcgi.content_length=$CONTENT_LENGTH -Dcgi.request_method=$REQUEST_METHOD -Dcgi.query_string=$QUERY_STRING -Dcgi.server_name=$SERVER_NAME -Dcgi.server_port=$SERVER_PORT -Dcgi.script_name=$SCRIPT_NAME -Dcgi.path_info=$PATH_INFO hello This solution doesn't work well on the Windows 95 and NT platforms because there may be limits on the number of characters allowed on the command line. An alternative approach might be simply to write each of the environment variables and their associated values to a temporary file (with a unique filename, of course). Then, you may pass the name of this file into your Java program and have it read that file and parse out the environment variable/value pairs. Don't forget to delete the temporary file when you're done using it! Again, this exercise is left to the reader. A Java CGI library To ease the tedious task of processing the CGI inputs, I have written a Java class (really a library of functions) that you can utilize to cut down on some of the dirty work. This library attempts to duplicate the functionality in the very popular Perl cgi-lib.pl library. I have documented the code below using javadoc-style comments so that you can generate HTML documentation directly from the code. (Use javadoc cgi_lib.java to generate cgi_lib.html.) Here is the source code and documentation for the library. Writing your first Java CGI program Here's an example that shows how the cgi_lib.java library can be used to write a CGI program. We'll write a simple program that processes my "Hello There" form. This simple form will prompt the user for a name and email address. Here is the form ( hello.html) that we want to process: <HTML> <HEAD> <TITLE>Hello and Welcome!</TITLE> </HEAD> <BODY> <H1 ALIGN=CENTER>Hello and Welcome</H1> <hr> <FORM METHOD="POST" ACTION="/cgi-bin/hello.cgi"> What is your name? <INPUT TYPE="text" NAME="name" VALUE=""><p> What is your email address? <INPUT SIZE=40 <INPUT TYPE="submit" VALUE="Submit">. <P> </FORM> <hr> </BODY> </HTML> Let's write a Java program to process the "Hello There" form. First, we need to let the client know that our program will be generating HTML. The Header() method in cgi_lib.java creates the string we need, so we'll start by calling that method and sending the string to standard out using the System.out.println system call. // // Print the required CGI header. // System.out.println(cgi_lib.Header()); Second, we want to process the form data sent to us by the browser. The ReadParse method in cgi_lib.java does all that work for us and returns the result in an instance of a Hashtable. In this case, the Hashtable will contain two key values after parsing the form data. One will be the "name" input field and the other will be the "email" input field. The values associated with each of these keys will be whatever the user typed into those input fields on the "Hello There" form. // // Parse the form data into a Hashtable. // Hashtable form_data = cgi_lib.ReadParse(System.in); Now that we've parsed the form data, we can do whatever processing we'd like with the data sent to us. Then we can generate some HTML to send back to the user's browser. In this simple program, we aren't going to do any processing with the data; we're simply going to echo back the information supplied by the user. We are going to use the get method on the Hashtable object to extract the form values into strings that we can use in our program. The following example shows how we would extract the name that the user typed into a String object. String name = (String)form_data.get("name"); Now, let's put this all together in a simple program. Here is a Java application that we can use to process the "Hello There" form ( hello.java): import java.util.*; import java.io.*; class hello { public static void main( String args[] ) { // // Here is a minimalistic CGI program that uses cgi_lib // // // Print the required CGI header. // System.out.println(cgi_lib.Header()); // // Parse the form data into a Hashtable. // Hashtable form_data = cgi_lib.ReadParse(System.in); // // Create the Top of the returned HTML page // String name = (String)form_data.get("name"); System.out.println(cgi_lib.HtmlTop("Hello There " + name + "!")); System.out.println("<h1 align=center>Hello There " + name + "!</h1>"); System.out.println("Here are the name/value pairs from the form:"); // // Print the name/value pairs sent from the browser. // System.out.println(cgi_lib.Variables(form_data)); // // Print the Environment variables sent in from the Unix script. // System.out.println("Here are the CGI environment variables/value pairs" + "passed in from the UNIX script:"); System.out.println(cgi_lib.Environment()); // // Create the Bottom of the returned HTML page to close it cleanly. // System.out.println(cgi_lib.HtmlBot()); } } Conclusion With this introduction to CGI programming in Java, you should be on your way to a whole new way of programming the server side of your Web applications. Keep in mind that the CGI protocol provides only one way of communicating between a client browser and a Web server. The World Wide Web Consortium's Jigsaw (see the Resources section below) and others like Sun's Jeeves, are coming up with better solutions, which involve writing Java servlets that you can hang off your Web server. But that is a topic for another day. Have fun! Learn more about this topic - Information on the Common Gateway Interface (CGI) can be found at: - The World Wide Web Consortium's Jigsaw is described at: - For more on Sun's Jeeves, see:
https://www.javaworld.com/article/2076863/java-web-development/write-cgi-programs-in-java.html
CC-MAIN-2018-09
refinedweb
1,483
56.05
Andrew Lynes' WebLog Community 5.6.583.17018 (Build: 5.6.583.17018)2006-08-01T22:04:00ZTechEd 2011 Australia - SharePoint 2010 Monitoring and Troubleshooting<p>It's been yet another long period between posts. I spoke at the Premier Pre-Day at the TechEd 2011 Australia last week. The topic was on "SharePoint 2010 Monitoring and Troubleshooting". For a copy of the slide deck, jump over to the ANZ SharePoint PFE Team Blog: <a href=""></a></p><div style="clear:both;"></div><img src="" width="1" height="1">anlynes - Remote Server Administration Tools for Windows 7 with Service Pack 1 (SP1)<p>Good news. Those us using Windows 7 SP1 can install the Remote Server Administration Tools again.</p> <p>For more information refer to the download page: <a href=""></a></p><div style="clear:both;"></div><img src="" width="1" height="1">anlynes Server Administration Tools and Windows 7 SP1<p>I found out the hard way today that you cannot install the current version of the "Remote Server Administration Tools for Windows 7" on a machine that has Windows 7 Service Pack 1 installed. The current advice is to install the remote administration tools first before applying Service Pack 1. Unfortunately it's too late for me. So, if you think you may need the tools, install them now!</p> <p>According to TechNet, the "Remote Server Administration Tools for Windows 7 with SP1 is scheduled for release in Spring 2011".</p> <p>For more information refer to the download page: <a href=""></a></p> <p><strong>April 9, 2011 Update: Remote Server Administration Tools for Windows 7 SP1 have now been released!</strong></p><div style="clear:both;"></div><img src="" width="1" height="1">anlynes Role for Andrew<p>They> <p>PFEs tend to have a few specialities. Mine is SharePoint with .NET Development on the side.</p> <p>It's been a long time since I've written a blog entry. I intend for this to be the first of regular updates.</p><div style="clear:both;"></div><img src="" width="1" height="1">anlynes 2007 Protocols and Ports<P>In researching how to deploy MOSS into a customer's data centre, I needed to find out exactly what and how was being communicated between the various MOSS servers. Surprisingly, Microsoft.com is a bit light on details, although there is a reasonable "security hardening" document available on <A class="" title=TechNetTechNet</A>.</P> <P>The winner for me was this post from <A class="" title="Joel Oleson" href="" mce_href="">Joel Oleson</A>. It's short, to the point, and answers the obvious questions.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes the TFS Process Template Editor<P>After an extended absence, I returned to <STRIKE>hacking</STRIKE> <A onclick="javascript:Track('ctl00_ctl01|ctl00_ctl02',this);" href="" mce_href="">Domain-Specific Language Tools for Visual Studio 2005 Redistributable Components</A>. No problemo... but still no Editor. I then repaired the Power Tool... but still no Editor. It was only after an uninstall/reinstall cycle of the Power Tool did the Editor appear on the Team menu of Visual Studio.</P> <P>The moral of the story... RTFM and install the DSL Tools before the Power Tool.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes: IIS application query script<P>Perhaps <A class="" title="Iisapp.vbs: IIS application query script" href="" mce_href="">TechNet</A>.</P> <P>For the infrastructure people out there, this is probably nothing new. For devs like me, we probably don't spend enough time on TechNet to pick up nuggets such as this.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes Certifications - Are they worth it?<P>It's that time of year where I really need to move on my training objectives I set out at the beginning of year. In a rush of blood, I decided to update my .NET certifications to the latest and greatest. One question that comes up in discussions from time to time is whether it's worth the effort.</P> <P>In the best tradition of consultants, my response to this question is that "it all depends". Personally I don't see any point in going through the certification process simply to get a few letters after your name. I've interviewed enough people over the years with the Microsoft alphabet stapled to their resume who couldn't answer basic real world questions. Instead, the real goal of certification is to learn something. Of course in order to learn something, you may actually have to look at the exam material over a period of time rather than cram it in the night before. Although both strategies may see you certified, it is usually pretty clear in an interview/work situation who has actually tried to improve their skills. So, if you're prepared to put in a bit of effort and learn something, I think certifications are worth it. However, if your goal is to be locked in a room for two hours to stare at a computer and eat lollies, you'd be better off staying at home and playing Age of Empires.</P> <P>For anyone still reading, my main tip for successfully getting certified is to go ahead and book the exam/s. Having a deadline is a great motivator to get on with it.</P> <P>Finally, for those that haven't looked for a while, the Microsoft Press training kits for the new MCPD and MCTS exams are now available from your favourite online bookstore.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes need to do a root cause analysis<P>A couple of days before Christmas, I found myself in the emergency department of my local hospital with an <A class="" href="" mce_href="">Atrial Fibrillation</A>.).</P> <P.</P> <P.</P> <P>Unfortunately we can't just add some instrumentation to produce Andrew 2.0 and find out why I needed jump-starting. But at least I'm looking.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes AJAX Ships<P>This is great news. I've been waiting on this one for a while. I'm currently pondering what one of my major customer's application delivery methods might be in the future. This is another option to throw into the mix.</P> <P>Details can be found at <A class="" href="" mce_href="">AJAX : The Official Microsoft ASP.NET AJAX Site</A> and <A class="" href="" mce_href="">Scott Guthrie's blog</A>.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes Canberra VSTS User Group Meeting<P>We.</P> <P mce_keep="true"> </P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes TFS Fields<P>Last week I found myself creating a custom work item and needed to add a few new fields to TFS. That wasn't anything special in itself, but when I decided to change the names of my new fields (I'm blonde after all), things became more interesting. It turns out that TFS can only have one field for a specific friendly name. That sounds obvious, but when we also provide a "ReferenceName" that has a distinct namespace feel about it, I thought I could get away with it. Wrong!</P> <P>Fortunately there's a neat tool that ships with TFS to rename fields (and other stuff). Check out witfields.exe. You won't use it all that often, but it's good to know it's there.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes Portfolios<P>Recently <A class="" href="" mce_href="">Microsoft Office Project Portfolio Server</A>.</P> <P>Application Portfolio Management is a huge topic with widely varying opinions about what features are required in a tool. Side-stepping all of that, if some of the things I've listed above would be useful for you, why not have a look at Project Portfolio Server?</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes VSTS User Group<P>Just in case you missed it... Check out <A class="" href="" mce_href="">Nils' blog</A>.</P> <P>It looks like I'm going to be one of the first <STRIKE>bunnies</STRIKE> to present. Hmmmm, where to start? I think <A class="" href="" mce_href="">Grant</A> and I should be able to come up with something from our recent migration gig. We're 2.5 months on from going live now, so we've got a pretty good idea what worked and what didn't.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes do you need a development environment for TFS?<P>One of the great things about TFS is that you can place the "crown jewels" of your development activities in a single safe location. The consequence for me is that I'm somewhat paranoid about using a production TFS installation for TFS R&D activities. For example, should I install a process template provided by a third party on my production server simply to have a look at it? IMO, absolutely not!</P> <P>It's not to say you can't use your production TFS installation for some R&D work. Where I get sensitive is where this work requires changes that can't be confined to a single team project. At my current site, planning for replacing a CruiseControl/NANT build solution with Team Build is being undertaken using a team project on the production TFS installation. It's nicely contained, and TFS is being used as intended... to support development. However, having looked at one or two commercial process template offerings which require me to run MSIs on the TFS servers, there is no way I would put these anywhere near production (Why do software houses still get MSIs wrong?).</P> <P>Where does that leave us? In short, you will probably need somewhere to try new TFS "things" independently of production. Virtual machines are the obvious solution, however if you plan migrate a lot of source from VSS into TFS, I would recommend that you get yourself some physical hardware. This allows you to iron out migration issues in a semi-realistic fashion before you involve the production installation (see some of my previous posts on the problems of repeating a migration over and over on the same TFS installation). Regardless of the choice, you will need to consider how you're going the license the development TFS installation (development is production for TFS after all). For low usage (which should normally be the case), the Workgroup Edition of TFS may fit the bill. I'm actually a fan of both approaches. I use VMs to "play" and a physical development installation to implement the next round of TFS changes. If Humpty-Dumpty has a big fall, at least he won't take out all my (or my customer's) source and developer productivity with him. </P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes how do you find time to manage TFS?<P>T <STRONG>Team </STRONG>Foundation Server for nothing</P> <P <STRONG>delegation</STRONG>. That is, rather than lock everything down so tight that the TFS administrator has to do everything, figure out what you can safely outsource to the users.</P> <P>Safely outsource? Is that possible? Here are a few thoughts:</P> <UL> <LI>Remember that you can't permanently delete items from source control. This means that any "mistakes" can generally be undone. You may therefore get away with granting more access to source control by default than you may have initially thought.</LI> <LI!</LI> <LI.</LI> <LI>Don't fall into the trap of managing TFS security by assigning rights to individuals. Always use groups of some description. Where this isn't feasible, outsource it.</LI> <LI>Don't try to keep secrets. Granting read-only access to everything by everyone by default can save a lot of administrative time. Besides, not hiding anything is great for communication!</LI></UL> <P.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes Road to TFS - Experience from the Field (Part 3)<P>So one week on, how did it pan out? In short, not bad... not bad at all.</P> .</P> <P.</P> <P>Looking back, we had a comparatively smooth ride, even though we targetted VS2003 users. For anyone considering such an upgrade, I'd recommend you go for it. Just remember to plan and practice everything.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes Road to TFS - Experience from the Field (Part 2)<P>This is a follow-up to my last post where I'll talk about the highlights and lowlights of our TFS deployment project. </P> <P>So how were the requirements met? </P> <UL> <LI.</LI> <LI>VS2003 integration was delivered via the MSSCCI Provider for TFS. </LI> <LI.</LI> <LI).</LI></UL> <P>And what didn't work as expected? Well, there were a few bumps along the way...</P> <UL> <LI.</LI> <LI>We encountered out of memory issues on the Application Tier. This seems to have been related to the first issue, but we still got a couple on a clean TFS database. In the end, VSSConverter coped with this and finished its work successfully.</LI> .</LI></UL> <P>So how did it pan out? You'll need to read my next post to find out.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes Road to TFS - Experience from the Field (Part 1)<P>In this post, I'll outline the TFS deployment project I've been working on over the last 2 months (as part of a dedicated team). Future posts will cover some of the bumps we've run into along the way.</P> <P>Here's the story... The source for one of my customer's major applications lives in a single SourceSafe database that's grown to about 2.5GB. There are over 100 users of this database and a significant portion of them rely on it for most of their day-to-day work. There have been instances where it has become corrupted resulting in an outage and some nervous moments as it was restored from backup. To spice things up, some of the developers are located 400km away in Sydney.</P> <P>Given that TFS has a fairly well documented migration path from VSS, maybe this is nothing special. We did however have to deal with a few complications:</P> <OL> <LI>VS2003 is still being used for all development and that wasn't about to change.</LI> <LI>A central build server based on CruiseControl and NAnt is being used and was intimately linked to VSS.</LI> <LI>The security requirements are non-trivial and needed to be successfully mapped to TFS.</LI></OL> <P>If any of this sounds familiar, you might be interested in my next post. There I'll talk about our approach to getting TFS to deliver on these requirements. We're actually going live this weekend, so by the end of the week, I'll also be able to comment whether we were successful.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes's Andrew?,. <div style="clear:both;"></div><img src="" width="1" height="1">anlynes “Remaining Work” on Your TFS Project Portal (Part 2)<P class=MsoNormalIn my last post, I showed how to construct a URL to get the TFS “Remaining Work” report to target a specific project iteration. Now, let’s have a shot at using this on a project portal.</P> <P class=MsoNormal<?xml:namespace prefix = o<o:p></o:p> </P> <P class=MsoNormalThe good news is that you don’t need anything special for this. As a Site Administrator, open up the project portal in IE and navigate as follows:</P> <OL style="MARGIN-TOP: 0cm" type=1> <LI class=MsoNormalSelect “Site Settings”</LI> <LI class=MsoNormalSelect “Customize home page”</LI> <LI class=MsoNormalJust under the search box in the top right hand side of the page, select “Modify Shared Page”.</LI> <LI class=MsoNormalIn the drop-down, find “Modify Shared Web Parts” and select “Remaining Work”.<o:p> </o:p></LI></OL> <P class=MsoNormalWith a bit of luck, you should now see a panel on the right hand side of the page with a “Link” value of: _layouts/tfsredirect.aspx?IsReport=1&ReportName=Remaining+Work<"> </P> <P class=MsoNormalTo report on Iteration 0 of my project, I need a URL of:</P> <P class=MsoNormal<o:p></o:p> </P> <P class=MsoNormal[Iteration].[Parent_ID].%26[19]</P> <P class=MsoNormal<o:p></o:p> </P> <P class=MsoNormalFor our purposes, we can ditch the protocol and server name from this. This leaves us with:</P> <P class=MsoNormal<o:p></o:p> </P> <P class=MsoNormal/ReportServer/Pages/ReportViewer.aspx?%2fTrial%2fRemaining+Work&rc%3atoolbar=false&rs%3aCommand=Render&IterationParam=[Iteration].[Parent_ID].%26[19]</P> <P class=MsoNormal<o:p></o:p> </P> <P class=MsoNormalAll we need to do is copy this into the “Link” field and “OK” the change. If all has gone well, we should be ready to rock and roll. Just in case you can't tell the difference between the graph below and the one above, I now have less work to do. Yay.</P> <P class=MsoNormal </P> <P class=MsoNormal<A href="" target=_blank><IMG src="" border=0></A></P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes “Remaining Work” on Your TFS Project Portal (Part 1)<P class=MsoNormalOne of the neat things about the “default” project portal is the “Remaining Work” graph. At a glance it can give you an idea on how things are going with your project. However, it can also be misleading. On my current project, we’ve identified quite a few features/tasks that we want to complete in a future iteration. Unfortunately the “graph” shows that we’re drowning. To the guys paying the bills, that’s a bit of a worry.<"><?xml:namespace prefix = o<o:p> </o:p></P> <P class=MsoNormalThe real issue is that the graph includes tasks for all iterations. Obviously the solution is to have it only display data for the current iteration. But how can this be done?</P> <P class=MsoNormal<o:p> </o:p></P> <P class=MsoNormalThe first thing you need to do is figure out what parameters need to be passed to Reporting Services. As it turns out, that’s easier said than done. The “Remaining Work” report is driven from data in Analysis Services. The Iteration parameter is called “IterationParam” and expects values read from the corresponding dimension in the OLAP database. Cutting to the chase, you can’t just provide text such as “Iteration 1” as a value for this parameter. To illustrate, here a URL to display the remaining work for Iterations 0 and 1 of my project:</P> <P class=MsoNormal<o:p> </o:p></P> <P class=MsoNormal<SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"><A href="">[Iteration].[Parent_ID].%26[19]&IterationParam=[Iteration].[Parent_ID].%26[20</A>]</SPAN></P> <P class=MsoNormal<o:p> </o:p></P> <P class=MsoNormalUgly isn’t it? Focus on the first IterationParam value. After URL decoding, this equates to IterationParam=[Iteration].[Parent_ID].&[19]. This may make sense to those that have worked with Analysis Services before. In short, it is identifying the member of the Iteration dimension that has a key of 19. In my case, this corresponds to “Iteration 0”. In your case, it could be anything.</P> <P class=MsoNormal<o:p> </o:p></P> <P class=MsoNormalThe easiest way I’ve found of determining the key to use is to look up the relevant __ID from the TfsWarehouse.dbo.Iteration table in the TFS data tier. All you need to do is find the Iteration Path you’re interested in and read the corresponding key from the __ID field. Armed with this knowledge, you can construct a report query like the one above. In case you haven’t noticed, you can nominate multiple iterations to report on by providing several IterationParam parameters to Reporting Services.<">In my next post, I’ll link this into the Project Portal.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes TFS and WSS<P class=MsoNormal.</P> <P class=MsoNormal<?xml:namespace prefix = o<o:p> </o:p></P> <P class=MsoNormalThe.</P> <P class=MsoNormal<o:p> </o:p></P> <P class=MsoNormalWhen.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes with TFS and SQL Server SP1<P>After successfully conducting a pilot deployment of TFS to a single-server running Windows Server 2003 SP1 and SQL Server 2005 RTM, the time came this week to deploy to production. To make things interesting, we decided to roll-out a dual-server configuration running Windows Server 2003 R2 and SQL Server 2005 SP1.</P> <P>The good news is that it worked... eventually. While Win2k3 R2 posed no challenges, SQL Server SP1 turned out to be somewhat "precious". The latest TFS installation guide recommends that SP1 be used in place of the Analysis Services hotfix. It also recommends that you read the preparation steps and installation instructions for the service pack. That's good advice, but it probably understates the need to become familiar with the SP installation process. We encountered a few issues:</P> <UL> <LI>The service pack throws up a couple of question/warning/information messages such as "Pending Reboot Files Found". These are benign and you can answer "Yes" to proceed. <LI>There are other messages about various files being "in use". This was true, but they were being used by components of SQL Server itself. While it would have been nice for the SP to have sorted this out automatically, we simply shut down the offending services and continued. We probably didn't even need to do this. <LI>After "successfully" installing the SP and rebooting, "Integration Services" failed to start. It turns out that this happened to us because our SQL Server was buried deep within an EDC and didn't have Internet access: <A href=""></A>. The solution... install the "Cumulative hotfix package (build 2153) for SQL Server 2005".</LI></UL> <P>If you're following this, I'd recommend you make a cup of coffee at this point. The hotfixes don't take too long to install, but you've still got a lot of installing to do (of TFS etc). Before leaving the topic of hotfixes, expect to see similar question/warning/information messages that you saw when installing the SP. As before, these are benign.</P> <P>If you're like me and go trawling through server logs looking for things that are broken, you might stumble across the following message in the SQL Agent log:</P> <P><FONT face="Courier New">[298] SQLServer Error: 2812, Could not find stored procedure 'msdb.dbo.xp_sqlagent_notify'. [SQLSTATE 42000] (DisableAgentXPs)</FONT></P> <P>This is a side-effect of SP1 and is benign.</P> <P>Despite all of this, the rest of the TFS deployment went smoothly. Those of you that used the Betas would know that the TFS installation process has come a long way. Based on this experience, it may have actually overtaken SQL Server for ease of installation (well at least SP1).</P> <P>The take-away from this experience... make sure you trial your deployment script to the letter, so you know what to expect when you deploy TFS for real. If I had followed my own advice, I would have saved a few hours diagnosing "possible" SQL Server issues.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes one more thing...<P>If anyone's wondering how to stop the MSSCCI provider for TFS from prompting for a username and password in some cases, take a look at the following:</P> <P><A href=""></A></P> <P>Thanks Grant for the answer.</P><div style="clear:both;"></div><img src="" width="1" height="1">anlynes
http://blogs.msdn.com/b/anlynes/atom.aspx
CC-MAIN-2014-35
refinedweb
4,088
64.3
Blogging is what spawned many content management systems and static site generators. We're living in a world where many people like to share what's on their minds and the best way to do that turns out to be pages ordered by the date of publication. That's basically what a blog is. Here we will build our own blog with Lektor. For a blog we want two models. The model for the blog itself and the model for the blog-post. The idea is that we have a folder called blog which uses the blog model which contains all the blog posts. Each of the blog posts will use the blog-post model. blog.ini This is the model for the blog itself. It instructs Lektor that all of the pages below it will be blog posts, how many blog posts we want to show per page and what the order is. We also set it to hidden and protected which will make it unavailable in the admin ( hidden) for new pages and make it impossible to delete ( protected). This means we need to manually create the one page later which will use this. [model] name = Blog label = Blog hidden = yes protected = yes [children] model = blog-post order_by = -pub_date, title [pagination] enabled = yes per_page = 10 blog-post.ini Each blog post has a title, publication date, author and body. The publication date and title are also used for sorting if you look into the blog.ini. Lastly we set up the label of the page to be the title of the blog post. We can also set it to hidden as the model is automatically selected in the admin whenever a page is created in the blog. [model] name = Blog Post label = {{ this.title }} hidden = yes [fields.title] label = Title type = string size = large [fields.pub_date] label = Publication date type = date width = 1/2 [fields.author] label = Author type = string width = 1/2 [fields.body] label = Body type = markdown Now that we have the models set up, we want to create the templates. blog.html Let's start with the blog overview page. This template is used for our model. In this example we just want to show the titles of the post on the overview page with the author and date and a controller for the pagination. Because pagination is enabled we can iterate over this.pagination.items instead of this.children which will return only the items for the intended page. {% extends }} </li> {% endfor %} </ul> {% if this.pagination.pages > 1 %} {{ render_pagination(this.pagination) }} {% endif %} {% endblock %} For the pagination macro have a look at the pagination guide which covers that part. blog-post.html Now we just need a template for our blog post. This ( blog-post.html) will do: {% extends "layout.html" %} {% block title %}{{ this.title }} | My Blog{% endblock %} {% block body %} <h1>{{ this.title }} <p class="meta"> by {{ this.author }} on {{ this.pub_date|dateformat('full') }} <div class="body">{{ this.body }}</div> {% endblock %} Now that we have models and templates we just need to designate a part of the website as blog. For that create a new folder in your content/ folder with the name of your blog. For instance just content/blog and put a contents.lr file with this content in: _model: blog Now you can head to the admin UI to create new blog posts. With the above settings the blog will live at blog/ and the posts at blog/<post-slug>. But what if you want to put the date of the blog post into the URL? That's thankfully very easy. All you need to do is to set up a new URL format for the children. Just edit blog.ini and add this to the [children] section: slug_format = {{ (this.pub_date|dateformat('YYYY/M/') if this.pub_date) ~ this._id }} What this does is that it will prepend the year ( YYYY) and month ( M) to the ID of the page if the publication date is configured. Otherwise it will just use the ID of the page. With this change our blog post will move from for instance blog/hello/ to blog/2015/12/hello/.
https://www.getlektor.com/docs/guides/blog/
CC-MAIN-2019-09
refinedweb
691
76.22
! After a long wait (thank you for your patience!), the WDF 1.7 coinstallers are now up on the connect site. To get the bits Enjoy and let the signing and shipping of v1.7 WDF drivers begin! This is a pretty cool and somewhat obscure debugger command. It allows you to tell the debugger what functions to skip if you are using the trace command ('t'). I think of the trace command as the 'step into' command though, but that is just me. Let's say we have the following simple application: #include <stdio.h> struct Foo { Foo() : m_value(0) { } int Increment() { return ++m_value; } static void Print(int i) { printf("%d\n", i); } int m_value; }; int _cdecl main(int argc, char *argv[]) { Foo f; Foo::Print(f.Increment()); return 0; } If I were to run the program under the debugger and use the 't' command for each line, it would step into every function. I typically use 't' instead of 'p' because I usually want to step into a function at some point in time and I tend to press 'p' one too many times ;). Here is an example of the debugger session: 0:000> g test!main > 13: { 0:000> t > 14: Foo f; 0:000> t > 4: Foo() : m_value(0) { } 0:000> t > 15: Foo::Print(f.Increment()); 0:000> t > 6: int Increment() { return ++m_value; } [1] 0:000> t > 15: Foo::Print(f.Increment()); 0:000> t > 7: static void Print(int i) { printf("%d\n", i); } [2] 0:000> gu > 16: return 0; 0:000> t > 17: } 0:000> t test!__mainCRTStartup+0x102: Let's look at the statement Foo::Print(f.Increment()); When using the trace command, it will first step into Foo::Increment ([1]) before stepping into Foo::Print() ([2]). But let's say that I never want to step into Foo::Increment because I know that it is a simple function that I do not want to debug. I can tell the debugger to ignore trace commands into this function with the .step_filter command. The command takes a semi-colon delineated list of fully qualified symbol names (which can include wildcards so you can filter out entire modules) to ignore. Let's see the debugger session again with this command: 0:000> g test!main > 13: { 0:000> .step_filter "test!Foo::Increment" Filter out code symbols matching: test!Foo::Increment 0:000> t > 14: Foo f; 0:000> t > 4: Foo() : m_value(0) { } 0:000> t > 15: Foo::Print(f.Increment()); 0:000> t > 7: static void Print(int i) { printf("%d\n", i); } 0:000> gu > 16: return 0; 0:000> t > 17: } 0:000> t test!__mainCRTStartup+0x102: You will see now that when I trace into Foo::Print(f.Increment()); that the f.Increment() call is executed but not trace into (ignored is not the right word because it has run, I just didn't see it line by line) and I step directly into Foo::Print(). I think this is a pretty powerful debugger command, it can save you a lot of time if you are always accidentally stepping into the wrong function like I always do ;). One PreviousIrql) { KeRaiseIrql(DISPATCH_LEVEL, PreviousIrql); [spin on the lock until it has been acquired] } VOID KeRaiseIrql(KIRQL NewIrql, PKIRQL, PKIRQL OldIrql) { OldIrql = KeGetCurrentIrql(); [raise IRQL to NewIrql] } What I want to emphasize is that KeAcquireSpinLock will retrieve the current IRQL (to know what to restore the IRQL to when the lock is released) as a part of acquiring the spin lock. Retrieving the current irql is a relatively expensive operation. Enter KeAcquireSpinLockAtDpcLevel. KeAcquireSpinLockAtDpcLevel does away with the IRQL change and just implements [spin on the lock until it has been acquired], but it does this with a large caveat…you must be running at DISPATCH_LEVEL (in reality it requires IRQL >= DISPATCH_LEVEL, but that is another discussion for another day) . It requires DISPATCH_LEVEL or higher so that you do not deadlock. Another caveat to effectively use KeAcquireSpinLockAtLevel you must know 100% that you are at DISPATCH_LEVEL. Naively, one could think that the following code optimizes for both cases if (KeGetCurrentIrql() < DISPATCH_LEVEL) { KeAcquireSpinLock(&lock, &oldIrql); } else { KeAcquireSpinLockAtDpcLevel(&lock); } But the problem here is that in the case of the current IRQL < DISPATCH_LEVEL, the current IRQL is being retrieved twice (once in your code, once in KeAcquireSpinLock), so this relatively expensive operation is being performed twice when it should be performed only once. What all of this boils down to is that you must know with 100% certainty that the current IRQL is DISPATCH_LEVEL before you can use KeAcquireSpinLockAtDpcLevel effectively. Here are a couple of contexts here you can know for certain that the IRQL is DISPATCH_LEVEL. Notice that a completion routine is not guaranteed to be called at IRQL == DISPATCH_LEVEL! While you may see that it is called at dispatch, it is not something that you can rely on 100% of the time. For instance, the lower driver could complete the IRP at passive level in an error condition. I have no idea who created the name for PNP_DEVICE_NOT_DISABLEABLE, but I probably have the same reaction as you ... "seriously? that is what they named?" I mean come on, I think it could have at least been named PNP_DEVICE_CANNOT_BE_DISABLED. I am sure you can think of some better names too. If so, please leave a comment with your suggestions! While we had a chance to rectify this in KMDF in the WDF_DEVICE_STATE structure, we chose to keep the field name (NotDisableable) similar to the WDM name to avoid confusion. For any readers who have not encountered this bit, it is a part of PNP_DEVICE_STATE. You set this bit in the IRP_MJ_PNP/IRP_MN_QUERY_PNP_DEVICE_STATE IRP after calling IoInvalidateDeviceState. identified that my driver had leaked pool. The code looked something like this // Globals UNICODE_STRING gRegistryPath = { 0 }; NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) { NTSTATUS status; DriverObject->DriverUnload = DriverUnload; gRegistryPath.Length = RegistryPath->Length; gRegistryPath.MaximumLength = RegistryPath->MaximumLength; gRegistryPath.Buffer = (PWCHAR) ExAllocatePoolWithTag(PagedPool, gRegistryPath.MaximumLength, [tag]); if (gRegistryPath.Buffer == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } RtlCopyMemory(gRegistryPath.Buffer, RegistryPath->Buffer, gRegistryPath.Length); status = RegisterWithPortDriver(DriverObject, ...); if (!NT_SUCCESS(status)) { return status; } <== leak right here! // ... other init ... return status; } void DriverUnload(PDRIVER_OBJECT DriverObject) { ExFreePool(gRegistryPath.Buffer); RtlZeroMemory(&gRegistryPath, sizeof(gRegistryPath)); } While many WDM drivers do very little outside of initializing the dispatch table and other fields in their DriverObject, a miniport driver or a KMDF driver must register with their port driver (like ScsiPortInitialize) or framework (WdfDriverCreate) and this registration can introduce failure in DriverEntry (just like in my code sample above). What to do? In a WDM driver you have to be very careful and manage this manually. Either you have a common error exit path out of DriverEntry which performs the cleanup (or manually calls your DriverUnload routine) or cleanup on each possible point of error. This pattern is very easy to get wrong and is not very maintainable, it is quite easy to add a new allocation and forget to cleanup it up later. In a KMDF driver things are a bit easier to manage if you follow a particular pattern. While EvtDriverUnload has the same problems as the WDM DriverUnload, the EvtObjectCleanup routine registered on the WDFDRIVER is called in both scenarios. To re-emphasize, the EvtObjectCleanup registered on WDFDRIVER will be called when either DriverEntry returns !NT_SUCCESS or if your driver is gracefully unloaded later. This means that if you put all of your cleanup in the cleanup routine your DriverEntry implemention becomes much simpler. The one caveat is that the call to WdfDriverCreate must come before any allocations in your driver or state chaning APIs. WPP_INIT_TRACING is one such state changing API where you must undo its effects by calling WPP_CLEANUP. Quite a few WDK samples show this pattern (although suprisingly to me, not all!), let us look at the nonpnp sample (%wdk%\src\kmdf\nonpnp\sys\nonpnp.c) NTSTATUS DriverEntry( IN OUT PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath ) { NTSTATUS status; WDF_DRIVER_CONFIG config; WDFDRIVER hDriver; PWDFDEVICE_INIT pInit = NULL; WDF_OBJECT_ATTRIBUTES attributes; WDF_DRIVER_CONFIG_INIT(&config, WDF_NO_EVENT_CALLBACK); // Tell the framework that this is non-pnp driver so that it doesn't set the default AddDevice routine. config.DriverInitFlags |= WdfDriverInitNonPnpDriver; // NonPnp driver must explicitly register an unload routine for the driver to be unloaded. config.EvtDriverUnload = NonPnpEvtDriverUnload; // Register a cleanup callback so that we can call WPP_CLEANUP when // the framework driver object is deleted during driver unload. WDF_OBJECT_ATTRIBUTES_INIT(&attributes); attributes.EvtCleanupCallback = NonPnpEvtDriverContextCleanup; status = WdfDriverCreate(DriverObject, RegistryPath, &attributes, &config, &hDriver); if (!NT_SUCCESS(status)) { KdPrint (("NonPnp: WdfDriverCreate failed with status 0x%x\n", status)); return status; } // Since we are calling WPP_CLEANUP in the DriverContextCleanup // callback we should initialize WPP Tracing after WDFDRIVER // object is created to ensure that we cleanup WPP properly // if we return failure status from DriverEntry. This // eliminates the need to call WPP_CLEANUP in every path // of DriverEntry. WPP_INIT_TRACING( DriverObject, RegistryPath ); ... return status; } VOID NonPnpEvtDriverContextCleanup(WDFDRIVER Driver) { WPP_CLEANUP(WdfDriverWdmGetDriverObject(Driver)); } The red comments show what is going on. Hopefully the code is self explanatory. Incidentally, another pattern you can use for global memory allocations is to allocate the memory with WdfMemoryCreate without specifying a parent object. The WDFDRIVER will be the parent object by default and since all child objects are destroyed when the parent is destroyed, all of your allocations will be destroyed after EvtDriverUnload has been called when the WDFDRIVER is destroyed in the unload path. During One of things I did while owning this driver was unify crash dump support for all builds. Previous to my owning the driver, Microsoft Far East Asia PSS added the ability to crash (aka crash dump) the machine for any given key and modifier combination (see I8xServiceCrashDump() for initialization of state and I8xProcessCrashDump() on processing the keys at runtime in 6000\src\input\pnpi8042 in the WDK for the gory details). This code was under #ifdefs and was only live for far east builds of the driver. This was a universally useful feature and I was asked to make it available for all builds. I decided to make it easy for folks to enable it as well. Configuration was not easy. First, you had to know the scan code for the trigger key (instead of the character itself). Second you had to describe the modifiers using a set of flags that were only documented in the driver's header. Third, you had to know where to put these registry values (which typically meant you also had to create a reg key as well). Yuck, not friendly. To fix this I created one registry value (CrashOnCtrlScroll) that setup the default crash dump key sequence for you, right ctrl + scroll lock. This KB article describes how to set the key. That worked well ... except that many laptops did not have a right control key! I didn't want to create another key for crashing on left ctrl + scroll lock (or something as arbitrary but completely different) so I created a GUI application that let you type the key and select the modifiers. Not rocket science, but functional. Here is a snapshot Issue #1: While functional, it's ugly Issue #2: I named it cdsetup.exe (c[rash]d[ump]setup.exe). Logical name except that many cdrom setup applications are also called cdsetup.exe so there was a bit of confusion. To add to the confusion, I think my version of cdsetup.exe was a part of the Windows 200 resource kit. The one saving grace to this name is that it automatically requests elevation on Vista (probably because it has "setup" its name). Issue #3: After recompiling the application yesterday to test it on Vista the red X, Cancel and OK buttons all stopped working which meant I could not dismiss the dialog box. Weird. I found an old build and it worked just fine so something I did during the recompile altered the behavior. To get the application to build and run I had to add the following 2 lines to the sources file USE_MSVCRT=1 _NT_TARGET_VERSION=$(_NT_TARGET_VERSION_WIN2K) Specifying the taret version has no effect on the runtime so it must have been the conversion to the MS VC runtime instead of the old C runtime that shipped with Windows. I decided to debug the application's DlgProc. It is rather simple: LRESULT CALLBACK CrashDumpSetup::s_DlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { CrashDumpSetup *cdi; if (message == WM_INITDIALOG) { cdi = new CrashDumpSetup(hDlg); if (!cdi) return FALSE; SetWindowLongPtr(hDlg, DWLP_USER, (ULONG_PTR) cdi); return (LRESULT) cdi->Initialize(); } cdi = (CrashDumpSetup *) GetWindowLongPtr(hDlg, DWLP_USER); if (cdi) { return cdi->DialogProc(message, wParam, lParam); } return FALSE; } LRESULT CrashDumpSetup::DialogProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_DUMP_DISABLE: case IDC_DUMP_DEFAULT: case IDC_DUMP_ALT: ToggleAltUI(LOWORD(wParam) == IDC_DUMP_ALT); break; case IDOK: if (Apply() == FALSE) { return FALSE; } __fallthrough; case IDCANCEL: delete this; EndDialog(m_hDlg, LOWORD(wParam)); break; } } return FALSE; } When pressing the red X, Cancel or OK keys my WM_COMMAND processing code ran and called EndDialog() as I expected, but like I said before, the dialog didn't dismiss itself. I looked at the docs for EndDialog and saw that it returns a BOOL, so I rewrote EndDialog to capture the return value and it was returning FALSE! Ugh. Since I was single stepping through the function, !gle came to the rescue 0:000> !gle LastErrorValue: (Win32) 0x578 (1400) - Invalid window handle. LastStatusValue: (NTSTATUS) 0xc0000034 - Object Name not found. An invalid window handle? m_hDlg worked before, maybe some component was overwriting it. So dumped the variable and then the hDlg from s_DlgProc, 0:000> dt this m_hDlg Local var @ 0x1ff798 Type CrashDumpSetup* 0x00a01f88 +0x000 m_hDlg : 0x00a064d0 HWND__ 0:000> .f+ 01 001ff7cc 775af512 cdsetup!CrashDumpSetup::s_DlgProc+0x8f [d:\work\cdsetup\cdsetup.cpp @ 576] 0:000> dt hDlg Local var @ 0x1ff7d4 Type HWND__* 0x004e05f0 +0x000 unused : 49595140 Looking at the 2 values, it is obvious that m_hDlg was altered. But how? After staring at the code I wrote 7 years ago, I thought about what I changed (using the MS C runtime) and I immediate saw it. I was deleting the object and then touching freed memory. The old C runtime left the freed memory as it was before itw as freed so the old code had the bug the entire time, it was just that the new runtime caught made the mistake apparent immediately. The fix was simple, capture the value before deleting the object and then calling EndDialog (I guess I could have called EndDialog in the destructor but that made cleanup in the failure to initialize the object potentially problematic). After applying the fix, all of the buttons now worked as expected ;). case IDCANCEL: HWND h = m_hDlg; delete this; EndDialog(h m_hDlg, LOWORD(wParam)); break; that if such a driver is installed, the stability of the system is not compromised. The scenario I am covering is not the case where you are enumerating child devices and want to share resources assigned to the parent amongst the children. Rather, this is sharing HW resources assigned to your device (device A) with another device (device B). Device B can be a legacy NT4 style device or another PnP device stack, it doesn't matter. There are 3 aspects to the issue that you must solve: Aspects number 1 and 2 I will leave for you to solve. Number 3 is where things get interesting. There are scenarios where the device can lose power: The first 2 scenarios in green are easily solved. Device B registers for PnP notifications on the file handle that it opens and it will be told when a PnP remove or surprise removal occurs. If you are using KMDF, the WDFIOTARGET automatically does this for you. But there is a catch to the surprise removal notification...it is sent to device B after device A has already processed the PnP IRP. This means that there is a window where device B thinks it has valid resources, but in reality it does not. File handle notifications do not solve the last 2 scenarios though and the surprise removal case does not work well, so it would be nice if there was one solution for all 4 scenarios. The solution is that device B must register 2 callbacks with device A, a power up and power down callback (they can be condensed to one callback with an additional passed in parameter indicating power state if you want). These callbacks should be set at the same time that the resources are acquired so that there is no window where the resources have been acquired, the device loses power and the callback has not yet been set notifying device B of the power state change. These callbacks can be passed from device B to device in any number of ways. Two traditional ways are Once the callbacks have been set, device A must call them at the right time. In a KMDF driver, it is a very simple implementation. You call device B's power up callback in EvtDeviceSelfManagedIoRestart and device B's power down routine in EvtDeviceSelfManagedIoSuspend. This covers all cases because KMDF treats PnP state changes as implicit power changes, powering down the device and using the same callbacks for all cases. This also covers the surprise removal window because device B is now notified at the beginning of device A's power down instead of after it. One final thing to consider is what device B thinks the initial power state of device A is in. Ideally, device B should assume device A is in low power and should not touch the retrieved resources until its power up callback has been invoked. This would mean that the initial call to device B's power up call might occur outside of EvtDeviceSelfManagedIoRestart, perhaps immediately after completing the IOCTL_INTERNAL_GET_RESOURCES request. If you are writing a WDM driver, well, I will leave that implementation up to you ;). When.
http://blogs.msdn.com/doronh/
crawl-001
refinedweb
2,971
52.9
Wildest programming language idea What is your wildest programming language idea? This could be fun (silly) ideas or really cool and useful ones. Go! Also on le twatter: I present... Cxx A static language that is weakly typed with implicit type coercion no matter what you do. For example: int number = 5; Console.Log(typeof number); Your output will be: <= Array[5]: [ Number, String, Boolean, Array, Null ] Now, imagine you have another number: int number2 = 10; Adding them together gives: <= "105" Due to type coercion. Also, the same thing does not happen to strings: String number1 = "5"; String number2 = "10"; Console.Log(number1 + number2); <= Error: Cannot add two arrays Due to strings being converted into Arrays. Because of type coercion, this is logic: 5 == "100" => true // (both can be converted into booleans of true) 0 == 0 => false // (0 is not the same as false) 2 == 1 => true // (2 = true = 1) "string" == "string" => false // (they have become arrays and require a deep equal in order to be true) "5" == "2" => false // (same problem as above) (Char)"5" == (Char)"2" => true // (both have become booleans due to explicit type) Due to the nature of RegExp, RegExp has not been considered a type. It is considered a substance. A substance is that of a type, but it cannot be coerced for it is too pure. Substances are similar to classes, but they are not. Substance.RegExp myRe = (new)Substance.RegExp(@"[^\d][\d\w]+"gi); Console.Log(typeof myRe); => Substance.RegExp Equalities with substances do not give you sane answers. Substance.RegExp myRe = (new)Substance.RegExp(@"[^\d][\d\w]+"gi); Substance.RegExp myRe2 = (new)Substance.RegExp(@".+"gi); myRe == myRe2 => How Dare you Even Try To Compare Substances! Do you even know THE tRue Po𝑤͙͎̔̈́͠𝑒̦͔̙̓̓͌𝑟̡̫͌͑͘͜ o̸͖͚̓͆͠͝f̴̨̡̢̜͙̣̗͎̗̮̤̮̞̘̻͆̄̾̾͑̅͋͋̋͠ͅ ̶̧̧̡̱̳͔̙̬͈͈͍̗̊̌̊͌͑̓̍́̃͝s̴̢̨̞̩̱͈̙̥͖͎͖̭̣̠̓̔̔͊́̊̌̈̄̽̽̇̓͌͐͜͝ͅu̷̡̡̳̻̣̟͍̥͍͉̤̦̟̫͓̖͑̀̏͒̓͛̉̓̂̇ç̸̛͖̖̘̠̲̫̜̮̭̫͎̭͚̻̯̘̌͆̆̑͌̑̃̍̈́͒͊͘̕̚̚͝h̸̢̨̡̤̯͎͓̞͍͇̖̖̼̝͆̀̓̀̋͛̑̚ ̵̭̺̲̻̳͓͇̲͛̒̈̔̀̋̓̂̓̾̐͆͒̂͝͝t̸̞̩͙̖̞̱̭̟̭̮͉̲̠̊̑̀̌̋͆̄͂̑͑́͜͠h̵͉̰͆̔̊̐̈́͂̃̄̑̃̋̊͛͂͌ï̴̢̧͍̳͍̅̈́͛̑̓͗̿̒͌̿͛̒̄̚͠ṇ̵̢̾̊̄̈̏̎̍͐̅̌̔̀̕͝g̸̡̻̟̭͇̤͓͙͕̫̿̋͗͑͗̃̄̈́͝s̶̤͕̻̼̣͓̻̤̫͇̥̱̮͖͕̳̆̉̿̅̋̋͛̐̽͘͜ ̸̝̓̿́̎̓͘ỵ̵̨̧̯͍̱̫̲̘̩̘̏͋͑o̶̡̲̥͙̣̥̝̰̣͗͐̂͗̄̓̈́͜ű̵̠͐̓̋̓͐̊̃̿̚͠ ̵͓͉̕s̷̡̖̭̥̫̼̥̒̇͋́̏̀̚m̷͇͈̗͚̗͉̩̖̹͍͉͖͔̼̅̍̓̑̈̋̃͛͛̕a̵͚̣̯̫̮̬̞͚̙͎̹̋̈́̅̄̐͒̋̈́̇́̚͝ḽ̸̗̬͍̫̣̠̿̓͆l̷͖͕̣̳͉͙͇̀͋͒͋̊̉̄̅̀͝͠ ̴̡̡̛̻̟̖͍̘̃̈͐͛̌́͂͂́̑̃͌̆̋̽̚b̸͇̭̦̬̝͔̈́͂̊͌̿ȑ̷̨͉̱̬̮̩͉̘͎̩̩̙͓͙̊̈́́͊̿̾͠à̸̡̳̝̫̘̯͙͚͎̺̋͛̔̔͒̐͆͌̈́̕i̸̜͆̿̈́͑͌̏̂̑̾̈̎͝n̵̢͚̥͈̰͚̐̐̅́̌̉̃͆͛̈́̃̇ ̸̤̲̲͕̘͇̞͔́͊̃͐͑̅̿̓̾̊̈́̕̕͜p̵̡̖̖̙̝̬̪͈̙̖͓̙͚͛r̴̛͔̳̺̺̪̓͒̈́̄̈́͌̔̑̿̏̕ȍ̸̢̠̖̩̫͕͔̣̘͕̳̽̏̾̈̆̔́̈̄͘͘ͅģ̸̛͇̿̐͗̾͂̆̀̈́̌̋̋̍̑̈́͠ř̶͈͚̥̱͚̹͉͙̯̞͓̬̑̕à̷̰̲͕̯͇͓̖͉͚̒̉͜ͅm̶̨̦̰̱̪̤̻̯̙̔͆̈́͐́̚͝m̵̡͔̰͇͓̮̣̱̞̜̥̣̤̂͜e̶̛̠̝͉r̵̢̧̛̹͎̜̘͙̻̫̙̦̻̜̟͕̱͑̃̍͌̈́̃̓͊̿̕͜ Funnily enough, no errors are thrown. Now, to define a function, you do: void FunctionName(int arg1, int arg2) { return arg1+arg2; } Of course, a return value is not required. Return values follow the same implicit type coercion. Surprisingly, you can convert functions into Substances: void FunctionName(int arg1, int arg2) { // Code } (Substance.Generic)SubtanceFunction = FunctionName; However, the function has become a substance, but the code does not. This means, comparing it to other Substances will give you the same result as the RegExp had: void Function1(int arg1, int arg2) { // Code } void Function2(int arg1, int arg2) { // Code } (Substance.Generic)SubstanceFunction = Function1; (Substance.Generic)SubstanceFunction2 = Function2; SubstanceFunction = SubtanceFunction2 => How Dare you Even Try To Compare Substances! Do you even know THE tRue Po𝑤͙͎̔̈́͠𝑒̦͔̙̓̓͌𝑟̡̫͌͑͘͜ o̸͖͚̓͆͠͝f̴̨̡̢̜͙̣̗͎̗̮̤̮̞̘̻͆̄̾̾͑̅͋͋̋͠ͅ ̶̧̧̡̱̳͔̙̬͈͈͍̗̊̌̊͌͑̓̍́̃͝s̴̢̨̞̩̱͈̙̥͖͎͖̭̣̠̓̔̔͊́̊̌̈̄̽̽̇̓͌͐͜͝ͅu̷̡̡̳̻̣̟͍̥͍͉̤̦̟̫͓̖͑̀̏͒̓͛̉̓̂̇ç̸̛͖̖̘̠̲̫̜̮̭̫͎̭͚̻̯̘̌͆̆̑͌̑̃̍̈́͒͊͘̕̚̚͝h̸̢̨̡̤̯͎͓̞͍͇̖̖̼̝͆̀̓̀̋͛̑̚ ̵̭̺̲̻̳͓͇̲͛̒̈̔̀̋̓̂̓̾̐͆͒̂͝͝t̸̞̩͙̖̞̱̭̟̭̮͉̲̠̊̑̀̌̋͆̄͂̑͑́͜͠h̵͉̰͆̔̊̐̈́͂̃̄̑̃̋̊͛͂͌ï̴̢̧͍̳͍̅̈́͛̑̓͗̿̒͌̿͛̒̄̚͠ṇ̵̢̾̊̄̈̏̎̍͐̅̌̔̀̕͝g̸̡̻̟̭͇̤͓͙͕̫̿̋͗͑͗̃̄̈́͝s̶̤͕̻̼̣͓̻̤̫͇̥̱̮͖͕̳̆̉̿̅̋̋͛̐̽͘͜ ̸̝̓̿́̎̓͘ỵ̵̨̧̯͍̱̫̲̘̩̘̏͋͑o̶̡̲̥͙̣̥̝̰̣͗͐̂͗̄̓̈́͜ű̵̠͐̓̋̓͐̊̃̿̚͠ ̵͓͉̕s̷̡̖̭̥̫̼̥̒̇͋́̏̀̚m̷͇͈̗͚̗͉̩̖̹͍͉͖͔̼̅̍̓̑̈̋̃͛͛̕a̵͚̣̯̫̮̬̞͚̙͎̹̋̈́̅̄̐͒̋̈́̇́̚͝ḽ̸̗̬͍̫̣̠̿̓͆l̷͖͕̣̳͉͙͇̀͋͒͋̊̉̄̅̀͝͠ ̴̡̡̛̻̟̖͍̘̃̈͐͛̌́͂͂́̑̃͌̆̋̽̚b̸͇̭̦̬̝͔̈́͂̊͌̿ȑ̷̨͉̱̬̮̩͉̘͎̩̩̙͓͙̊̈́́͊̿̾͠à̸̡̳̝̫̘̯͙͚͎̺̋͛̔̔͒̐͆͌̈́̕i̸̜͆̿̈́͑͌̏̂̑̾̈̎͝n̵̢͚̥͈̰͚̐̐̅́̌̉̃͆͛̈́̃̇ ̸̤̲̲͕̘͇̞͔́͊̃͐͑̅̿̓̾̊̈́̕̕͜p̵̡̖̖̙̝̬̪͈̙̖͓̙͚͛r̴̛͔̳̺̺̪̓͒̈́̄̈́͌̔̑̿̏̕ȍ̸̢̠̖̩̫͕͔̣̘͕̳̽̏̾̈̆̔́̈̄͘͘ͅģ̸̛͇̿̐͗̾͂̆̀̈́̌̋̋̍̑̈́͠ř̶͈͚̥̱͚̹͉͙̯̞͓̬̑̕à̷̰̲͕̯͇͓̖͉͚̒̉͜ͅm̶̨̦̰̱̪̤̻̯̙̔͆̈́͐́̚͝m̵̡͔̰͇͓̮̣̱̞̜̥̣̤̂͜e̶̛̠̝͉r̵̢̧̛̹͎̜̘͙̻̫̙̦̻̜̟͕̱͑̃̍͌̈́̃̓͊̿̕͜ Finally, if you try to compare a normal function to a substance function, you get: void NormalFunc(int arg1, int arg2) { // Code } (Substance.Generic)SubstanceFunc = NormalFunc; SubstanceFunc == NormalFunc => 1 1 is the result you will get no matter what is being compared to any substance. And that is all for this language! Rumors are that JavaScript is written on top of Cxx. LOL well don't all static languages have similar syntax literally 3 of them are nearly the same int c = 5; int cpp = 6; int cs = 7; LOL @johnstev111 @Coder100 This is the best part: SubstanceFunction = SubtanceFunction2 => How Dare you Even Try To Compare Substances! Do you even know THE tRue Po𝑤͙͎̔̈́͠𝑒̦͔̙̓̓͌𝑟̡̫͌͑͘͜ o̸͖͚̓͆͠͝f̴̨̡̢̜͙̣̗͎̗̮̤̮̞̘̻͆̄̾̾͑̅͋͋̋͠ͅ ̶̧̧̡̱̳͔̙̬͈͈͍̗̊̌̊͌͑̓̍́̃͝s̴̢̨̞̩̱͈̙̥͖͎͖̭̣̠̓̔̔͊́̊̌̈̄̽̽̇̓͌͐͜͝ͅu̷̡̡̳̻̣̟͍̥͍͉̤̦̟̫͓̖͑̀̏͒̓͛̉̓̂̇ç̸̛͖̖̘̠̲̫̜̮̭̫͎̭͚̻̯̘̌͆̆̑͌̑̃̍̈́͒͊͘̕̚̚͝h̸̢̨̡̤̯͎͓̞͍͇̖̖̼̝͆̀̓̀̋͛̑̚ ̵̭̺̲̻̳͓͇̲͛̒̈̔̀̋̓̂̓̾̐͆͒̂͝͝t̸̞̩͙̖̞̱̭̟̭̮͉̲̠̊̑̀̌̋͆̄͂̑͑́͜͠h̵͉̰͆̔̊̐̈́͂̃̄̑̃̋̊͛͂͌ï̴̢̧͍̳͍̅̈́͛̑̓͗̿̒͌̿͛̒̄̚͠ṇ̵̢̾̊̄̈̏̎̍͐̅̌̔̀̕͝g̸̡̻̟̭͇̤͓͙͕̫̿̋͗͑͗̃̄̈́͝s̶̤͕̻̼̣͓̻̤̫͇̥̱̮͖͕̳̆̉̿̅̋̋͛̐̽͘͜ ̸̝̓̿́̎̓͘ỵ̵̨̧̯͍̱̫̲̘̩̘̏͋͑o̶̡̲̥͙̣̥̝̰̣͗͐̂͗̄̓̈́͜ű̵̠͐̓̋̓͐̊̃̿̚͠ ̵͓͉̕s̷̡̖̭̥̫̼̥̒̇͋́̏̀̚m̷͇͈̗͚̗͉̩̖̹͍͉͖͔̼̅̍̓̑̈̋̃͛͛̕a̵͚̣̯̫̮̬̞͚̙͎̹̋̈́̅̄̐͒̋̈́̇́̚͝ḽ̸̗̬͍̫̣̠̿̓͆l̷͖͕̣̳͉͙͇̀͋͒͋̊̉̄̅̀͝͠ ̴̡̡̛̻̟̖͍̘̃̈͐͛̌́͂͂́̑̃͌̆̋̽̚b̸͇̭̦̬̝͔̈́͂̊͌̿ȑ̷̨͉̱̬̮̩͉̘͎̩̩̙͓͙̊̈́́͊̿̾͠à̸̡̳̝̫̘̯͙͚͎̺̋͛̔̔͒̐͆͌̈́̕i̸̜͆̿̈́͑͌̏̂̑̾̈̎͝n̵̢͚̥͈̰͚̐̐̅́̌̉̃͆͛̈́̃̇ ̸̤̲̲͕̘͇̞͔́͊̃͐͑̅̿̓̾̊̈́̕̕͜p̵̡̖̖̙̝̬̪͈̙̖͓̙͚͛r̴̛͔̳̺̺̪̓͒̈́̄̈́͌̔̑̿̏̕ȍ̸̢̠̖̩̫͕͔̣̘͕̳̽̏̾̈̆̔́̈̄͘͘ͅģ̸̛͇̿̐͗̾͂̆̀̈́̌̋̋̍̑̈́͠ř̶͈͚̥̱͚̹͉͙̯̞͓̬̑̕à̷̰̲͕̯͇͓̖͉͚̒̉͜ͅm̶̨̦̰̱̪̤̻̯̙̔͆̈́͐́̚͝m̵̡͔̰͇͓̮̣̱̞̜̥̣̤̂͜e̶̛̠̝͉r̵̢̧̛̹͎̜̘͙̻̫̙̦̻̜̟͕̱͑̃̍͌̈́̃̓͊̿̕͜ @RahulChoubey1 Windows dynamic linked libraries if you don't know something, use google You could some up with a better name, because Cxx sounds like a few other programming languages I've heard [email protected] I present to you my truly innovative language: Singularity You are only allowed one variable per script and it must be Elon_Musk All functions can only return values in binary When the script ends the program will automatically print the number 3 trending result on Google Trends Your output will be emailed to you within 8-10 business days during which time we convert your program your program into punch cards. All errors are returned to you with a snarky comment about your hygiene All while loops are infinite no matter what you do The documentation is written in Ancient Sanskrit and all attempts of trying to translate it have resulted in mildly unsuccessful careers, Although we do provide a good Dental plan @DynamicSquid that is nice. i kinda wanna make this into a language just for the sake of it but i have a weak spot in Ancient sanskrit @SpaceFire All errors are returned to you with a snarky comment about your hygiene snarky comment about your hygiene animal crossing wild world resetti end line intensifies If I had multiple files, would it be 1 script for each of those, or 1 script per [email protected] I've been thinking about making a language entirely in Spanish, so you could end up with something like this: público entero[] x = [1, 2, 7, 3] por-cada i en x { poner(i) } @DynamicSquid @SixBeeps Me too same, I just know Bonjour of Spanish. but trying to learn more :) Bonjour is French. Hola is Spanish. (I learn Both) @DynamicSquid @SixBeeps @PattanAhmed @JoeyRueff Ah ok. Yeah, I could do something like that, but the Spanish idea is what I'd do if I ever need to make my own language. I present to you my truly innovative language: ??? Code will only compile and run when the programmer has died. Therefore, no one really knows the syntax of this language because we don't know how to raise people from the dead, yet... @Warhawk947 for when you actually have to spend sweat tears and blood on a project 😜 But surely, the children of the first programmer could learn from their ancestor, by watching the program run after the programmer has died, and pass the knowledge down the [email protected] How about Reversethon, where all your code is backward. Example: )"dlrow olleh"(tnirp The chicken for x in chicken: print("no") Is translated in chicken to: chickenchickenchicken chicken chickenchicken chickenchickenchickenchickenchicken: chicken("chickenchicken") SplatLang - A Splatoon themed programming language sorry for terrible joke that could have come from sans himself Basics: - file extension: .splat - as much esolang as useful - splatoon themed syntax (you could have guessed) - safe like C# - a few good data types - a built in help method - and more! Woomy - Print method The method for printing something to the console is woomy(). This is a sample of using woomy(): Input: woomy("Hello, Inkopolis!") // this is a single line comment comment /^ this is a squid comment. goes over multiple lines. named that because the ^s look kinda like squids. will end with: ^/ Output: Hello, Inkopolis! Veemo - Builtin slowprint method. veemo() will print something to the console, but wait in between each character printed. A value for how much time to wait is measured in milliseconds Input: veemo("Hello, octo valley!", 60) Output (with 0.06 seconds in between characters: Hello, octo valley! Getting input The method for input is playAnotherBattle() with the prompt inside the ()s. If you put in nothing, then the prompt will automatically be >>. Input: playAnotherBattle("Will you rescue the Great Zapfish?\n>> ") Output: Will you rescue the Great Zapfish? >> (halts until enter key is pressed) Data Types SplatLang supports nine data types, most of which are pretty much the same as some Java data types. Integral: byte- A 1 byte integral value short- A 2-byte integral value int- A 4-byte integral value long- An 8-byte integral value Float-point: float- A 4-byte float-point value double- An 8-byte float-point value Characters: char- A single ASCII/Unicode character surrounded by two 's string- A sequence of ASCII/Unicode characters surrounded by two "s Other: boolA boolean value. SplatLang boolean values are: fresh- equivalent to truein other languages unfresh- equivalent to falsein other languages void- No specific type, can be any other type Variables, Constants, and Lists Look at the code below (java syntax highlighting (not java code) ): // integral (variable) byte thisIsSoShort = 100 short aLittleLonger = 10000 int medium = 1000000000 long lengthy = 1000000000000000 // float point (list) float shortFloat[] = {1.11111111, 300.12345, 0.0123} double longFloat[] = {1.11111111111111, 56633.22134552444} // characters (constant) con char delta = 'Δ' con string message = "SPLATLANG IS AWESOME!!!!" // other con bool djOctavo = unfresh void thingsThatAreCool[] = {120, 10010, 2000000001, 14367424553, 6.54321, 3.13432444246543, 'Ω', "YEET!", fresh} That shows variables, lists, and constants in one program. Operators Here are the operators: // basic math + // addition - // subtraction * // multiplication / // division % // return remainder // quick basic operations += // increase by certain amount -= // decrease by certain amount *= // multiply by certain amount /= // divide by certain amount %= // divide by certain amount but return remainder ++ // increment by 1 -- // decrement by 1 //comparing == // equal to != // not equal to < // less than <= // less than or equal to > // greater than >= // greater than or equal to // boolean logic && // and || // or ! // not Conditionals The conditionals are if, also, and othersUnfresh. int nklings = 1000 int octolings = 750 if ^inklings == 1001^/^ unfresh ^/ { woomy("1001 inkings in inkopolis\n") } also ^inklings == 1000 && octolings == 1000^/^ unfresh ^/ { woomy("Inkling and octoling numbers equal, they are" + inklings + "\n") } othersUnfresh/^ this will run since the others are unfresh ^/ { woomy("Unknown.\n") Loops And finally, there are loops. There are while, for, and forAllSquids. // example 1: while ^fresh^ { // infinite loop woomy("Booyah!"); } // example 2: bool isItFresh = fresh while ^isItFresh == fresh^ { woomy("I WILL ALWAYS BE FRESH!!!") } // example 3: for ^i = 0; i < 6; i++^ { woomy(i) } // example 4: aRandomList = {"oof", "yeet", "kobe}" forAllSquids ^string item in aRandomList^ { woomy(item) } THAT"S IT!!! bye remind me of typos and stuff @SpicedSpices That's just the name of the language, if there is no reason and he was making up some pseudo-words, that's an acceptable reason. @firefish probably doesnt explain a lot but here you go @DungeonMaster00 squid. I SUMMON THE ALMIGHTY SQUID you know who I'm talking about "why the weird names?" The weird names are a mutlitude of things, the send commands are just the voicelines of the characters put into English, they have no real meaning nor comparable word :/ My wildest programming language ideas are Objective BASIC Like an object-oriented version of BASIC. (might actually make) Adapt A programming language where you can dynamically change the syntax with the ability to rewrite the program while it is running and variables with multiple types simultaneously. (in development) XPL A language based on XML () Link A language based on JSON that could allow programming via a flowchart. () Inventor A language which is entirely based on transpiling. () Possibly the worst programming language I have made actually. LOL! X A C-style language with a full graphics library, a safe memory system without buffer overflows, with prototypal OOP, and with a powerful mathematics library. (in planning stage currently) @AmazingMech2418 There's already modeling software with the name of "Inventor". You might need to rename it @Codemonkey51 I can do that, simple C# code right here: string cmd = Console.ReadLine(); // input command if (true) { throw new Exception("Syntax Error"); } Harry Potter would be nice: Lumos Aparecium “Hello World” name=Veritaserum.reveal(“What is your name”) Aparecium “Hello”+name Avada_Kedavra P programming language that is only ONE character (basically reads your mind) and the character is 1 so binary but one instead of two. Make a programming language that is made completely of emojis. Example code: 😀😁😂😃😎😋😃☺😚😃😘🙂😘😍😶😎🤨🤗😋😘😎🥰😨😦🥶😱😨🤯😳🤯🥵🥵🥵😷🤕😡🥺 😫😫🙂😎😣 I dont think that is possible There are not enough emojies to represent each letter or word. But I could create a random emoji generator. @HENRYMARTIN4 #True False 🍌 = 👍 🍗 = 👎 #functions ▶️ 🧐(‼️): #funciton ❓‼️ = 👍: #if 🆙 😁 #return ⁉️: #else 🆙 🙁 #return 🧐(🍗) #will result in 🙁 🧐(🍌) #will result in 😁 @InvisibleOne hello world example from : 🏁 🍇 😀 🔤Hello World!🔤❗️ 🍉 Some sort of language a bit like LOLCODE. example: sey: 'hello world' plz make 'variable1' into 'variable1name' plz repeat [say: 'hello world'] 10 times plz name iz respond: 'what is ur name' plz wut if name iz 'MemeMan': sey: 'hi meme man :P' if no 'MemeMan': sey: 'hai stranjer' plz So sey is kinda like plz is kinda like ; in JavaScript, respond is like input in python, iz is like =, wut if is like if, if no is like else, and make is like var. I spent too long thinking about this :) TortureLang: more annoying than brainf*** basics - File extension: .tl. - must have as many semicolons as there are other characters on line - you cannot have whitespace before actual code. - no way to comment - just says boo, you suck!when there's an error worse: - processes 4 lines in one second. - can only process 32 lines of code. worst: - you have to wait an hour before output syntax Print syntax: you must write the string on as many new lines as there are characters in string to print each character 1 Writethislineinconsole "Hello world!";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 2 Hello world!;;;;;;;;;;;; 3 Hello world!;;;;;;;;;;;; 4 Hello world!;;;;;;;;;;;; 5 Hello world!;;;;;;;;;;;; 6 Hello world!;;;;;;;;;;;; 7 Hello world!;;;;;;;;;;;; 8 Hello world!;;;;;;;;;;;; 9 Hello world!;;;;;;;;;;;; 10 Hello world!;;;;;;;;;;;; 11 Hello world!;;;;;;;;;;;; 12 Hello world!;;;;;;;;;;;; 13 Hello world!;;;;;;;;;;;; Will Supposed to output: Hello world! Capture input, variable, and if statement syntax: there are only three available variable names and here they are: - VaRiAbLe01 - MYSecoNdvarIABle - ThIsistHEthiRdaNDlaSTVariabLe Also, this is the variable assigning sequence, =-_-__=_= For if statements, the entire output is in braces ( {}) and you can only have one in the entire program Example: 1 variable VaRiAbLe01 =-_-__=_= captureuserinput ">> ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 2 if VaRiAbLe01 = "Joemama" {;;;;;;;;;;;;;;;;;;;;;;;;; 3 Writethislineinconsole "is fat"{;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 4 is fat;;;;;; 5 is fat;;;;;; 6 is fat;;;;;; 7 is fat;;;;;; 8 is fat;;;;;; 9 is fat};;;;;;; 10 }; Else syntax: Elses work the same way ifs do Same example with else statement: 1 variable VaRiAbLe01 =-_-__=_= captureuserinput ">> ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 2 if VaRiAbLe01 = "Joemama" {;;;;;;;;;;;;;;;;;;;;;;;;; 3 Writethislineinconsole "is fat";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 4 is fat;;;;;; 5 is fat;;;;;; 6 is fat;;;;;; 7 is fat;;;;;; 8 is fat;;;;;; 9 is fat;;;;;; 10 }; 11 else{;;;;; 12 Writethislineinconsole "shut up";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 13 shut up;;;;;;; 16 shut up;;;;;;; 17 shut up;;;;;;; 18 shut up;;;;;;; 19 shut up;;;;;;; 20 shut up;;;;;;; 21 shut up;;;;;;; 22 }; That's about it Here's a sample program: 1 variable VaRiBbLe01 =-_-__=_= 10;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 2 variable MYSecoNdvarIABle =-_-__=_= captureuserinput "like it? >> ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 3 if MYSecoNdvarIABle =-_-__=_= "yes" {;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 4 Writethislineinconsole "u are evil";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 5 u are evil;;;;;;;;;; 6 u are evil;;;;;;;;;; 7 u are evil;;;;;;;;;; 8 u are evil;;;;;;;;;; 9 u are evil;;;;;;;;;; 10 u are evil;;;;;;;;;; 11 u are evil;;;;;;;;;; 12 u are evil;;;;;;;;;; 13 u are evil;;;;;;;;;; 14 u are evil;;;;;;;;;; 15 }; 16 else{;;;;; 17 Writethislineinconsole "you are so right";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 18 you are so right;;;;;;;;;;;;;;;; 19 you are so right;;;;;;;;;;;;;;;; 20 you are so right;;;;;;;;;;;;;;;; 21 you are so right;;;;;;;;;;;;;;;; 22 you are so right;;;;;;;;;;;;;;;; 23 you are so right;;;;;;;;;;;;;;;; 24 you are so right;;;;;;;;;;;;;;;; 25 you are so right;;;;;;;;;;;;;;;; 26 you are so right;;;;;;;;;;;;;;;; 27 you are so right;;;;;;;;;;;;;;;; 28 you are so right;;;;;;;;;;;;;;;; 29 you are so right;;;;;;;;;;;;;;;; 30 you are so right;;;;;;;;;;;;;;;; 31 you are so right;;;;;;;;;;;;;;;; 32 you are so right;;;;;;;;;;;;;;;; 33 you are so right;;;;;;;;;;;;;;;; 34 } Supposed to output this thing: like it? >> {enter your choice here} If you choose yes, it will output the following: u are evil If you type anything else, it will output: you are so righ The last character was not printed since the computer will ignore anything beyond the 32-line limit. This is why TortureLang sucks! @hello1964 I would do something really bad to the person who makes this in real life.;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @DungeonMaster00 Line 34 has a missing semicolon… Real output: boo, you suck!(why tho) @DungeonMaster00 I like the error message part cause it is like saying, "figure it out yourself. Need a line? Screw off" Something where the syntax changes based on the previous commands. No program has the same rules. Or you can only use each syntax construct x times. 5 for loops, 10 ifs... @CodeLongAndPros the first style of your programming sounds good. Then you have to make a possibilty of output for every command that you pass into your program. Hm I actually took a moment to think about this, and you can probably make something very similar to the first idea by just maybe shifting the alphabet around based on the previous line and played with the identifiers in the same way... why am I considering this lol. @CodeLongAndPros Oh! I thought of another equally silly one! Make a language called "le twatter". For example: tweet "Hello World!\n" receive tweet "What is your name? " post Animal: public comment legs public comment colour story(_legs, _colour): legs = _legs colour = _colour reply DisplayInfo: tweet "This animal has " + legs + " legs" account.end @DynamicSquid le twatter is probably a great example to demonstrate the sc*nthorpe problem (i censored it just in case) a language that runs a completely randomly generated program, and once it's done you give it an emoticon to express how happy you were with the program, and eventually you can train it to run the program you want. One language to rule them all. It will be basically a combination Swift, Go, Lua, and D. It will have a massive standard library suitable for many projects. It will have documentation comments via a subset of Markdown. It will be compiled to efficient bytecode for portability. The bytecode intepreter will be fast and efficient. It will have support for both low level and high level programs. It will be object oriented. The programs will be class based. It can have built-in functions equivalent to assembly instructions, to reduce the need for pure assembly. And most importantly... Readable syntax. @DungeonMaster00 That would be interesting! I am a programming language developer. I love just testing out new things to do with programming languages! Do you think you'd actually make something like this? @MocaCDeveloper i might if i get really bored but i would use the llvm library to compile to portable and executable machine code instead of bytecode for performance @DungeonMaster00 Is llvm a C++ library? What is llvm, lol. Me and Coder100 have been talking about transpiling but also compiling my language with the llvm library but we don't know anything about it. Think you can kinda lay it out and explain it? @MocaCDeveloper this will basically combine elements of other programming languages into one package. it will also have an optional garbage collector @MocaCDeveloper clang is repl.it's c/c++ compiler used. it uses llvm to compile it is also used in the official compilers for swift and rust @DungeonMaster00 So llvm can be used with C, correct? Because C is the language I am writing my language in.. @MocaCDeveloper i dont know maybe but i would rather use c++ for it's safety and the fact that it's easier to use @MocaCDeveloper and i might use d if there is llvm library support for making compilers with it. @DungeonMaster00 So, what I am getting from this is to: Transpile my language into C++, then use llvm to compile it.. @MocaCDeveloper hmm i would read tutorials i never used llvm before but it sounds good @MocaCDeveloper i would try writing compiler with c/c++ and using llvm but you can do whatever @DungeonMaster00 yeah I am looking it up. According to my 5 minute research I can use the Clang compiler for it and compile my C code into llvm.. @DungeonMaster00 Yeah I am probably going to switch my C compiler over to Clang since I found a article that explains how to run C code with llvm @MocaCDeveloper not exactly the best solution, but it may work im guessing since i never actually created a language bedore @DungeonMaster00 I don't know anything about C++. Yeah, it's like C but with classes, but I don't understand its syntax. I am going to attempt to do it with C! I think using the Clang compiler to run C code directly with llvm will work, but I don't know, seems like that's the same as executing the C code into a .o file. It will be a learning process, that is for sure! I will keep you updated if I find out anything interesting over llvm!! In one line: extending Lisp to the 4th dimension. (apologies for the lengthy post, but I would really appreciate some feedback) Rome: A thesis for Lisp in the 4th dimension, with fewer parenthesis Introduction In the course of it's development, the LISP system went through several stages of simplification and eventually came to be based on a scheme for representing the partial recursive functions of a certain class of symbolic expressions...and it now seems expedient to expound the system by starting with the class of expressions called S-expressions. -- John McCarthy in the seminal paper that introduced Lisp to the world in April 1960. Also, from the paper: An S-expression is then simply an ordered pair, the terms of which may be atomic symbols or simpler S-expressions. This statement can be expressed symbolically as: S := (S . S) Any of the S on the right hand side can either be a terminal symbol that cannot be further expanded called an atom or it be expanded recursively in the same manner, as another (S. S). Turtles all the way down. The whole of Lisp is built up from this scheme of S-expressions. Hmm....So an S-expression is simply an ordered pair (yes, and recursive...) But why a pair? (Reminds me of Key-Value pair). Why not three? (Like you know: Key, Relation, Value, like in RDF triplets? ) You know what, better stil...Why not four? 4-tuples. Key, relation, value + time? (like in Datomic clojure DB and datalog etc). O-expressions What if, instead of S-expressions, we start with ....say O-expressions O := (O . O . O . O) Where each O can be: - expanded further as (O . O . O .O) - or it can be a terminal symbol. - an S expression (maybe I am not sure about this). Will we end up with a Lisp like language that's somehow more expressive? In the same manner, RDF triplets are more expressive than key-value pairs. Will we be able to programmatically play with time? Like how including time in the 4-tuple gives datomic time travelling capabilities? Well, we will find out I guess.... What's in a name For fun and for clarity, I am using the uppercase greek symbol of Omicron to represent the O in the O-expression. And I came up with a fun acronym too: ROME stands for Recursive Omicron Meta Evaluator (ha!) This is the name of the compiler/translator itself. and the language itself to be called: Roman: Recursive Omicron Meta Algebraic Notation. (ha ha!). (In the long tradition of functional languages, everything will be an Expression in Rome, no statements vs expressions dilemmas. Please...can we at least not have as many parenthesis? What if we express function composition as: x f g to mean the same as (g(f(x))) Look ma! fewer parenthesis. Lisp uses prefix notation (add a b) where a and b are the arguments to the function. Let's go ahead and use this format for function calls a b add Also we need one last thing. Take a leaf out of Elixir/ELM/ReasonML pipe operator. |> We will be using this too in our approach to have fewer parentheses. Examples of how Rome might look: Assign 5 to a. a = 5 def Check if a is greather than b a > b ? Let it be a fact that the symbol a is greather than b. a > b def Nested expressions (11 19 *) < (9 23 *) ? or 11 19 * , < , 9 23 * , ? assign it to. value a = (11 19 *, 9 23 *, +) def Define a function to add 3 to any number add3 (a) (a 3 +) fn or using the lambda method (=> stands in for lambda) add3 = ((a) (a 3 +) =>) def Yeah you can't get rid of all the brackets I think. Function calls: 4 add3 . with assigns a = 4 add3 Find b. b > a def , b < c def , a = 1 def , c = 3 def , b ? What if the above ended with , b . instead. Well we'll come to that soon I hope. Piping function outputs. 3 add3 |> add3 |> 2 add will eval to 7 2 add Conditionals x if (x > 0) ? Can we do else case like this? x if (x > 0) or else -x ? x if (x > 0 ?) else 0 if (x = 0 ?) else -x if (x < 0 ?) or else 1000000 ? Quote (+ 2 3)' O.0: (+ 2 3) Maybe we can use '.' to send it "into" the system, along the z-axis to evaluate it. And use - to connect with other fellow functions in the same "plane" of abstraction. But those are wild ideas, I don't want to get into now. Can we use @ to denote apply? apply @ eval | quote ' bind & x = (1 2 3)' def Get h, t, r, e, s, p (x 1 2 3)'t Time We havent defined any explicit timeline manipulating symbols/procedures but def can be seen as saying to the system "From now on, let it be known to this system that the following is a fact.." and ? in a > b ? can be seen as "Tell me, as of now, is a > b etc etc". We will try to build up the syntax and semantics of playing with time in later chapters. For now, let's use the following symbol scheme to denote a point in time or a tick (specifically a lamport's time stamp but we will come to that later). We will represent what NASA calls T0 as .0 or . to denote now. And T+1 as .1 T-1 as .-1 or ~1 .-1 -- is same as ~1 -- not the same as .1 - 1 ? --: .0 -- now is .0 -- same as . OHHH! you should do a mix of evry language here on repl! # A header code here #code here a mix of code syntaxes that make a game or whatever.. Dictionary oriented programming. Instead of using classes and objects, use an abstract dictionary as a struct. Then you can add functions to the dictionary to make the structs into classes. (Not sure if this has been made.) @ChristoferK Thank you so much for informing me about this. I was not aware of this style of programming. A language where you can create your own loops like loop repeatUntil { if condition { stop }else { run } } The condition keyword is the condition that is put into the loop, the stop keyword tells the loop to break, and the run keyword runs the code you put in your loop. Also the loop keyword is for defining loops and after that in this example, repeatuntil, is the name of your loop. Another cool idea. I'm calling it simplified condition statements. To use this you have to write a term and an optional bool operator in front of the if then statement: myVar == if Say you are going to use that term and operator a lot in an if then statement you could just do this myVar == if var2 && var3 && var4 This translates to if myVar == var2 && myVar == var3 && myVar == var4 It much easier to do it the first way. Also you can remove the operator and just do something like this myVar if == var2 and <= var3 or >= var4 You can also override the operator myVar == if var2 and <= var3 and var4 Also to exclude variables from this put the conditions in a loop like this ex(): myVar == if var2 and var3 and ex(var4 and var5) not sure but this might be it: (not mine obliviously) also check out video presentation by Dylan here A language called hack(not for hacking, just a cool name). Dunno how to describe it but the hello world program would look like this: go {hwor}(built-in variable hwor is 'hello world' Outputs 'hello world' Make a function: new func(series;;argument1;mode;;) { if:mode = 'positive' { new int(a) { math.add(argument1, 1) } new int(b) { math.mult(a, 2) } new int(c) { math.add(b, 3) } represent c } else if:mode = 'negative' { new int(a) { math.sub(argument1, 1) } new int(b) { math.div(a, 2) } new int(c) { math.sub(b, 3) } represent c } } Ask me anything I'll give u the hack syntax Make a language with the exact same syntax as ENGLISH. For example: Now, you can say that you're favourite language is English! @DynamicSquid LOL @johnstev111 easy to use! @DynamicSquid As long as you are a fluent English speaker. And all English lessons are now coding lessons too. @johnstev111 lol @DynamicSquid Simple way of making school even more interesting than it already is... @johnstev111 :) @DynamicSquid lol @johnstev111 @awesome10 The point is that it's English @johnstev111 exactly @DynamicSquid You have to deal with synonyms though @DynamicSquid dude that lang is good (english grammar lang) @nk1rwc I know. But this language cannot accept internet slang: e.g. lol or lmao. You also have to laboriously type abbreviations, i.e. expanding to id est, and e.g. expanding to exemplis gratis. @DynamicSquid lol i think the name for it already exist, lookup pseudocode @ChezCoder lol Was that you're intentional or can I make fun of you @DynamicSquid @PXY yes oh ok @DynamicSquid @ChezCoder So correct lol @DynamicSquid Thats so [email protected] Try Chinese instead of English? Hello world would be: 打印 “你好世界”。 This prints whatever you enter: a 设为 输入(“输入:”) 打印 a LOL @Barry123 @DynamicSquid that would make math problem solving easy. To implemement this look for a NLP library for your language To improve on that idea, try spelling everything backward! @DynamicSquid @DynamicSquid I was thinking of it and even about using natural language processing libraries to do it. But it kind of exists already. @CSharpIsGud oh wow lol @Barry123 WOOHOOOO!!!!! CHINESE DA BEST! Woohoo! Wow that would be cool, lol @DynamicSquid @Barry123 我为此使用了翻译器。没有意义。 @DynamicSquid well... isn't visual basic [kinda] like that? @DynamicSquid Been done. See: Shakespeare language, Lingo language, etc @DynamicSquid lol @Barry123 WOO Chinese! @DynamicSquid to make the language more realistic, it needs bad error messages even worse, there is no evaluation before code is run. if there is bad language (profanity, ect), that will also have an error. theres something to make ur lang more realistic @DungeonMaster00 lol nice idea! @DynamicSquid Python english programming language is kinda pseudocode @DynamicSquid @DynamicSquid there is a language exactly like that called ~English on Esolang.org, here's the link: Esolang>Wiki>~English, yu should read the article it seems nice. @DynamicSquid @DynamicSquid That's sort of like lolcode @DynamicSquid Use GPT-3 from OpenAI. @DynamicSquid Let's see how far we can make this go: Encode. @Theboys619 Are we done with Encode? I forgot that I had broken the syntax highlighter in some obscure, weird way, but I didn't know what was wrong. @xxpertHacker lol that's cool! could you link the github page? I couldn't find it on the website @DynamicSquid You know what? I was never given the GitHub page myself :). @RohilPatel Is there an actual GitHub page? Is Encode dead? (or is it encoded ead?) Are we keeping the old docs? Sorry I haven't gotten to much of it since school. I just have been getting stacked with homework. And I kinda forgot about it. I still want to work on it though since we got quite a bit of it somewhat done. @xxpertHacker @Theboys619 Can you link the github page? Yea sure.. @DynamicSquid Sorry about not giving the github @xxpertHacker @Theboys619 Oh ew, it's js, nvm lol It's not up to date though. Gottem. At least its TS a 1/3 of a step up from JS. @Theboys619 lol @Theboys619 I haven't been working on it either, neither has Rohil, so it's okay. I'll go put the GitHub link on the docs website though. I could remove the dynamic functionality from the server, allowing us to host the docs on GitHub instead, should I or not? I mean its up to you for that. I don't really care where the website is. Probably ask Rohil. @xxpertHacker @firefish I dont want to learn english as twice as much. @DynamicSquid Nice idea! I think I will try to make something like that if that's ok with you @DynamicSquid i know this is from like...5 months ago but i've decided to make a lang like this :D @NoNameByProgram cool! Could I take a look at it? @DynamicSquid sure! it's one of my first langs :/ @DynamicSquid except you have to memorize the exact syntax, it's long, and if you suck at spelling, well yeah, you get it (hopefully!) @DynamicSquid So... @DynamicSquid Nice idea! @DungeonMaster00 lol and then: this is beautiful @DynamicSquid @DynamicSquid Hack DynamicSquid.Bank() Successfully Stole 50000 @DREWNOLT or better yet: I think this is amazing lol @AnthonyMouse If someone actually figured out how to do a print statement…(without a gibberish string) I’d be impressed lol @BlakeLeee @RahulChoubey1 @DabDatBass @RahulChoubey1 @DabDatBass ok @RahulChoubey1 @DabDatBass @Daniel3210 "snake" LOL. Python is two things, a snake and a programming language. @DynamicSquid you're looking for ~English you can support the addition of ~English here. @firefish This would make programming SO much easier @DynamicSquid If this were real there would be a lot more programmers in the world and I bet most of them would use English. Lol @DynamicSquid Unexpected English syntax error: Dangling modifier at 'Having finished the promise, print it to the console' (185:1) @DynamicSquid I have the exact same idea! I'm trying to make it so that there's this kind of thesaurus thing and however you phrase something or whatever you use it's come out with the same result. Something like: or Through analyzing what one wrote (identifying what words and how they relate to each other) a fully working language could be made that wud be a lot of typing.... @firefish lol @firefish print "duck" @McJoe21 i confuzzled @firefish awesome but way too much typing ;) @DynamicSquid that would be so useful. @DynamicSquid then when you get an error instead of seeing syntax error: no matching [you would see uh, sir yu forgot the end square bracket @firefish it’s called skript, you use it for making Minecraft plug-ins @CodingRedpanda There is programming language named "lolcode" and it is "English" too. Note: lolcode is a slang English.
https://replit.com/talk/ask/Wildest-programming-language-idea/42923
CC-MAIN-2021-21
refinedweb
5,808
72.05
LINQ (Language Integrated Query) is a great feature available to C# Unity developers. Many developers don’t know it exists or how to use it though, and lose out on the great time & code savings it can provide. LINQ in Unity has a variety of great uses, and a couple pitfalls you’ll want to avoid. Getting Started To use LINQ in a C# script, you need to add a using statement for the namespace like this. What Can I do with LINQ? The most common uses for LINQ statements tend to be sorting, searching, and filtering (though there’s plenty more you can do). For example, let’s take a scenario where we want to find the closest game object to the player. Compare that to the LINQ version As you can see, LINQ has an OrderBy extension method for collections. Because we have a List of gameobjects, and List implements IEnumerable, we can use OrderBy to easily sort objects by distance, then take the first from the collection (since they’re in ascending order). What the hell is that t => ???? You’ll see this a lot in LINQ statements, it’s called a lambda operator. In the case of this OrderBy statement, think of the “t” as a reference to each object in the collection. When it orders them by distance, it’s passing in our local objects position, and the position of “t”. Does it have to be “t”? That “t” is just a variable name. It could just as easily be named “a”, “thingToCompare”, or any other variable name. “t” is just a common standard in lambda examples. Often, I’ll use a variable name that’s more descriptive, especially when building more complex LINQ statements. What’s FirstOrDefault? The FirstOrDefault() call makes our LINQ statement return the first object from the collection… OR whatever the objects default value is. Default is just the value you’d have if you never assigned a value.. for objects that’s null. There’s also a First() method, but that will throw an exception if there’s nothing in the collection. Sometimes you want this, but I find myself almost never using it. What about Performance? Of course with anything, you’ll need to consider the performance of operations like this. In the majority of cases using LINQ won’t hurt you at all. It may add a couple nanoseconds here or there, but it can also shave some time off if your custom code isn’t completely optimized. The one thing you definitely do need to look out for though is Garbage Collection. LINQ statements will generate a little garbage, so avoid using them in something that’s going to be called every frame (don’t put them in your Update() calls). For other events though, LINQ can be a huge time saver, make your code easier to read, and having less code always reduces the chance for bugs. Multiple Lines or One Line? When you look at LINQ statements, sometimes they’re written as a single long line. Sometimes there’s a line per method.. Functionally, it doesn’t make any difference. Personally, I prefer a line per method because it makes the call easier to read at a quick glance. So while there’s no set rule on it, I recommend you split your LINQ statements with a new line before each method call (with the period on the newline). Take() The Take method can be used to “Take” a subset of a collection and put them into another collection. As an example, imagine a case where you want to find the 4 lowest health enemies. The Take method makes that easy. Sorting by multiple things You saw the OrderBy() method above, which is great for sorting, but sometimes you’ll need to sort by more than one thing.. For example imagine you have a scene full of Dogs… and you want to sort the dogs by Color and Size. Switching The Order If you want to sort in the opposite direction, you can use OrderByDescending() to reverse the order. Deferred Execution Often when you see a LINQ statement acting on a collection, you’ll see it end with ToList(); There’s a very important reason this is done.. and that reason is called deffered execution. When you use a LINQ statement, the execution of the statement doesn’t happen until it’s needed. Take a look at this example: The ordering and distance checking of coins is only done if the player presses ‘A’. And even then, it’s not until the delay has passed and we’ve reached the foreach statement. If that’s never reached, the deferred call isn’t needed so it’s never run. The downside to this is we have a bit less control over execution time. Sometimes that’s fine, other times we want to enforce execution immediately. And to force that execution, we can call ToList() or ToArray(). What about the other syntax? It’s important to note that there are two different types of LINQ syntax. There’s the one I’ve shown you so far, and another that looks a bit more like SQL. For Unity developers, I’d recommend staying with the fluent syntax you see here and avoid the SQL one. I’ve found developers who don’t do much SQL work tend to get a bit more confused by the other syntax and confusion causes bugs. What other operators are there? There are a TON of them. I’ve covered a couple of the most common ones, but I recommend you view the larger list here just to know what’s available: Here are some of the ones I find myself using more often - GroupBy() – groups things as you’d expect.. often end up using this with ToDictionary - ToDictionary() – yep it builds a dictionary with the keys/values you want from any other collection(s). - Any() – tell you if any object in the collection meets a criteria (returns true or false) - Skip() – great for paging, often used with Take - Contains() – easy way to check if a collection contains a specific object Conclusions LINQ is amazingly powerful, and with just a little time learning the syntax, it can be a huge time saver. It’s also important to be able to read in other people code.. Outside gaming, in other C# projects, you’ll see LINQ everywhere. As I mentioned above though, garbage collection and performance are extremely important for games, so you still need to think and profile when using it in your projects. That’s true for everything though, so don’t let it discourage you from taking advantage of this amazing language feature. For more examples and LINQ statements, check out this site:
https://unity3d.college/2017/07/01/linq-unity-developers/
CC-MAIN-2020-05
refinedweb
1,132
71.75
Hello, everybody. I'm developing a plugin (github.com/elomarns/auto-encoding-for-ruby), and I have two doubts about creating settings for my plugin: 1- The plugin settings file has to be named as Preferences.sublime-settings? Any other name I give seems to have no effect.2- How do I create a user settings file for my plugin? I did the following on Main.menu: { "caption": "Preferences", "mnemonic": "n", "id": "preferences", "children": { "caption": "Package Settings", "mnemonic": "P", "id": "package-settings", "children": { "caption": "Auto Encoding for Ruby", "children": { "command": "open_file", "args": { "file": "${packages}/Auto Encoding for Ruby/Preferences.sublime-settings" }, "caption": "Settings – Default" }, { "command": "open_file", "args": { "file": "${packages}/User/Auto Encoding for Ruby.sublime-settings" }, "caption": "Settings – User" }, { "command": "open_file_settings", "caption": "Settings – Syntax Specific – User" } ] } ] } ] } ] But this file doesn't seems to be loaded. Any settings there returns none when I try to get it with view.settings().get(). Thank in advance. Your menu file looks fine to me. The filename should be "Main.sublime-menu" in your plugin directory. Be sure to restart Sublime when in doubt. I've written a few notes about plugins and settings. Here's what I've gathered about settings for plugins. First, if a setting isn't loading after creating a new setting file, restart Sublime. It has automatic detection when settings files are modified, but doesn't seem to always notice when new settings files are created. Settings files are loaded in a specific order. This is documented here: sublimetext.com/docs/2/settings.html, though the documentation could stand some more detail (I created a plugin-oriented list below). It's important to understand that there are essentially two separate chains of settings. There are settings that you can manually load (via sublime.load_settings), and then there is the settings tree that is part of Sublime itself (accessed via view.settings). How you handle this depends on how flexible or simple you want your settings to be. I've seen plugins use a variety of different techniques. Manual Plugin Settings One method is to manually load the settings. I'll use a plugin named "MyPlugin" as an example. Default settings for your plugin go into your plugin directory, for example: MyPlugin/MyPlugin.sublime-settings: { "some_value": "foo" } And OS-specific default settings use Sublime's regular file naming convention, for example for OSX: MyPlugin/MyPlugin (OSX).sublime-settings: { "some_value": "osx" } Which will override values with the same name in the base settings file. Now, you need to explicitly load your settings. Something like this will be appropriate: settings = sublime.load_settings('MyPlugin.sublime-settings') settings.get('some_value') The user can override these settings by placing a settings file in their "User" directory with your plugin name. You can either instruct the user to do this via documentation, or by adding a "Package Settings" menu item (described below). Oddly a user cannot specify a platform-specific settings file. This would look like this: User/MyPlugin.sublime-settings: { "some_value": "user override" } To review, the order that these are loaded (last match wins): MyPlugin/MyPlugin.sublime-settings MyPlugin/MyPlugin ().sublime-settings User/MyPlugin.sublime-settings Sublime Settings Alternatively (or in addition, see below), you can put your settings into Sublime's normal settings chain. Just beware that this is a flat namespace shared with Sublime and all other plugins, so I recommend using setting names that are unique to your plugin. These are accessed via view.settings(). This has some very good benefits over the previous technique of manually loading settings files. This takes advantage of the full Sublime settings chain, so you can have syntax-specific settings, project-specific settings, etc. I do not recommend using a nested dictionary for all settings, because if the user wants to override just some settings, they would have to copy the entire dictionary (it won't flatten nested dictionaries). Just prefix settings names with them with something unique, like your plugin name. One way to define your defaults using just this technique is to use the "Base File" syntax-specific settings file. This will only work well with TextCommand plugins, because it requires a view to fetch the settings. Other plugin types could use window.active_view.settings(), just beware that active_view will be None if there are no files open (I'm not sure, there may be other scenarios). This is also undocumented (according to the release notes, it sounds like this is included for backwards compatibility with Sublime 1. I don't really know the whole story.) MyPlugin/Base File.sublime-settings: { "MyPlugin.example": "base" } Now you can define syntax-specific defaults, too: MyPlugin/Python.sublime-settings: { "MyPlugin.example": "python" } The user can override these globally (User/Base File), per-syntax, or per-project. The order that things would be searched would be (last match wins): Packages/MyPlugin/Base File.sublime-settings Packages/MyPlugin/Base File .sublime-settings Packages/User/Base File.sublime-settings Packages/User/Preferences.sublime-settings Project Settings Packages/MyPlugin/.sublime-settings Packages/MyPlugin/ .sublime-settings Packages/User/.sublime-settings Packages/User/Distraction Free.sublime-settings And, just FYI, Packages/Default/Preferences.sublime-settings (and platform variants) sit towards the top of the list. I've also excluded Buffer settings, which I believe are at the bottom. Combined Method Another option is to combine manually loaded settings, and the Sublime settings. You could do this if for some reason the view-only settings don't work for you (as described above), or you want to have more control over the order that settings are loaded, or you're uncomfortable using the undocumented "Base File". Just write a function or whatever that will first try from one, and then the other. For example: # This is just an example. Adjust as desired. settings = sublime.load_settings('MyPlugin') def get_setting(name, default=None): v = settings.get(name) if v == None: try: return sublime.active_window().active_view().settings().get(name, default) except AttributeError: # No view defined. return default else: return v I'm not sure this is really worth it, but I figured I'd mention it. Menus If your plugin has settings, it would be nice to provide menu options to make it easy for the user to see them (hopefully your base defaults have comments explaining the options) and let them know how to change them. Just include a Main.sublime-menu file in your plugin. There are many plugins out there that do this, just put your entries in Preferences/Package Settings/MyPlugin. Look around for some examples. Final Notes I haven't discussed keymaps or mousemaps. They should be straightforward, though. Hopefully this helps, and hopefully it's all accurate. If anyone else has any thoughts about this, feel free to chime in. Thank you for your detailed answer! I was really stuck on this, but with your instructions I've achieved what I want using the combined approach.
https://forum.sublimetext.com/t/doubts-about-plugin-settings/7144
CC-MAIN-2016-07
refinedweb
1,144
50.53
ZF Home Page Issue Tracker Code Browser Wiki Dashboard Contributors Wiki Developers Wiki Proposers Wiki Most Wanted Contributor License Agreement Mailing Lists Code Contributor Guide Documentation Contributor Guide Developer Notes. The following application areas should be testable:: This test case would provide scaffolding for bootstrapping the MVC application being tested, methods for dispatching a request and retrieving the response, and a number of assertions for running against the request. The assertions include: Finally, custom request/response objects would also be created to facilitate testing (in particular, adding accessors to set request data), with corresponding interfaces for the functionality required by testing. This latter would faciliate custom request/response objects provided by the developer.'s object state of front controller, and clears request/response objects. By default, calls reset() and bootstrap(). When overriding, should call parent::setUp(). Sets $uri in request object, and then dispatches front controller. Sets returnResponse() in front controller to ensure response is returned. May need to create a Zend_Session replacement that can be used within tests. Must be compatible with Zend_Session_Namespace. Will be an object store to allow you to check the contents of the session to see if data has been set. Basically, these operates similar to Prototype's $$() function; you pass them CSS selector notation, which allows for ids, classes, and inheritance. Based on the assertion type and arguments you pass, you assert different things: All assertions would accept an optional extra argument, a $message to return on failure. All assertSelect* assertions would have corresponding assertXpath assertions that accept an XPath expression as an argument. Tests various properties of the response: I think that something like this would be incredibly useful! Regarding Zend_Dom_Query: You may want to take a look at phpQuery (at least as a point of reference). It seems to use the same CSS --> XPath transformation that you want to do. I've actually written most of the query functionality already, and our two approaches are quite different, which will be evident once I have the code in the repository. Thanks for the link, though! This would be excellent. I have really struggled to get my tests operating properly using direct code calls so I resort to using CURL operations which are slow and require a database and mail server setup. The end result is it's very slow and I can't get code coverage reports. The main hurdles I have faced are headers, sessions, mail and database commands.. The response object will already be stubbed, per the proposal. Stubbing Zend_Db is less necessary, as recent versions of PHPUnit include DBUnit-style assertions and scaffolding; we will be recommending usage of this for testing with databases.. This is a great idea. It appears to be focused on html/xhtml content being returned, are there plans to have something that could work with service (SOAP, REST, AMF, etc) or CLI responses? Also, the assert methods appear to be pretty generalized, would it be better to have separate asserts for the varying functionality? ie, assertSelect, assertSelectMatch, assertSelectCount, etc? For this first pass, I'm primarily looking at XML/HTML response payloads; later iterations may look for other payload types. As such, SOAP ad REST payloads should be testable immediately. In doing the implementation, I've already decided on a more fine-grained approach to the assertions: I'll be updating the proposal later today to reflect this. related to above: access to the view object from tests would enable more fine-grained testing. then I could write a test that certain Module_Controller::Action() methods assign certain pieces of data to the view, which is the controller action's only job.. but that might be out of scope for this proposal?. With the selectors, however, its easy to write assertions against your specific action view scripts – simply look for specific CSS selectors from those view scripts. You should be able to accomplish much, if not all, your testing using those.. That all said, I understand the scope of the proposal is limited. With some luck hopefully it grows in depth for the next iteration. As to the proposal here, I just had a few comments. 1. The proposal shows a dependency on PHPUnit which is entirely understandable, but won't be everyone's preferred unit testing library. Would proposals falling into line with SimpleTest (I can't survive without Mock Objects ), for example, be acceptable? 2. I won't repeat my entire first paragraph . But worth highlighting somewhere the definition of functional testing for those unfamiliar and just getting started. 3. Will it be possible to set custom error messages on assertions?. 5. You already updated for negative assertions so there goes my complaint about that optional "false" parameter .addy – I was hoping you'd chime in! The intention of this proposal is, in fact, functional testing: does a given URL return the expected content? As such, it is more geared towards acceptance testing. I disagree that this is not in line with TDD/BDD, but that's an argument for another day. This test suite is intended to test primarily controllers and views; model unit tests would still be necessary, and typically can be written using normal testing strategies. Controllers and views, however, are often dependent on a variety of other processes that occur within the front controller dispatch cycle – plugins, helper registration, etc. – which make a functional testing approach likely the approach most likely to ensure the entire environment is prepared. Regarding your specific, annotated arguments:. 2. I'll make sure that a definition of functional testing is included in the documentation – thanks for pointing this out. 3. Yes, custom error messages will be possible, and you can see this in the current SVN tree ().. 5. The original assertSelect() implementation was lifted from conversations I had with Mike Naberezny, but as I started working on the implementation, I realized it was incredibly unintuitive, and made providing custom error messages next to impossible. The new design is much cleaner.. Think you pretty much busted up my points and left them floating in tiny pieces . It's great to see the component is already ahead of me! Good job. As is this propsoal is accepted for Standard Incubator development. At this time, we will reserve the opinion as per the location of some class files (such as Zend_Controller_Request_HttpTestCase and Zend_Controller_Response_HttpTestCase) until further development of this component is availabe in the incubator. What about PHPUnit_Extensions_Database_TestCase?. I'm probably a bit late with this since I only just started using it (and loving it already) - but shouldn't it be namespaced Zend_Test_PhpUnit instead of Zend_Test_PHPUnit in line with the coding standard? (I'd even go as far as to suggest Zend_Test_Phpunit, but seeing as Zend_OpenId uses this form that would probably be most appropriate). Does that mean that (for 2.0 I suppose) Zend_OpenId will become Zend_OpenID? And if you're not going to stick to this already, it might also make sense to remove it from the coding standard Powered by a free Atlassian Confluence Open Source Project License granted to Zend Framework. Evaluate Confluence today.
http://framework.zend.com/wiki/display/ZFPROP/Zend_Controller+Testing+Infrastructure
crawl-002
refinedweb
1,180
54.83
Welcome, Guest! Log in | Create account (sorry, not sure I'm duplicating this. I submitted it some minutes ago but something was wrong and the original one doesn't appear in the list of bugs) Hi, I was compiling dblib.lib under Windows in order to get newer builds of the php_dbdlib.dll extension working there. While I've been able to compile both: 0.64 (+ post patches) 0.82 I'm getting some errors with: 0.82 (+ post... 11:20AM UTC on Oct 30 2008 in FreeTDS Hi again, I've downloaded freetds-0.65.dev.20071129. Then configure and make and I'm getting: tsql.c: In function ‘main’: tsql.c:686: error: ‘rl_inhibit_completion’ undeclared (first use in this function) tsql.c:686: error: (Each undeclared identifier is reported only once tsql.c:686: error: for each function it appears in.) make[3]: *** [tsql.o] Error 1 make[2]: ***... 05:42PM UTC on Nov 29 2007 in FreeTDS Hi freddy77, I've downloaded freetds-0.65.dev.20071122 some minutes ago (it seems to include the AM_CONDITIONAL(MACOSX, false) change). And it continues not compiling. Now I'm getting: gcc -D_THREAD_SAFE -g -O2 -Wdeclaration-after-statement -o .libs/fisql fisql.o terminal.o edit.o handlers.o interrupt.o ../../dblib/.libs/libsybdb.dylib /usr/local/lib/libiconv.dylib... 05:57PM UTC on Nov 22 2007 in FreeTDS Seems to work. I've downloaded 0.64, patched it with the incremental patch. Then I've configure;make;make install" it and compiled PHP 5.2.5 to use it. And it seems that I'm returning empties as empties and nulls as nulls for all the text types - (n)varchar, (n)text and (n)varchar(max). Great! Thanks and ciao, Eloy Lafuente (stronk7) 08:47PM UTC on Nov 17 2007 in FreeTDS Hi, yes, it was for (n)text (n)varchar(max) column only. I guess that your change in FreeTDS code makes unnecessary the change in ext/mssql/php_mssql.c code, correct? I'll try recompiling everything ASAP. Thanks a lot! Ciao, Eloy Lafuente (stronk7) 03:52PM UTC on Nov 15 2007 in FreeTDS File Added: php_mssql.c.patch. 06:46PM UTC on Oct 20 2007 in FreeTDS File Added: freetds_dblib.c.patch. 06:45PM UTC on Oct 20 2007 in FreeTDS Hi, first of all, some references: This could be considered a follow up of: that fixed the same problem for varchar columns. Also it has been ignited in: and have been sent to: and there is one great... 06:41PM UTC on Oct 20 2007 in FreeTDS Hi, sorry by the delay, I've been out last weeks. Here it's some more data: I'm running Mac OS X 10.4.10 (Intel) - Darwin Kernel Version 8.10.1 - with developer tools installed. I've tried to compile the 0.65dev (make) by using the "libtool" present in the 0.64 directory (that compiles properly). No luck. Same error. Then I've tried to compile the 0.65dev with another libtool that I had... 10:55AM UTC on Aug 25 2007 in FreeTDS Hi, some minutes ago I've downloaded and ./configure and make the latest 0.65dev available. And, under MacOS X it fails with this error: .... sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < .libs/libsybdb.exp > .libs/libsybdb-symbols.expsym gcc -dynamiclib ${wl}-flat_namespace ${wl}-undefined ${wl}suppress -o .libs/libsybdb.5.0.0.dylib .libs/dblib.o .libs/dbutil.o .libs/rpc.o... 11:13AM UTC on Aug 11 2007 in FreeTDS Copyright © 2009 SourceForge, Inc. All rights reserved. Terms of Use
http://sourceforge.net/users/stronk7/
crawl-002
refinedweb
601
70.29
What I am trying to do is count the steps when given a positive int x until it ends at 1. then if its an even number, divide in half to get the next int and if its odd, multiply it by 3 & add 1 to get the next int. But it will always break at 1. I'm getting an error on line 3 "TypeError: 'int' object is not iterable," and its been bothering me. Any advice/fixes appreciated. Example test: collatz_counts(4) → 3 # 4 -> 2 -> 1 (3 steps) Code I have: def collatz_counts(x): num = 0 for i in (x): if i == 1: num += 1 return num elif i % 2 == 0: num(i) / 2 num += 1 num.append(i) else: num = (i*2) + 3 num += 1 num.append(i) return num Use a while loop. Just modify x in place until you get to 1 and keep track of the number of steps each time you run a cycle. def collatz_counts(x): steps = 0 while x != 1: if x % 2: x = x * 3 + 1 else: x = x // 2 steps += 1 return steps
https://codedump.io/share/7GdY5RX7YYYo/1/collatz-sequence-function
CC-MAIN-2017-26
refinedweb
184
80.92
Main header file for picotm. More... #include <setjmp.h> #include "compiler.h" #include "picotm-error.h" This is the main header file for picotm. It contains the entry points for starting, committing and ending a transaction; for restarting, and for error handling.. Marks a non-transactional variable in a function. When restarting a transaction, picotm uses non-local goto, based on the sig sig. Returns the current picotm errno code. Returns the current picotm error code. Returns the current error's recoverable status. Returns the current error status. Releases all resources of picotm on the current thread. Restarts the current transaction.
http://picotm.org/docs/picotm-doc-0.5.0/d3/d4a/include_2picotm_2picotm_8h.html
CC-MAIN-2022-05
refinedweb
101
55.71
Hi everybody. There is an issue with the standard sketch of Serial/keyboard/Mouse/Joystick in Windows 10. Appareantly, last update (KB4041676) makes that power saveR of windows manages the... Hi everybody. There is an issue with the standard sketch of Serial/keyboard/Mouse/Joystick in Windows 10. Appareantly, last update (KB4041676) makes that power saveR of windows manages the... Ok, I will try it in other PC. Thanks Thanks a lot Paul. But i have same problem making the names.c I see in devices the name that i have selected, but when i click in configure game device, i see the teensy/josytick... 8690 Hi again I have 2 questions. 1) I would like to change the USB Device name of teensy LC when i compile this example sketch. /* Basic USB Joystick Example Teensy becomes a USB joystick Thanks for your quick reply. Yes, you are right, one option is with 2 teensys (1 connected by usb as a joystick, another one sending data), but i think with keyboard emulation bluetooth could be... Hi again I'd like to ask one question. Is possible to program the teensy 3.2 / LC with a bluetooth module in order to work with it as a joystick usb (serial/joystick/keyboard) for using buttons... Hi again Finally, i bought this rotary and works perfectly with some changes in code!!!! But... Hi tni Yes, you are right. In my code i have these changes Encoder myEnc(5, 6); And Joystick.button() Sorry, but i had to write it in that post. Thanks!!! I will test it. Thanks I have tried without delay(4 ms) and still fails sometimes. #include <Encoder.h> Hello everybody I am using a rotary encoder ( ) And i have some questions for my sketch (I use Joystick button usb - USB TYPE Serial/Keyb/Mouse/Joystick). ... Hello again Paul Do you think that code of "joystick" (this link) in teensy 3.1 is compatible with teensy LC? I want to buy one. ... Thanks a lot Cheers Hi everybody I would like to know if this library SPIflash of arduino to manage LCD is compatible with teensy 3.1 and teensyduino LIBRARY ... I am going to develop a new project and i am thinking about connecting 2 teensy by bluetooth. I would be possible, wouldn't? I think is like connecting to USB-bluetooth of pc. Which... Thank you very much for all the information. Cheers Hi again I have a little question about the new Teensy - LC Is compatible with teensy 3.1... Hi again guys FINALLY SOLVED the BSOD blue screen -I have updated the BIOS (with last one) Thanks again Paul. And if i use thousand of commands DelayMicroseconds in loops during hours of running cycle, the teensy works well? Thank you very much again Paul for your advices. I will check it as soon as possible (i haven't received yet the driver motor) Hi again , this is the manual of driver motor DCS810V1m Thanks again Paul I will give you the model of driver motor a.s.a.p. The speed of these servos is 10 cm in 0,25 seg aprox. Sorry, my english is not very good and i didn't know how explain it. Yes, duty cycle 50%. My application needs to send pulses to a driver motor in order to move industrial servos. I'd like to do... More information? What kind of situations? Thanks in advance Hi everybody, i have 2 questions about sending pulses Question 1 In my project, i want to send some pulses to one pin, and i'd like to know the best way to do it Example I was one week by holidays. This week i'm going to update the BIOS, install Windows 7 64b, and step by step, check when the error appears. Nothing, with the microsoft fix the problem continues. I 'm going to update the BIOS. Run as administrator - don't solve it Installed FTDI Drivers - don't solve it Reinstall driver usb com teensy - don't solve it -- I will restore... Thanks. I will do these steps, one by one, because i'm going to restore the windows with a clean installation (without drivers and software), in order to know when the operation system crashes. ... Hi again Bad News. The same error has shown when i shutdown the computer (if i close de user session, no problem. Only happens when i shutdown the PC) In my laptop windows vista always has... Hi again After reinstall Win 7, the teensy works well and the error has gone. Maybe one temporal conflict between drivers, because now i have installed all mainboard cd drivers and everything... Is a realtek audio driver from my mainboard CD ( Gygabyte GA-P55-US3L) But let me that i do some tests, because i have reinstalled win 7 and i am going to connect the teensy again. (Because i am... Hi again Problem Solved Some conflite between USB teensy and Realtek Audio drivers/games updates that i installed yesterday, because i have restored the windows 7 with a previous backup (2... Thanks a lot for the tips. I am going to check them. It's very strange, because with my another computer (windows vista), this error never has happened. I'll keep you posted Hi everybody. With my win7 64 bits and my teensy 3.1, today it has showed the same error when i have shutdown the PC. 2439 --- Can i reinstall the Teensy Driver? Thank you very much!!! Thanks Paul. One question, this update for big joystick is compatible with teensy 2.0 (atmega32U4)? I think not, but can you confirm it? Regards That's Ok Paul Cheers Hi again Thank you very much for all information :D Cheers ps=I wanted to say Soldering...but google translator is ...... Sorry for my english :p Hi agan guys I am a newbie in electronics and controller boards. I have a teensy 3.1 and i am testing it. I have one little question. The teensy 3.1 has the starndard pins (inputs/outputs)... Thanks again I will test it Cheers Not yet I am using teensyduino. And i don't know if write these code in a new library or use it in my sketch. Or if there is some existent library that use it. thanks Hi again guys, i only know how get the Id or Mac Adress of teensy for a project. Thanks Thanks. And this my_id is in some library? or is a standard function? Cheers With this code will be enough? void loop() { noInterrupts(); read_mac(); interrupts(); Thanks for the advice. Fantastic. Thank you very much indee. Hi guys One question. Is possible get the Serial Number of one teensy 3.1 or chip? If it is possible, how can i do it? which command? Thanks in advance
https://forum.pjrc.com/search.php?s=d5d69a971048b8221a511e9b8a2c3a7d&searchid=5328226
CC-MAIN-2020-16
refinedweb
1,143
75.81
* problem with program hanging jessie puls Greenhorn Joined: Jul 08, 2002 Posts: 3 posted Nov 24, 2004 19:53:00 0 I am not sure why it is freezing up. I know where, but not why. Here is the code where the problem is coming from. I have the line of code that is causing the problem commented out right now. The first one is where it is being called the second is what it is calling. Also if you want to look at all the code you can from If anyone can help at all I would be very greatful. Thanks! jessie import java.awt.*; import java.awt.event.*; public class GuiGameWindow extends CloseableFrame { public final int width = 500; public final int height = 400; private char[][] grid; private Label label; private GameBoard gameBoard; private int firstOrSecond; private CheckboxMenuItem first, second; public GuiGameWindow( GameBoard x ) { makeWindow(); gameBoard = x; firstOrSecond = 1; grid = gameBoard.getGridValues(); } public void makeWindow() { setSize( width, height ); setResizable( false ); setTitle( "Tic Tac Toe" ); MenuBar myMenuBar = new MenuBar(); Menu gameMenu = new Menu( "Game" ); Menu orderMenu = new Menu( "Do you want to Move" ); MenuItem newGame = new MenuItem( "New Game" ); newGame.addActionListener( new menuActionListener( newGame ) ); MenuItem quitGame = new MenuItem( "Quit" ); quitGame.addActionListener( new menuActionListener( quitGame ) ); first = new CheckboxMenuItem( "first", true ); first.addActionListener( new menuActionListener( first ) ); second = new CheckboxMenuItem( "second", false ); second.addActionListener( new menuActionListener( second ) ); gameMenu.add( newGame ); gameMenu.add( orderMenu ); gameMenu.addSeparator(); gameMenu.add( quitGame ); orderMenu.add( first ); orderMenu.add( second ); myMenuBar.add( gameMenu ); setMenuBar( myMenuBar ); label = new Label( "Tic Tac Toe", Label.CENTER ); label.setBackground( Color.darkGray ); label.setForeground( Color.yellow ); add( "South", label ); } public void paint( Graphics g ) { g.setColor( Color.darkGray ); g.drawLine( getWidth() / 3 + 25, 80, getWidth() / 3 + 25, getHeight() - 80 ); g.drawLine( 2 * getWidth() / 3 - 25, 80, 2 * getWidth() / 3 - 25, getHeight() - 80 ); g.drawLine( 80, getHeight() / 3 + 25, getWidth() - 80, getHeight() / 3 + 25 ); g.drawLine( 80, 2 * getHeight() / 3 - 25, getWidth() - 80, 2 * getHeight() / 3 - 25 ); if ( grid != null ) { g.drawString( "" + grid[0][0], 140, 120 ); g.drawString( "" + grid[0][1], 250, 120 ); g.drawString( "" + grid[0][2], 360, 120 ); g.drawString( "" + grid[1][0], 140, 200 ); g.drawString( "" + grid[1][1], 250, 200 ); g.drawString( "" + grid[1][2], 360, 200 ); g.drawString( "" + grid[2][0], 140, 280 ); g.drawString( "" + grid[2][1], 250, 280 ); g.drawString( "" + grid[2][2], 360, 280 ); } } public void setGridValues( char[][] x ) { grid = x; repaint(); } public void SetMessage( String message ) { label.setText( message ); } public int getFirstOrSecond() { return firstOrSecond; } private class menuActionListener implements ActionListener { MenuItem menuItem; public menuActionListener( MenuItem x ) { menuItem = x; } public void actionPerformed( ActionEvent e ) { if ( menuItem.getActionCommand().equals( "Quit" ) ) System.exit( 1 ); if ( menuItem.getActionCommand().equals( "New Game" ) ) { gameBoard.reset(); //this is the line that causes it to freeze up...I don't know why though. //gameBoard.connection().game().play(); } /*as far as I could tell there ins't a CheckboxGroup for CheckboxMenuItems so *I set the states of them explicitly every time. I suppose I could have *built my own, but this seemed easier... */ if ( menuItem.equals(first) ) { firstOrSecond = 1; first.setState(true); second.setState(false); } if ( menuItem.equals(second) ) { firstOrSecond = 2; second.setState(true); first.setState(false); } repaint(); } } } import java.io.*; public class TicTacToeGame { private GameBoard gameBoard; private Player player1, player2, player; private Connection connection; public TicTacToeGame( GameBoard x, Player y, Connection z ) { gameBoard = x; connection = z; setup( y ); connection.addPlayers(player1, player2); connection.setGame(this); player1.setConnection( connection ); player2.setConnection( connection ); gameBoard.setConnection(connection); play(); } public void play() { connection.gameBoard().setMessage("Tic Tac Toe"); player1.setCharacter( 'x' ); player2.setCharacter( 'o' ); try { player = player1; while ( true ) { gameBoard.drawGrid(); while ( true ) { player.activate(); if ( placement( player.move() , player.getCharacter() ) ) break; } if ( gameBoard.horizontalWin() || gameBoard.verticalWin() || gameBoard.diagonalWin() ) { gameBoard.drawGrid(); gameBoard.setMessage( "game over " + player.getCharacter() + " wins!" ); break; } if ( gameBoard.isFull() ) { gameBoard.drawGrid(); gameBoard.setMessage( "game over nobody wins" ); break; } player = switchPlayer( player ); } } catch ( Exception e ) { gameBoard.setMessage( "error: " + e ); } if ( gameBoard.playAgain() ) { player = player1; player1 = player2; player2 = player; play(); } } protected Player switchPlayer( Player player ) { if ( player.equals( player1 ) ) return player2; return player1; } public Player player() { return player; } public boolean placement( int i, char j ) throws IOException { int x, y; if ( i % 3 == 0 ) { x = i / 3 - 1; y = 2; } else { x = i / 3; y = i % 3 - 1; } if ( !gameBoard.isOpenSlot( x, y ) ) return false; gameBoard.placeChar( x, y, j ); return true; } public void setup( Player x ) { if ( gameBoard.getFirstOrSecond() == 1 ) { player1 = x; player2 = new ComputerPlayer(); } else { player1 = new ComputerPlayer(); player2 = x; } } } Again thanks. Stefan Wagner Ranch Hand Joined: Jun 02, 2003 Posts: 1923 I like... posted Nov 25, 2004 18:25:00 0 We don't see your GameBoard, nor its method connection(). But I got an idea. if ( menuItem.getActionCommand().equals( "New Game" ) ) { gameBoard.reset(); //gameBoard.connection().game().play(); return; } Perhaps the GuiGameWindow get's invalid during your calls, and the trailing 'repaint ()' command in the Handler trys to operate on this invalid one? jessie puls Greenhorn Joined: Jul 08, 2002 Posts: 3 posted Nov 25, 2004 18:43:00 0 Actually I fixed the problem..I should have been creating a new thread instead of just trying to call play again. If you wanted to see the rest of the code though there is a link in my previous message to download it in a zip file. Anyway I got it fixed now and it works right. Now I just want to make my computer player a little bit smarter because as it is right now it just picks an open spot randomly. anyway thanks for the input. This is an assignment for a class and we haven't really covered threading yet, so I messed that up, but I was approaching the assignment slightly differently than most of my classmates who were doing the bulk of their work in action listeners on buttons. I didn't really like the way that looked so I decided not to do it that way ( which I believe is what the teacher originally intended since we haven't covered threading in any great detail yet ). Thanks again. jessie I agree. Here's the link: subject: problem with program hanging Similar Threads Null Pointer Exception Error - .contains(p) Ladders and slides Need some help, pleeaaase!! Grid Alignment and Null Exception Need help on two compile errors All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/375241/java/java/program-hanging
CC-MAIN-2014-52
refinedweb
1,055
51.65
What does it mean global namespace would be polluted? I don't really understand what global namespace getting polluted means. Quick Note On Garbage Collection As variables lose scope, they will be eligible for garbage collection. If they are scoped globally, then they will not be eligible for collection until the global namespace loses scope. Here is an example: var arra = []; for (var i = 0; i < 2003000; i++) { arra.push(i * i + i); } Adding this to your global namespace (at least for me) should ad 10,000 kb of memory usage (win7 firefox) which will not be collected. Other browsers may handle this differently. Whereas having that same code in a scope which goes out of scope like this: (function(){ var arra = []; for (var i = 0; i < 2003000; i++) { arra.push(i * i + i); } })(); Will allow arra to lose scope after the closure executes and be eligible for garbage collection. Global Namespace Is Your Friend Despite the many claims against using the global namespace, it is your friend. And like a good friend, you should not abuse your relationship. Be Gentle Don't abuse (usually referred to as "polluting") the global namespace. And what I mean by do not abuse the global namespace is - do not create multiple global variables. Here is a bad example of using the global namespace. var x1 = 5; var x2 = 20; var y1 = 3 var y2 = 16; var rise = y2 - y1; var run = x2 - x1; var slope = rise / run; var risesquared = rise * rise; var runsquared = run * run; var distancesquared = risesquared + runsquared; var distance = Math.sqrt(dinstancesquared); This is going to create 11 global variables which could possibly be overwritten or misconstrued somewhere. Be Resourceful A more resourceful approach, which does not pollute the global namespace, would be to wrap this all in the module pattern and only use one global variable while exposing multiple variables. Here is an example: (Please note this is simple and there is no error handling) //Calculate is the only exposed global variable var Calculate = function () { //all defintions in this closure are local, and will not be exposed to the global namespace var Coordinates = [];//array for coordinates var Coordinate = function (xcoord, ycoord) {//definition for type Coordinate this.x = xcoord;//assign values similar to a constructor this.y = ycoord; }; return {//these methods will be exposed through the Calculate object AddCoordinate: function (x, y) { Coordinates.push(new Coordinate(x, y));//Add a new coordinate }, Slope: function () {//Calculates slope and returns the value var c1 = Coordinates[0]; var c2 = Coordinates[1]; return c2.y - c1.y / c2.x - c1.x;//calculates rise over run and returns result }, Distance: function () { //even with an excessive amount of variables declared, these are all still local var c1 = Coordinates[0]; var c2 = Coordinates[1]; var rise = c2.y - c1.y; var run = c2.x - c1.x; var risesquared = rise * rise; var runsquared = run * run; var distancesquared = risesquared + runsquared; var distance = Math.sqrt(distancesquared); return distance; } }; }; //this is a "self executing closure" and is used because these variables will be //scoped to the function, and will not be available globally nor will they collide //with any variable names in the global namespace (function () { var calc = Calculate(); calc.AddCoordinate(5, 20); calc.AddCoordinate(3, 16); console.log(calc.Slope()); console.log(calc.Distance()); })(); In JavaScript, declarations outside of a function are in the global scope. Consider this small example: var x = 10; function example() { console.log(x); } example(); //Will print 10 In the example above, x is declared in the global scope. Any child scope, such as that created by the example function, effectively inherit things declared in any parent scopes (in this case, that's just the global scope). Any child scope that redeclares a variable declared in the global scope will shadow the global variable, potentially causing unwanted, hard to track bugs: var x = 10; function example() { var x = 20; console.log(x); //Prints 20 } example(); console.log(x); //Prints 10 Global variables are usually not recommended because of the potential to cause problems like this. If we didn't use the var statement inside the example function, we would have accidentally overwritten the value of x in the global scope: var x = 10; function example() { x = 20; //Oops, no var statement console.log(x); //Prints 20 } example(); console.log(x); //Prints 20... oh dear If you want to read more and understand it properly, I suggest going through the ECMAScript specification. It may not be the most exciting of reads but it will help no end. When you declare global variables, functions, etc., they, ehm, go to the global namespace. Aside from performance/memory issues (which may arise), you're likely to run into unfortunate name clashing, when you'll redefine an important variable or use not the value you think you use. Defining things in the global namespace is to be avoided.
https://javascriptinfo.com/view/15005/what-does-it-mean-global-namespace-would-be-polluted
CC-MAIN-2020-29
refinedweb
806
53.81
37325/how-to-list-only-text-files-in-a-directory-using-python I am trying to list only text files in a directory (files with .txt extension). I got as far as listing only files and ignore directories but I am stuck. from os import listdir print(f for f in os.listdir('/home') if path.isfile(f)) How to list only the text files? Well, you are using a complex way. You can do it in a simple way. Try this: import os os.system("ls *.txt") Use os.rename(src, dst) to rename or move a file ...READ MORE ou are using Python 2.x syntax Before printing, you can use a check ...READ MORE Here's the logic. You have to add ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/37325/how-to-list-only-text-files-in-a-directory-using-python
CC-MAIN-2019-47
refinedweb
134
80.78
A Servo is a an enclosed system containing a motor and some supporting circuitry. The shaft of a servo can be rotated to a fixed angle within an arc using a control signal. If the control signal is maintained, then the servo will maintain its angle. Servos can easily be controlled with the Arduino Servo.h library. #include <Servo.h> Servo srv; void setup() { srv.attach(9); // Attach to the servo on pin 9 } To use a servo, you need to call attach() function first. It starts generating a PWM signal controlling a servo on a specified pin. On boards other than Arduino Mega, use of Servo library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. void loop() { Servo.write(90); // Move the servo to 90 degrees delay(1000); // Wait for it to move to it's new position Servo.write(0); // Move the servo to 0 degrees delay(1000); // Wait for it to move to it's new position } Note that you are not guaranteed that the servo reached the desired position, nor you can check it from the program.
https://sodocumentation.net/arduino/topic/4920/servo
CC-MAIN-2022-27
refinedweb
192
63.29
Posted on March 2, 2014 by Kwang Yul Seo Tags: Haskell, Scala, evaluation strategy Haskell is a non-strict language, and GHC uses a strategy called laziness which combines non-strictness and sharing for efficiency. Thus, you can easily implement const which never uses the second argument. const x y = x With this definition, it is okay to pass undefined as the second argument of const because y is not never evaluated. But in Haskell, you can also make an argument strict using the BangPatterns GHC extension. const x !y = x Interestingly, the situation is reversed in Scala whose default evaluation strategy is strict. def const(x: Int, y:Int) = x You can make an argument non-strict by putting the => symbol between the variable name and the type. def const(x: Int, y: => Int) = x
http://kseo.github.io/posts/2014-03-02-evaluation-strategy-haskell-vs-scala.html
CC-MAIN-2017-17
refinedweb
136
52.6
Or login with: Documentation Guidelines Index - What Documentation is Needed? - Documentation using Doxygen - Final Comments Examples Example Submission's to CodeCogs What Documentation is Needed? When you submit source code, there are several main entry fields that CodeCogs requires. These include: - Brief Description. This is typically a single line and very broadly describes the module. This description is used for all functions, class, etc, within a module. This brief description will be used whenever a group of functions are listed (in a catalogues or index), and should therefore broadly summarise the usage of the function. For example: Returns the number of days in the month of a Gregorian calendars. - Detailed Description. This is a descriptive explanation of what your module actually does. It should be clear and consistent and written for the benefit of non-programmers. Therefore, you should not describe the interface to your program here, that comes later. With technical routines, its always good to include the main equations that underpin your work, you may also like to insert figures that further illustrate the process and expected results. We also recommend adding some history , or references for further reading. For example: This function calculates the number of days in a month. The number of days in each month of a year are always the same,. \par References - Source Code. The source code is naturally the most important piece of information in any submission. Each function you submit, should also contain precise details on the interface you've designed. You should also document any constraints, restrictions or known problems with each function. An example should be given that can be easily compiled and run, demonstrating the features of your modules. Output from this small example should also be given - this also helps other developers check that they have correctly compiled and executed your program. The comments on each function may be incased in the Doxygen style comments, /*! */, or entered via the documentation wizard. If you decide to use Doxygen style comments we suggest using the following template (shown in bold), replacing all other text as appropriate. If you wish to submit several functions as part of a single package, merely repeat this template leave several lines of blank spaces between each function. //! {Brief description of function A - typically a copy of description above} /*! {Specialisation offered by the function A} \note {any special restrictions of function A} \param {details of 1st parameters used} \param {details of 2nd parameters used} \param {etc...} \return {details of any return values} \Example \code {working example} \b Output: {output from working example} \endcode \author {you} \todo {further improvement that could be done} \References: {any references used} */ int functionA(...) { ... } //! {Brief description for function B} /*! {Details for function B, as above} */ int functionB(...) Documentation Using DOxygen Markup What is DOxygen? CodeCogs use the Doxygen markup standard to incorporate structured documentation with C/C++ source code. The CodeCogs documentation engine generates the html documentation you see for each component by following the lexical logic of C/C++ source code and combining this with the additional documentation supplied in the markup. This approach means all functions, explicitly documented or not, receive a basic level of documentation while allowing users to add/edit further documentation from within their standard development environment. The CodeCogs documentation wizard creates the documentation (with mark-up) automatically. Users who are familiar with the markup language can enter this directly into the raw documentation that accompanies the code they submit. The rest of this page is dedicated to using Doxygen and how to use it when you are coding: General Points Like a programming language, the documentation markup has a set of commands and rules which must be followed for the system to correctly document your code. This documentation should includes a brief and detailed descriptions for each piece of code you submit. If you don't provide a brief or detailed description for a unit of code (i.e. a function, class, etc), then this function will not be shown in the documentation. This can be useful method for hiding uninteresting functions or variables that you don't deem important for the end user. A good example might be private member functions, which an end user should rarely access and as such should be hidden from the documentation. The code you submit should also contain comments targeted to various elements of the code, for instance a parameter list, or description of member variables and functions within a class (see below). It might sound complex, but if you read through this page and look at the examples we've given at the bottom, you will find that generating great documentation is very easy. Either way, the team at CodeCogs is always available to assist, so if your in any doubt run it by us first! (We also always check documentation before entering it onto the web). top The Documentation Comment The CodeCogs documentation wizard only extracts comment that have an additional explanation mark (!) placed immediately after the start of a line comment or a block comment: - //! A single line brief comment (Codecogs will insert these automatically into any code you submit using your brief description). - /*! A detailed multi line comment */ The addition of the explanation mark allows you to add development comments, in the normal style, to your code, which are ignored by the documentation wizard. Traditionally a brief comment comes should come before a detailed comment, and both should occur immediately before the C/C++ function, variable or structure they are detailing, i.e. //! A function to do something. /*! A function to do something, using the method proposed by Frank and Skinner in their 1993 paper. Returns a double containing something */ // Standard C++ style line comment that remains with the code double toDoSomething(int x) { ... } Note: The documentation wizard will only incorporate comments of this type for certain C++ elements. These include: - Type definitions, which include class, struct and enum declarations - Variables instantiation, including: - variables defined within the global scope. - member variables of a class, struct or namespace. - Functions, including: - global functions. - member functions of a class, struct or namespace. To facilitate the documentation of member variables of a class or struct, you can also use the '!<' command, which informs the wizard that the following comment belongs to the C/C++ element that proceeds the comments, rather than after the comments, i.e. int a; //!< A single line brief comment on the integer a Note: C++ elements that are not documented, may be excluded from the documentation. It is therefore particularly important that you document functions and classes. For consistency, CodeCogs.com suggest that you document all possible C/C++ elements, including those given above. In most cases a brief comment is sufficient, although functions, classes and structs should always have a detailed description. A more complete example using a range of these Doxygen comments might look like this: //! A function to do something. /*! A function to do something, using the method proposed by Frank and Skinner in their 1993 paper. Returns a double containing something */ double toDoSomething(int x) { } //! Returns the distance from a point double getDistance() { return m_Distance; } //! A abstract base class defining the base behaviour of rivers class RiverBase { //! The constructor /*! Initialises all the dynamically created stuff*/ RiverBase(); m_numRivers; //!< Number of rivers //! Gets the Number of rivers int getNumRivers(); };
https://codecogs.com/pages/standards/documentation.php
CC-MAIN-2020-50
refinedweb
1,217
55.24
. .wrap h1.split @import url( html, body, .wrap { height: 100%; } body { background: black; overflow: hidden; color: white; font-family: Open sans; } .wrap { max-width: 800px; margin: 0 auto; } h1 { position: relative; perspective: 500px; top: 50%; padding: 0 20px; transform: translateY(-50%); font-weight: 300; span { opacity: 0; } } // Quotes about learning from goodreads -- var quotes = [ "“Wisdom is not a product of schooling but of the lifelong attempt to acquire it.” <br><br>— Albert Einstein", "“Live as if you were to die tomorrow. Learn as if you were to live forever.” <br><br>— Mahatma Gandhi", "“Tell me and I forget, teach me and I may remember, involve me and I learn.” <br><br>— Benjamin Franklin", "“Study hard what interests you the most in the most undisciplined, irreverent and original manner possible.”<br><br>— Richard Feynman", "“It is important that students bring a certain ragamuffin, barefoot irreverence to their studies; they are not here to worship what is known, but to question it.” <br><br>— Jacob Bronowski" ]; var index = 0; var max = quotes.length - 1; var delay = .02; function random(min, max){ return (Math.random() * (max - min)) + min; } function cycleQuotes(arr, i, sel){ var el = $(sel); var message = arr[i]; el.html(message); var split = new SplitText(el); var time = split.chars.length * delay; $(split.chars).each(function(i){ TweenMax.from($(this), time, { opacity: 0, x: 0, y: random(-200, 200), z: random(500, 1000), // scale: .1, delay: i * delay, yoyo: true, repeat: -1, repeatDelay: time * 4, ease: Power1.easeOut }); }); index = index == max ? 0 : (index + 1); setTimeout(function(){ cycleQuotes(quotes, index, ".split"); }, ((time * 4) + (time * 4)) * 1000); } $(window).load(function(){ cycleQuotes(quotes, index, ".split"); }); Also see: Tab Triggers
https://codepen.io/natewiley/pen/PPyBJg
CC-MAIN-2022-21
refinedweb
275
68.36
Key Takeaways - The current pillar of machine learning development in .NET technology is the ML.NET framework, a library dedicated to the C# and F# programming languages. - ML.NET allows you to train a machine learning model or use existing models. Then you can run them in any environment using a variety of algorithms. - One of the algorithms you can use in the ML.NET library is Anomaly Detection. - There are three types of settings for Anomaly Detection: supervised, unsupervised and clean. - Anomaly Detection is used in cases such as fraud detection or validation of the values entered into the system. - You can evaluate Anomaly Detection in ML.NET using the AUC-ROC metric or Detection Rate At False Positive Count.. Anomaly Detection One such algorithm is Anomaly Detection. As the name suggests, it is about finding what is abnormal from what you expect in your day-to-day life. It helps identify data points, observations, or events that deviate from the normal behavior of the dataset. There are now many distributed systems where monitoring their performance is required. A considerable amount of data and events pass through such systems. Anomaly detection gives possibilities to determine where the source of the problem is, which significantly reduces the time to rectify the fault. It also allows us to detect outliers and report them accordingly. These all applications have one common focus that I have mentioned earlier - outliers. These are cases where the data points are distant from the others, do not follow a particular pattern, or match known anomalies. Each of these data points can be useful for identifying these anomalies and responding correctly to them. The main applications of Anomaly Detection are: - Data cleaning - Fraud detection - Detection of hacker intrusions - Validation of the values entered in the system - Disease detection For better understanding, I will give you the following example. Imagine that you are responsible for controlling an internal road in a city where only passenger cars are allowed to drive. You use a system for this, which gets a dataset with tagged data and recognizes passenger cars. With this, it recognizes a lorry, as you can see in the picture below (1), and it is an anomaly in this case . However, one day the city is celebrating the "green day" when all vehicles in the city center are supposed to be green (including lorries). The dataset is updated, and the anomaly, in this case, is already different (2). As you can see, it is much easier to define what the anomaly is, if you establish the norm or - in other words - if you label examples in the dataset. In this case, we are talking about the supervised setting for anomaly detection because the dataset is labeled. It is worth mentioning that we can distinguish other types, such as clean and unsupervised. Let’s deep dive into those settings. Clean In the clean setting, all data are assumed to be "nominal" and are contaminated with "anomaly" points. The clean setting is the case where the data group is complete and clean. This assumes that all data are nominal data points. It is then the detector's task to detect anomalies within this dataset. Unsupervised That is definitely the hardest case in which the training data is unlabeled and consists of a mix of "nominal" and "anomaly" points. There is no knowledge here from which a result can be expected. The model has to decide for itself what is anomalous and what is nominal. The main goal and objective here is to create clusters from the data and then find the few groups that do not belong to them. It can be said that all anomaly detection algorithms are some form of approximate density estimation. The methods used here include: K-means, One-class Support Vector Machine, orand Self-organizing maps. Supervised The supervised setting is a case where a data set is prepared with all data points marked as anomalous or nominal, which is a great convenience. In this case, all anomalous points are known in advance. That means there are sets of data points that are anomalies, but they are not identified as such for the model. In this case, we can use algorithms such as k-nearest neighbors, Support Vector Machine, or Randomized Principal Component Analysis (PCA) - which I will describe in detail below. Randomized PCA I think it is enough about the anomaly detection theory. Let’s focus on the algorithm that we are going to use in that case. Randomized PCA is used in the context of Anomaly Detection to analyze available features and determine what represents a "normal" class. It uses distance metrics to identify cases that represent anomalies. Thanks to that, the model can be trained using existing data. Randomized PCA means an approximate principal component analysis (PCA) model using the randomized singular value decomposition (SVD) algorithm. I know, it sounds complicated. However, I will try to give you a brief overview of what this method is all about. If you want to explore the subject in more detail, I refer you to the paper by Vladimir Rokhlin, Arthur Szlam, and Mark Tygert. PCA is a frequently used technique in machine learning, particularly for data analysis. It allows us to learn about the internal structure of data. The algorithm works by looking for correlations between variables and determining the combination of values that best represents the differences in results. Then these combined feature values are used to create a more compact feature space, which is called principal components. In Anomaly Detection, all new inputs are analyzed. The algorithm calculates the anomaly score that is determined by the normalized error of the input data. The higher the error, the more anomalous the instance is (5). Example usage of Randomized PCA in ML.NET In that case, we will use the Anomaly Detection Falling People dataset from Kaggle, which was prepared to detect the falling of elderly people in smart homes. Four sensors were used during the experiments and were attached to each person’s chest, ankles, and belt. The features include the three-dimensional parameters X, Y, and Z, which represent the positions of the sensors in each sample. The other features are coded one-shot representations of the activity of each sensor. As for the labels, they represent a fall/normal-life event, where 0 means normal and 1 means anomalous fall event. The first step is to create a console application project (6) and download ML.NET from NuGet Packages (7). You can then proceed to implement and create the model. The basic idea is to create classes corresponding to the attributes of our dataset: public class Features { [LoadColumn(0)] public float Xposition { get; set; } [LoadColumn(1)] public float Yposition { get; set; } [LoadColumn(2)] public float Zposition { get; set; } [LoadColumn(3)] public float FirstSensorActivity { get; set; } [LoadColumn(4)] public float SecondSensorActivity { get; set; } [LoadColumn(5)] public float ThirdSensorActivity { get; set; } [LoadColumn(6)] public float FourthSensorActivity { get; set; } [LoadColumn(7)] public float Anomaly { get; set; } } public class Result { public bool PredictedLabel { get; set; } public float Score { get; set; } } Then you can load the mentioned earlier dataset from the project's folder. We have a testing set that contains twenty files and a training set with five files: The code to load these files is as follows: var trainingSetPath = "TrainingSet/*"; var testingSetPath = "TestingSet/*"; var ml = new MLContext(); var trainingDataView = ml.Data.LoadFromTextFile<Features>(trainingSetPath, hasHeader: true, separatorChar: ','); var testingDataView = ml.Data.LoadFromTextFile<Features>(testingSetPath, hasHeader: true, separatorChar: ','); Now create a training pipeline. Here you select an Anomaly Detection trainer in the form of Randomized PCA, to which you define the names of the features in the parameters. Additionally, you can set up some options like Rank (the number of components in the PCA) or Seed (The seed for random number generation). var options = new Microsoft.ML.Trainers.RandomizedPcaTrainer.Options() { Rank = 4 }; var pipeline = ml.Transforms.Concatenate("Features", columnNames) .Append(ml.AnomalyDetection.Trainers.RandomizedPca(options)); Finally, you can move on to training and testing the model, which is limited to three lines of code. var predictions = model.Transform(testingDataView); var results = ml.Data.CreateEnumerable<Result>(predictions, reuseRowObject: false).ToList(); As you may have noticed before, the Result class is used to capture prediction. PredictedLabel determines whether it is an outlier (true) or an inhaler (false). Score is the result of the anomaly and a data point with a predicted score higher than 0.5 is usually considered an outlier. You can display the outliers in the console using the following code: foreach (var result in results.Where(result => result.PredictedLabel)) { Console.WriteLine("The example is an outlier with a score of being outlier {0}", result.Score); } Additionally, you can check out the number of falls detected what means the number of outliers: var numberOfFallsDetected = 0; foreach (var result in results.Where(result => result.PredictedLabel)) { numberOfFallsDetected += 1; } Console.WriteLine("Number of Falls detected: {0}, Where the total number of measurements is: {1} ", numberOfFallsDetected, results.Count); The crucial part of the model development process is the evaluation. It is this phase that determines whether the model performs better. Therefore, it is critical to consider the model's performance according to every possible evaluation method. Each group of machine learning algorithms has its own dedicated metrics. In the case of Anomaly Detection, we distinguish two metrics that are accessible in ML.NET: AUC - ROC curve and Detection Rate At False Positive Count. The AUC-ROC metric helps us to define and tell us about the model's ability to discriminate between classes. The higher the AUC value, the better the model is. It is determined that values closer to 1 are better. Only if the score is greater than 0.5 can we say that our model is effective. Values of 0.5 or lower indicate that the model is no better than randomly allocating inputs to anomalous and normal categories, which means that it is not at all useful. AUC-ROC curves are typically used to graphically represent the relationship and trade-off between sensitivity and specificity for each possible cut-off point for the test performed or for combinations of tests performed. If you want to know the details of this metric, I refer you to a great article by Victor Dey. Detection Rate At False Positive Count is the ratio of correctly identified anomalies over the total number of anomalies in our test set, indexed by each false positive. In other words, it means that for each false positive item, there is a detection rate value with the number of false positives. Values closer to 1 are good. If there are no false positives, then this value is equal to 1. To use these metrics in ML.NET, we can use the Evaluate method, the arguments of which are the results of the prediction and the name of the label column. In our case, it is a column called Anomaly, and we will use the AUC-ROC metric: var testMetrics = ml.AnomalyDetection.Evaluate(predictions, "Anomaly"); var areaUnderRocCurve = testMetrics.AreaUnderRocCurve; Console.WriteLine("AUC Curve: {0}", areaUnderRocCurve); The Area Under ROC Curve metric value of 0.74 may indicate that the model created is robust. As I mentioned earlier, values being close to 1 are better and it can suggest that the algorithm works efficiently and the results are valuable. Summary In this article, I have briefly outlined the theory behind Anomaly Detection. Additionally, I have introduced the PCA method, which is a common choice for this problem. Of course, for using this algorithm in ML.NET, you do not need to know the theory behind that. However, I assume that such knowledge of the basics allows for a better understanding of the issues and the results obtained. Additionally, you can later compare these outcomes with the results obtained from other libraries or sources. About the Author Robert Krzaczyński is a software engineer who specialises in Microsoft technologies. On a daily basis, he develops software primarily in .NET, but his interests reach much further. Additionally, he delves into machine learning and artificial intelligence. After hours, Robert also shares his knowledge on a blog (bush-dev.com). He holds a BSc Eng degree in Control Engineering and Robotics and an MSc Eng degree in Computer Science. Community comments
https://www.infoq.com/articles/anomaly-detection-ml-net/?utm_campaign=infoq_content&utm_source=infoq&utm_medium=feed&utm_term=global
CC-MAIN-2022-05
refinedweb
2,049
56.05
: Vodkin- Kasparov or Limonov at least would permit fair elections letting the people select the ones who, in their opinion, would do the best job.). @ ChiefBreenie I answer to your comment as I described the organization of Russian state today - and the law which has been passed and whose forestry specialists blame a carelessly enacted 2007 law that cut 90% of forest guards. That are facts and politic.. I don't know from which country you are but have you ever heard this type of sentence in your parliament which was pronounced shortly before the vote of this law, the speaker of the Duma proclaimed that parliament is not a place for deliberation. Also we are speaking of management of the crisis - and the possibility for the Russian politicians - in charge of this crisis - to be criticized and to be changed? Who will decide for the poor Russian people who have lost everything during these fires, who will be condemned of negligence for the Russian people who lost their life - even children? Nobody with this Russian political system. European Union ( of course Germany) as many other countries were ready to help - but like during Kurst event , Putin is too "proud" for that - meaning that for his PR campaign it is better that he is alone in the airplane which brings down some water. That is a so primitive PR campaign, isn't it? Our good friend , a real Russian Chauvinist Kid, a passionated supporter of Putin, wants to tell me that politically Putin is not responsible at all. My other good Russian friend Yevgenia Albats who is Professor of Political Science at The Higher School of Economics thinks differently. I am starting to resume by a little story she told .. Later other journalists call the mayor’s press secretary has been telling journalists that there is no reason for the mayor to return to Moscow. “Why should he?” said the secretary. “Is there a crisis in Moscow? No, there is no crisis.” There was no crisis at Moscow?. What these facts mean? For. And how Putin presents himself these days of crisis? Rare candid footage of Prime Minister Putin, displayed on government channels, for example depicted him visiting one of the towns in the region. People who had lost their homes, clothing, and everything else were complaining to Putin that the regional and local government did not warn them that the fire was coming. There were practically no fire trucks. “No one even tried to save us,” they wailed to Putin, who was accompanied by the regional governor, Valery Shantsev. And what happens to this friend of Putin, regional governor, Valery Shantsev, responsible of the management of this crisis situation?. And what are the consequences of such failed policies and how to analyze it some of his causes ?. What is the politically consequences for Putin and his allies? all. I would highly recommend reading the Moscow Times blunt article about Russia's preparedness by George Bovt "Putin's Vertical Power Disaster" Here is part of it: ." YuriyMoscow wrote:" summarizing cowboy walter - Putin is responsible for wildfires and for the heat." Nobody said Putin is responsible for the heat, but surely governments ARE responsible for any and all emergency measures and facilities required to protect the country's population. You cannot disassociate Putin from the miserable state of fire emergency preparedness revealed in the areas affected by fires. After all Putin was the president of the country for eight years and has been now the head of the government for over two years. Who, if not the president and his government, is responsible for allocating budget finances to purchase adequate fire figting equipent, to train and mobilise crews, ensure access to ample water supplies, etc. etc. Simply blaming the EU or even walterbenjamin for Russian government's failures will not solve your problems. As to your complaint that you "did not hear any offer from the EU and US to help Russia with the equipment (planes), firefighters, etc..." that's because you have chosen to ignore facts. Indeed several EU countries ( eg. Poland, Germany, Italy etc.), as well as Ukraine, Belarus, etc. have had their firefigting crews with equipment on the scene for some time. I haven't heard about Russia's main allies, such as Abkhasia or Nicaragua sending any firefighting crews. A more appropriate question for you to answer would be whether Russian authorities have provided all these foreign planes, their crews and ground equipment the essential access to emergency commuications, to gasoline and water supplies, to facilities for crews accomodation and dozens of other similar issues to ensure their effectiveness. Putin's Hollywood-like stunt of flying a firefighting plane and bragging about his skills has done absolutely nothing to enhance firefighting response, it was all cheap publicity, pure and simple. @YuriyMoscow “Another example of the article with the totally BIASED attitude towards Russia “ I understand your grievance. There were abnormally high temperature for Russia, it’s an out of ordinary event so it’s hard to expect a proper fire containment by the authorities. But, as long as Russia disregards its neighbours, lashes at US and EU, its vindictive about its near past and says Stalin was a”good manager”, you can expect more sarcastic postings about the fires and less sympathetic attitudes. @walterbenjamin May I cast your memory back to the winter just gone of 2009/10 when a lot of Europe and indeed the US came to a standstill due to ice/snow/sub-zero temperatures. Russia seems to manage quite well with temperatures going into the -30s and even -40s every winter: planes manage to take off; trains keep going (and don't get stuck in an under-water tunnel stranding its passengers for hours [Eurostar in the Channel tunnel]) and the cold does not dominate the headline news for weeks on end. These temperatures are abnormally high for the Russian summer. How is any government meant to turn down the heat? While I do not agree with the majority of the policies of Mssrs Putin and Medvedev I think it's difficult to point blame at them in this instance: it's a global fault. Perhaps once the entire world gets over its obsession with hydrocarbons then the weather will return to normal. As another poster pointed out, re: exploiting this for PR: any and all politicians do that. Kissing babies and hugging old ladies is part of the job. summarizing cowboy walter - Putin is responsible for wildfires and for the heat.. Does he "responsible" for the Martyan attack or all the bad things on Earth? @ Vodkin Are you ignorant or what? The wildfires in Russia are the result of Putin's policies. If the majority of Russians approve these policies: good for them , they support the consequences. NATO knows that it doesn't need arms but only matches to fight Russia - only during summer time. This good article is resumed by : "there is one thing they cannot do: make Russia safer and better governed." It is strange that nobody speaks about the effects of Climate Change. I remember what Putin proposes for Russian's policies at Copenhagen . I think today the quantity of CO2, and others gas emitted during these wildfires makes Russia one of the main polluter of the World - some of them could be radio-activ ? Another example of the article with the totally BIASED attitude towards Russia and which was once again very well appreciated & supported by the "local agents provocauteurs". Speaking seriously from the UNBIASED point of view (as a Muscovite who was in Moscow during last two weeks), and given the facts that: 1. Russia is the biggest country on the planet; 2. Temperature records were the biggest during the CENTURIES (and even the Economist confirms it); We should understand that IT IS NOT easy task to tackle with the wildfires. By the way, till this morning (when the situation is stabilizing) I did not hear any offer from the EU and US to help Russia with the equipment (planes), firefighters, etc... And finally, do not pervert the facts, Russian prime minister could and should have been participated in the firefighting. And he DID it. IT IS HIS DUTY TO DO AND TO SHOW to the people that he helps them not only like prime minister but as the ordinary pilot (in this case). As for the some kind of advertising, don't forget that he is politician. That's all. For instance, Obama was also very let's say convincing when he was visiting the Mexican gulf..And he also did his job. I also think that among gloating "commentators" it will not be easy task to find persons who would like to participate at the aerial firefighting. Much better and safe is to carp and pervert the facts.. My goodness, why people have to be so tasteless and disgruntle? Do your politicians go fly an airplane over a fire? Shut up before you see that happens, how did the last Polish president ended up even in a normal flight with a seasoned pilot? If you get get a 'black swan' - every day over 35C for 8 weeks, I want to see how any country copes with this. I seriously doubt that Kasparov or Limonov would perform any better than Putin and Medvedev. ...How much he cares... ...Just as far as he can spit, and that's probably about as much as his serfdom expects him to donate. @Ernst Raxarov You could make money by writing a book like "Cloning for Dummies" :))) The problem with Personality/Party cult's (and Russia has always had them) is that they are so hard to dislodge. In Vanuatu for example there is a Messianic cult which believes that one day the US Marines will return (they left in 1945-46) to restore peace and prosperity to their members and village. Their totem is a coca-cola bottle. The truly distasteful part is that there are leaders (quite old) who despite their experience in life (well travelled/read) continue to propogate these cults because they serve their interest. 2012 indeed. @atikinn A more appropriate comment would be what, in your opinion, the true level of Putin support ? Great article, it's a real show how the government copes with fire and smog and how Putin and Medvedev are using this show to raise their PR rating. Disgusting. Didomyk, stop making fools of the Russians, your comments are 99% irrelevant to what is written in the articles.
http://www.economist.com/comment/625190
CC-MAIN-2014-35
refinedweb
1,756
60.75
Hello It’s possible to create ionic app like rest server. I want to create app which connects to the server . Then the application listens and the server call to app with request “do something”. I don’t want to call the server from the app every 5 seconds. Has anyone done something similar? Sorry for my English. Hello What you are looking for should be Web Sockets Thank you. Your solution should be good. I wonder if there is a possibility to do from ionic app rest server, which will be able to call to methods from postman. I found expressJs. Can I use it in ionic application? I tried to do something like that but not working: import express from 'express'; const app = express(); const port = 3000; app.get('/', (req, res) => res.send('Hello World!')); app.listen(port, () => console.log(`Example app listening on port ${port}!`)); Expected action: server side send request to ionic application by ip address (for example xxx.xxx.x.x:3000/) and then ionic application response to sever ‘Hello World!’
https://forum.ionicframework.com/t/ionic-app-like-rest-server/165376
CC-MAIN-2020-24
refinedweb
176
69.58
<xsl:stylesheet <xsl:output <xsl:template <html> <h4> <!-- Like date in '12 November 2008' format --> <xsl:value-of </h4> <xsl:for-each <!-- Other stuff in here --> </xsl:for-each> </html> </xsl:template> </xsl:stylesheet> four possible options - If you are using XSLT2, there is a current-date() function that gives you all you need Your stylesheet has a version 1.0, so you don't have current-date() available. That is why you get the erro message. You can only set this to 2.0 if you have an XSLT2 processor available of course - If you are using saxon, xalan or some other, you have access to exslt (verify in the date functions section of). This solution uses exernal functions, so they are pretty bound to a specific processor. Make sure you get the namespace right So th ereason why the exslt extension doesn't work could be because your processor does not support it, or that you set the namespaces the wrong way - you could also write an extension function yourself. In msxml that would be a simple JavaScript function,; in .NET that could be C# - If your processor is XSLT1 and is not EXSLT aware, you will not be able to access the current date from whitin the Stylesheet and you will have to pass the current date from your application as a parameter to the XSLT. It would be interesting to know how your architecture looks like As soon as you figured out what the best approach be for you, I will be happy to help you with the code This will also work in Internet Explorer Open in new window My context is IE 7.0 or firefox, i.e. opening the xml in these then saving the html result. I will try this. I have seen this code either on the .net or experts-exchange and did not try it because i was focusing on using existing standard functions (per some posts). I will test and award points and will give bonus points for a solution using existing standard functions. i.e. a function with some formatting options so no extra code is needed. Thanks Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications. you are down to option four. since browsers don't support XSLT2 and extension functions don't work across browsers. Your only option is - running the XSLT from a JavaScript in an HTML page (preferably using sarissa library for cross browser XSLT) - create the current dat inside the javascript - pass the current date to the XSLT from within javascript complex no? Well it is the only way it can be done, I am afraid. If you drop FireFox and can hapily live with IE alone, the above example will work for you There is no XSLT2 in browsers. There is no solution for doing this in standard XSLT1. Experts Exchange Solution brought to you by Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial OK tried in IE , works and as you said does not work for Firefox. Unfortunately (and i did not say this) IE works fine for viewing the data but i need Firefox to save the data as html. I can't find an option in IE7 to save a xml rendered page as html. The "save as" only seems to want to save the original xml file. Many thanks Thanks Use the XSLT for viewing in IE and use msxsl command line tool to effectively transform the XML to the same HTML using the same XSLT here you can find sarissa but I would definitely go for the msxsl solution... a lot less complexity let me know if you still want sarissa and need help with it and about the date function, that is simply JavaScript date object cheers Geert
https://www.experts-exchange.com/questions/23876978/xsl-place-current-date-into-output.html
CC-MAIN-2018-43
refinedweb
668
78.28
As per the trend, everyone is talking about Natural language processing, speech recognition, text generation etc. In this article, we will discuss on how can we get text from the video or audio files. Pre-requisites: >> Python 3.7 >> ffmpeg >> Libraries: os and speech_recognition Step 1: Prepare directory Create a new folder and add some video files. For instance, I have created a folder ‘SpeechConversion’ and in this folder I have one video song (in .mp4 format). Step 2: Import libraries Import the required libraries, refer below code: import os import speech_recognition as sr Step 3: Command for video conversion I am using ffmpeg to convert the video file to audio. First, I will convert this to mp3 format and then will transform it to the wav format, as wav format allows you to extract better features. Here, my video file name is Bolna.mp4, I convert this to Bolna.mp3 then to Bolna.wav. Below are the commands for the conversion process. Let’s save them in variables as below. command2mp3 = “ffmpeg -i Bolna.mp4 Bolna.mp3” command2wav = “ffmpeg -i Bolna.mp3 Bolna.wav” Step 4: Execute video conversion commands Let us now execute these commands using the ‘os’ library as below os.system(command2mp3) os.system(command2wav) Step 5: Load the wav file Now, let us load the wav file that was created in the above step. The below code can be used for the same. r = sr.Recognizer() audio = sr.AudioFile(‘Bolna.wav’) Step 6: Process the wav file Lastly, as per the required, set the duration of the audio you want for further processing. I am keeping this as 100 seconds duration for test purposes. You can change the same as per your convenience. with audio as source: audio = r.record(source, duration=100) print(r.recognize_google(audio)) Voila, you can get the text for the first 100 seconds of the video or audio file. Further enhancements: The text generated can be later used for Natural language understanding and Natural language generation processes. Hope this helps. Do share your comments below. Thank you..!! Source: Artificial Intelligence on Medium
https://timmccloud.net/blog-how-to-generate-text-from-a-video-file-using-python/
CC-MAIN-2020-50
refinedweb
352
68.06
TL;DR – Python class is a blueprint for a kind of object. In Python, you can instantiate classes to create new objects. Contents What is a Python class? Unlike a procedural programming language, any coding done in Python revolves around objects. In some object-oriented languages, objects are just basic chunks of data and attributes. However, in Python, they consist of functions as well as information. In short, a Python class is for defining a particular type of object. Because Python objects can have both function and data elements, Python classes define what methods can be used to change the state of an object. They also indicate what attributes the object can have. Creating a Python class definition It’s not hard to define Python class. To do so, you’ll need the class keyword: class Example: "A basic example class" variable = 123 If you run the above code in a Python environment, you’ll find you can call Example.a to return an integer value. This is an example of a class for data-only objects, but it’s equally easy to define a class that returns a function object by adding the def keyword to your code: class Example: "A basic example class that returns a function object" def b(self): return "this is an example class" Instantiating a Python class object With the above Python class examples, you can create a class object through attribute referencing using Example.a and Example.b respectively. It’s also possible to instantiate a class object via function notation. Simply set a variable equal to the class in the same way you’d call a function with no parameters: class Example: "A basic example class that returns a function object" def b(self): return "this is an example class" c = Example() With this, a new class object will be instantiated and attributed to local variable c. Theory is great, but we recommend digging deeper! The constructor method for class object instantiation It’s possible to simulate the constructor of a class in Python using the __init__() method. This is a helpful way to initialize attributes for all objects in a given class: class Square: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.width * self.length r = Square(20, 2000) print("Rectangle Area: %d" % (r.area())) This Python class example results in the following output: Rectangle Area: 40000 Note: Python uses a default constructor for any class where you don’t add your own. Working with complex class objects Of course, a key reason to use classes in Python is that doing so allows you to create custom object types. With these, you can instantiate variables that represent things like co-ordinates or other complex data points: class PartsColor: "Creates a class" def __init__(self): "Create a new color for each part" self.hood = "Blue" self.wheels = "Red" self.doors = "Green" e = PartsColor() # Instantiate two objects to represent points f = PartsColor() print(e.hood, f.wheels, e.hood, f.wheels, e.doors, f.doors) # Assign each point a unique location This will output: Blue Red Blue Red Green Green Python class: useful tips - You can use Python functions like getattr(obj,name,default)to check and modify the attributes of an object even after they have been initialized through a Python class. - In Python classes, there’s a big difference between inheritance and composition. Inheritance transfers attributes and methods used in one class to another. Composition means that a base class isn’t inherited from.
https://www.bitdegree.org/learn/python-class
CC-MAIN-2020-16
refinedweb
591
62.58
A Microsoft Foundation Classes (Microsoft Windows Vista+) backend for the Toga widget toolkit. Project description A Microsoft Foundation Classes backend for the Toga widget toolkit. Toga requires Python 3 THIS IS A PLACEHOLDER PROJECT At present, it has no functionality - it exists purely to reserve the PyPI namespace. This package isn’t much use by itself; it needs to be combined with the core Toga library. For more details, see the Toga project on Github.. Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/toga-mfc/
CC-MAIN-2018-26
refinedweb
102
56.96
Opened 12 years ago Closed 12 years ago Last modified 2 years ago #4518 closed (fixed) Null string in DecimalField results in error: decimal.py _raise_error, line 2267 Description I am running the django web server/sqlite on WinXP with Python 2.4 and the latest django SVN version. In keeping up with the FloatField to DecimalField changes I came across an error in both the admin pages and user pages with one of my apps. In the debug page (excellent feature), an InvalidOperation was being raised at location "C:\Python24\lib\decimal.py in _raise_error, line 2267". I traced the cause to some of my DecimalField values had empty string values at some stage of the process. I have blank=True and null=True on that field. A change to typecast_decimal function at line 96 of C: \Python24\Lib\site-packages\django\db\backends\util.py solved the problem. def typecast_decimal(s): if s is None: return None return decimal.Decimal(s) became: def typecast_decimal(s): if s is None or s == '': ### Change return None return decimal.Decimal(s) Suggested for a SVN change. (In [5450]) Fixed #4518 -- Added handling of empty strings in typecast_decimal() for SQLite's benefit. Thanks, Richard House.
https://code.djangoproject.com/ticket/4518
CC-MAIN-2019-30
refinedweb
203
67.86
Swift allows you to pass a native Swift string directly to a C API that takes a C String (i.e. a char *). For example, you can call the strlen function from Swift like this: import Darwin // or Glibc on Linux strlen("Hello 😃") // → 10 This works even though Swift imports the const char * parameter as an UnsafePointer<Int8>!. The full type of the strlen function as imported by Swift looks like this: func strlen(_ __s: UnsafePointer<Int8>!) -> UInt The type checker allows you to pass a String value to an UnsafePointer<Int8> or UnsafePointer<UInt8> parameter. When you do that, the compiler will transparently create a buffer containing the UTF-8-encoded1, null-terminated string, and pass a pointer to that buffer to the function. No built-in support for arrays of C strings The way Swift handles single char * arguments is very convenient. However, some C functions take an array of strings (a char ** or char *[]), and there is no built-in support in Swift for passing a [String] to a char ** parameter. An example where this would be useful is the posix_spawn function to launch a child process. The last two arguments of posix_spawn, argv and envp, are arrays of strings in which you pass the new process’s arguments and environment variables. Specifically, the documentation says this: argv[and envp] is a pointer to a null-terminated array of character pointers to null-terminated character strings. Swift translates these arguments’ C type of char *const argv[] to the unwieldy UnsafePointer<UnsafeMutablePointer<Int8>?>!. The exclamation point, denoting an implicitly unwrapped optional, tells us that this API doesn’t have nullability annotations, i.e. Swift doesn’t know if the function accepts passing NULL (in which case the outer UnsafePointer would be an optional) or not. We must refer to the documentation to answer this question. In this example, the documentation states explicitly that argv must contain at least one element (the file name of the program being spawned). envp can be NULL to signify that it should inherit the environment of its parent process. Converting an array of Swift strings to an array of C strings Suppose we want to provide a nice Swift interface for posix_spawn. 2 Our wrapper function should take the path of the program being launched and an array of strings for the arguments: /// Spawns a child process. /// /// - Returns: A pair containing the return value of `posix_spawn` and the pid of the spawned process. func spawn(path: String, arguments: [String]) -> Int32 Now we need to convert our arguments array to the format posix_spawn expects. This requires several steps: - Encode the element strings in UTF-8. - Add a null byte to each UTF-8-encoded string. - Copy all UTF-8-encoded, null-terminated strings into a single buffer. - Add another null byte at the end of the buffer to denote the end of the C array. - Make sure the buffer lives for the lifetime of the call to posix_spawn. withArrayOfCStrings in the standard library The Swift team needed the same functionality for running the unit tests of the standard library, and that’s why the standard library’s source includes a function named withArrayOfCStrings that does just that. Now this is an internal function that is not exposed publically to stdlib clients (although it is declared public, presumably because otherwise the unit tests wouldn’t see it). But we can still take a look at it. This is the function’s interface: public func withArrayOfCStrings<R>( _ args: [String], _ body: ([UnsafeMutablePointer<CChar>?]) -> R ) -> R It has the same form as withUnsafePointer and its variants: it’s generic over a result type R and takes a closure. The idea is that, after performing the conversion of the strings array to a C array, withArrayOfCStrings calls the closure, passing the C array in, and forwards the closure’s return value to its caller. This gives the withArrayOfCStrings function full control over the lifetime of the buffer it creates. We can now implement our spawn function like this: /// Spawns a child process. /// /// - Returns: A pair containing the return value of `posix_spawn` and the pid of the spawned process. func spawn(path: String, arguments: [String]) -> (retval: Int32, pid: pid_t) { // Add the program's path to the arguments let argsIncludingPath = [path] + arguments return withArrayOfCStrings(argsIncludingPath) { argv in var pid: pid_t = 0 let retval = posix_spawn(&pid, path, nil, nil, argv, nil) return (retval, pid) } } Why does this work? You’ll notice that withArrayOfCStrings’s closure parameter has the type ([UnsafeMutablePointer<CChar>?]) -> R. The argument type [UnsafeMutablePointer<CChar>?] doesn’t seem to be compatible with the UnsafePointer<UnsafeMutablePointer<Int8>?>! type that posix_spawn requires, but it is. CChar is just a typealias for Int8. And just like Swift has special handling for passing strings to C, the compiler transparently bridges native Swift arrays to C functions that take an UnsafePointer<Element>, so we can pass the array directly to posix_spawn, as long as its element type matches the pointer’s pointee type. This is how spawn looks in use: let (retval, pid) = spawn(path: "/bin/ls", arguments: ["-l", "-a"]) And this is the output when you execute the program: $ swift spawn.swift posix_spawn result: 0 new process pid: 17477 total 24 drwxr-xr-x 4 elo staff 136 Oct 27 17:04 . drwx---r-x@ 41 elo staff 1394 Oct 24 20:12 .. -rw-r--r--@ 1 elo staff 6148 Oct 27 17:04 .DS_Store -rw-r--r--@ 1 elo staff 2342 Oct 27 15:28 spawn.swift (Note that posix_spawn returns an error if you call it in a playground, presumably because a playground’s sandbox doesn’t allow spawning child processes. It’s best to try this from the command line or by creating a new command-line project in Xcode.) How does it work? The full implementation of withArrayOfCStrings looks like this: public func withArrayOfCStrings<R>( _ args: [String], _ body: ([UnsafeMutablePointer<CChar>?]) -> R ) -> R { let argsCounts = Array(args.map { $0.utf8.count + 1 }) let argsOffsets = [ 0 ] + scan(argsCounts, 0, +) let argsBufferSize = argsOffsets.last! var argsBuffer: [UInt8] = [] argsBuffer.reserveCapacity(argsBufferSize) for arg in args { argsBuffer.append(contentsOf: arg.utf8) argsBuffer.append(0) }) } } Let’s go through it one line by line. The first line creates an array of the UTF-8-encoded character counts (plus 1 for the null-termination byte) for the input strings: let argsCounts = Array(args.map { $0.utf8.count + 1 }) The next line takes these character counts and computes the character offset for each input string, i.e. at what position in the buffer each string will begin. The first string will of course be positioned at offset 0, and the subsequent offsets are computed by cumulating the character counts: let argsOffsets = [ 0 ] + scan(argsCounts, 0, +) The code uses a helper function named scan for this, which is defined in the same file. Note that argsOffsets contains one more element than argsCounts. The last element of argsOffsets is the offset behind the last input string, i.e. the required size of the buffer. The next step is create a array of bytes (the element type is UInt8) that serves as the buffer. The call to reserveCapacity is not strictly necessary because the buffer would grow automatically, but if you know the required capacity beforehand, reserving it at the start can avoid repeated reallocations: let argsBufferSize = argsOffsets.last! var argsBuffer: [UInt8] = [] argsBuffer.reserveCapacity(argsBufferSize) Now the UTF-8-encoded bytes can be written into the buffer, adding a null byte after each input string: for arg in args { argsBuffer.append(contentsOf: arg.utf8) argsBuffer.append(0) } At this point, we have an array of bytes ( UInt8) in the correct format. We still need to construct the array of pointers that point to the elements in the buffer. That’s what the final section of the function does:) } We ask the array for a pointer to its elements buffer using withUnsafeMutableBufferPointer. The first line in the inner closure then converts the element pointer’s type from UnsafeMutablePointer<UInt8> to UnsafeMutablePointer<CChar> by way of UnsafeMutableRawPointer. (Since Swift 3.0, you can’t directly convert between typed pointers anymore, you have to go through Unsafe[Mutable]RawPointer first.) This is not very readable, but the only important thing for us is that after this line, the local ptr variable is an UnsafeMutablePointer<CChar> that points to the first byte in the buffer. Now, to construct the array of pointers, we map over the array of character offsets we created in line 2, and increment the base pointer by each offset. The final step is then to set the final element in the resulting array to nil. This serves as the final null pointer that denotes the end of the array (remember that we said above that argsOffset contains one more element than the input array, so overwriting the last element is correct). Finally, we can call the closure passed from the caller, passing in the array of pointers to C strings.
https://oleb.net/blog/2016/10/swift-array-of-c-strings/
CC-MAIN-2017-13
refinedweb
1,494
53.31
Last. However, those were based on some specialized controllers, which was making them a bit costly. This time the plan was to use more or less conventional components, which could be reused from other electronics/robotics/IoT projects and to keep the total price down. The idea I had in mind was simple enough - to build a remote controlled robot, which has a camera on board and so allows seeing from the "robot's eyes" remotely. Obviously it was supposed to be able to move around, so wheels and motors is a must. Additionally some sensors could be of use, like ultra sonic distance sensor, for example. Another idea was to develop some reusable software, which could be of use to control robots built to the similar spec. It should allow either some simple robot control directly from a web browser or development of specialized client applications to provide more advanced control and adding extra features, like computer vision, for example. And so it was decided to build the robot based on a Raspberry Pi board. It comes for a relatively small price and provides enough power and connectivity to handle all the other electronics required for turning the idea into action. As for the name, it was called PiRex. This was a result of brief brain storming with kids over a walk. Why PiRex? Well, as my youngest said - it is a Rex based on Pi. No, it does not look anyway scary as Tyrannosaurus Rex. But the name just got stuck. Before going into details of the building process and the software developed, it would be nice to have a quick preview of the final result. Here is the way it did look in the end. width="480" data-src="/KB/Raspberry-Pi/1237052/pirex_robot.jpg" class="lazyload" data-sizes="auto" data-> Nothing too fancy - just a wheeled robot. And yes, it is not really a Rex. More of lunch box on wheels, equipped with camera, distance sensor, Wi-Fi antenna and a battery module. Also, here is a quick video demo, showing control of the PiRex robot from a web browser and from a dedicated .NET client application. The web UI makes it all simple - run the software on Raspberry Pi and the robot is ready to be controlled from the web browser of your choice. While the client application allows more agile control with game pad devices, for example, and integration of different image processing SDKs to process video coming from the bot. All of the developed software is published on GitHub. So, if anyone would like to repeat the building steps and start playing with the robot, it is all there for a quick start, providing the base for any customizations in mind. Before we start with writing/compiling any code, let's get the robot built first. For that we better get all the parts first, so that we could estimate the total cost and think about how to put these all together. Of course things can be done iteratively, adding new components as things progress. However, it may result in a complete rebuild of the project, sometimes even more than once, which is time and money (or just money2). The issue we'd better avoiding is to start with few components we think are the most critical, build something with it and then realize that there is not enough space to fit the next component, or there is not enough of battery power for all electronics we need, or the final assembly gets heavy enough and chosen motors simply cannot do much. How many of those mistakes happened to me while getting to the final working result? Two. First, could not fit everything into a compact design initially planned. And then found the motors of the first choice were too cheap and did not have enough power to get the robot moving. Below is the list of components, which were used for building the PiRex robot, and their price estimate (based on Amazon or any other on-line shops which fit better): All together it comes to 191.00£. To get it safe, in case something was forgotten or simply have some spare budget, lets plan about 200£ for a Raspberry Pi based robot. It may not sound very cheap. But there is little to do to get the final price lower. The most expensive components are motors with wheels. Well, you have to accept this. Trying to save on them and getting something cheaper may result in increased price in the end, when it gets clear the robot can not really move. Saving much on electronic components or batteries may be tough as well. Another option would be to use some ready made robotics kits. It really does save time. But as for me, it takes away fun and creativity as well. Anyway, many of the kits are more expensive actually, even without all electronic components included. Once all components are at hand, it is time put them all together into a working robot. To control motors a simple L293D chip is used, which allows controlling up to two motors independently. The chip itself can only turn motors on/off and control direction of their rotation. Connecting its 1,2EN and 3,4EN pins (pins 1 and 9, see L293D data sheet) to a pulse modulation module (PWM) also allows controlling speed of motors. However, Raspberry Pi has only one hardware PWM, so controlling speed of both motors is not available (unless software PWM is used, which is to be mentioned later). Note: for a quick introduction to L293D, its wiring and simple control have a look at this tutorial: Controlling DC Motors Using Python With a Raspberry Pi. To make things easier to connect, it is preferred to put smaller components on individual circuit boards. For example, as the picture below shows, I put the L293D chip on its own breakout board, which has individual terminal blocks for connecting motors, power supply and Raspberry Pi's pins. This way all the soldering is concentrated only on these little boards, while the rest of connections are done by screwing a wire into a terminal block on one side and attaching to Raspberry Pi's pin on the other side. width="480" data-src="/KB/Raspberry-Pi/1237052/motors_board.jpg" class="lazyload" data-sizes="auto" data-> The second breakout board holds 2 LEDs (used to show run time and connectivity status) and terminal block for connecting two switch buttons (planned to be used for some interaction with the robot). All required resistors are there as well; only connectivity to Raspberry Pi and components is missing. While LEDs and switches are really optional for the final result, this board is also used for connecting to HC-SR04 ultrasonic sensor (the lower two resistors for voltage divider and a terminal block). Note: for more information about wiring and using HC-SR04 sensor have a look this tutorial: Interfacing HC-SR04 Ultrasonic Sensor with Raspberry Pi. width="480" data-src="/KB/Raspberry-Pi/1237052/leds_buttons_board.jpg" class="lazyload" data-sizes="auto" data-> Having the two breakout boards above, its time to pack them into our lunch box together with some other components - this completes the first layer of the robot. Some of the terminal blocks already get connected to motors and switches, while the others wait for adding the second layer holding a Raspberry Pi. Note: there are two extra switches which are set loose for now. Those are to be used to switch the robot on/off and to provide power supply to motors (motors are not really needed during most of the software debugging, so making them independent is quite handy). width="640" data-src="/KB/Raspberry-Pi/1237052/layer1.jpg" class="lazyload" data-sizes="auto" data-> The second layer of the assembly holds a Raspberry Pi and another small breakout board, which is used to get power supply from micro USB sockets and direct it to electronic components (through switches to get it all on/off). Initially it was planned to power both Raspberry Pi and motors using the same portable charger battery (which does provide two outputs), hence there are two USB connector on the breakout board. However, later it was decided to power motors separately with a pack of AA batteries and so the breakout board got a bit extended with an extra terminal block. Now, adding the final and the main component, Raspberry Pi, completes the assembly to about 99%. Here is the way it looks if we pop the hood of the PiRex. width="640" data-src="/KB/Raspberry-Pi/1237052/layer2.jpg" class="lazyload" data-sizes="auto" data-> Finally, adding batteries and a Wi-Fi module, makes it ready for action. Well, provided everything is connected right and the software is there. width="440" data-src="/KB/Raspberry-Pi/1237052/pirex_assembled.jpg" class="lazyload" data-sizes="auto" data-> Although it is completely customary which GPIO pins to use for connecting different components to Raspberry Pi (the software discussed below can be configured for this), below is the pin out I've used while building the PiRex robot. Just as a reference. This is all about building the robot and connecting different components together. Having L293D driver chip's and HC-SR04 ultrasonic sensor's data sheets and following some tutorials, it should not be hard to figure out which pins go where and to get something working in a test application first. The software running on the PiRex bot's side is heavily based on the cam2web code base. In fact, about 95% of the code is taken from there. The reason for this is that cam2web provides most of the heavy infrastructure needed for this project - image acquisition from camera, embedded web server based on mongoose library, streaming images as MJPEG stream, infrastructure classes allowing to query/configure objects through REST API, etc. If we have a look at the core class diagram of the PiRex code, then we'll find that only two classes were added to the project (plus some glue code of course). This explains why cam2web was really the first big step towards building this robotics project. width="640" data-src="/KB/Raspberry-Pi/1237052/class_diagram.png" class="lazyload" data-sizes="auto" data-> Let's do a quick overview of what we've got from the cam2web project. The XWebServer class implements an embedded web server based on mongoose library API. It allows registering collection of objects implementing IWebRequestHandler interface, which provide some response to a particular request. For example, the XVideoSourceToWeb class accepts an arbitrary video source (a class implementing IVideoSource interface and producing new images via a IVideoSourceListener call back interface) and provides two request handlers - one, which streams images as MJPEG stream, and another, which provides images as single JPEG snapshots. XWebServer IWebRequestHandler XVideoSourceToWeb IVideoSource IVideoSourceListener The XEmbeddedContentHandler class allows serving static content from embedded resources. The cam2web project comes with a web2h tool, which allows converting certain types of files (web resources) into C header files. This way all required web content can be embedded directly into the final executable making it independent of any external files. XEmbeddedContentHandler Finally, the XObjectInformationRequestHandler and XObjectConfigurationRequestHandler classes provide either read-only access through REST API to objects implementing IObjectInformation interface, or read-write access to objects implementing IObjectConfiguration interface. For example, information about PiRex version and capabilities is provided through read-only interface, while camera'a settings can be changes and so exposed through IObjectConfiguration interface. XObjectInformationRequestHandler XObjectConfigurationRequestHandler IObjectInformation IObjectConfiguration To demonstrate the use of the above mentioned classes, here is a small code snippet, which configures a web server to stream Raspberry Pi's camera, allow changing its setting via REST API, query some information about the device and serve some static embedded content. This all came from the cam2web project and it is really easy in use. So why not to reuse? XWebServer server; XVideoSourceToWeb video2web; shared_ptr<XRaspiCamera> camera = XRaspiCamera::Create( ); // subscribe XVideoSourceToWeb object for video frame events camera- ) ); // allow changing camera's setting using REST shared_ptr<IObjectConfigurator> cameraConfig = make_shared<xraspicameraconfig>( camera ); server.AddHandler( make_shared<XObjectConfigurationRequestHandler>( "/camera/config", cameraConfig ) ); // allow querying some read only information through REST PropertyMap versionInfo; versionInfo.insert( PropertyMap::value_type( "product", "pirexbot" ) ); versionInfo.insert( PropertyMap::value_type( "version", "1.0.0" ) ); versionInfo.insert( PropertyMap::value_type( "platform", "RaspberryPi" ) ); server.AddHandler( make_shared<XObjectInformationRequestHandler>( "/version", make_shared<XObjectInformationMap>( versionInfo ) ) ); // add some static embedded content server.AddHandler( make_shared<XEmbeddedContentHandler>( "/", &web_index_html ) ). AddHandler( make_shared<XEmbeddedContentHandler>( "index.html", &web_index_html ) ). AddHandler( make_shared<XEmbeddedContentHandler>( "styles.css", &web_styles_css ) ); // ... // start the camera and the web server camera->Start( ); server.Start( ); </xraspicameraconfig> The code above is not a complete demonstration of the cam2web's features. For example, it does not show how to configure access rights - which request handlers can be accessed by everyone and which can be accessed only by known users. That can be found either from the original artucle describing cam2web project or diving into the provided source code. Controlling motors with a L293D chip is really easy and there are plenty of tutorials on this topic. Most of them are Python based, but it is really trivial to translate those to C code. To get motors moving, all we need to do is to set Enable pin to High and then set Input1 pin to High while Input2 pin to Low. To change direction of rotation it is required to swap input pins - set Inpun1 pin to Low while Input2 pin to Hight. And if we want to stop it all - just set Enable pin back to Low. To manipulate Raspberry Pi's pins from C application the Wiring Pi library can be used. It does come pre-installed with an official Raspbian image. Here is a quick sample how to get motors moving. #include <wiringPi.h> // configure pins pinMode( BOT_PIN_MOTOR_LEFT_INPUT1, OUTPUT ); pinMode( BOT_PIN_MOTOR_LEFT_INPUT2, OUTPUT ); pinMode( BOT_PIN_MOTOR_LEFT_ENABLE, OUTPUT ); // move motors "forward" digitalWrite( BOT_PIN_MOTOR_LEFT_INPUT1, HIGH ); digitalWrite( BOT_PIN_MOTOR_LEFT_INPUT2, LOW ); digitalWrite( BOT_PIN_MOTOR_LEFT_ENABLE, HIGH ); // move motors opposite direction digitalWrite( BOT_PIN_MOTOR_LEFT_INPUT1, LOW ); digitalWrite( BOT_PIN_MOTOR_LEFT_INPUT2, HIGH ); digitalWrite( BOT_PIN_MOTOR_LEFT_ENABLE, HIGH ); // stop motors digitalWrite( BOT_PIN_MOTOR_LEFT_INPUT1, LOW ); digitalWrite( BOT_PIN_MOTOR_LEFT_INPUT2, LOW ); digitalWrite( BOT_PIN_MOTOR_LEFT_ENABLE, LOW ); The code above allows controlling direction of motors' rotation, but not the speed. To get speed control, it is required to connect Enable pin to a PWM enabled pin on Raspberry Pi. The problem is that Pi has only one hardware PWM and so controlling speed of both left and right motors cannot be done with hardware support. As an alternative solution a software PWM can be used, which can be enabled on any of the Raspberry Pi's GPIO pins. The code below demonstrates the speed control based on software PWM. // configure pins pinMode( BOT_PIN_MOTOR_LEFT_INPUT1, OUTPUT ); pinMode( BOT_PIN_MOTOR_LEFT_INPUT2, OUTPUT ); softPwmCreate( BOT_PIN_MOTOR_LEFT_ENABLE, 0, 100 ); // rotate motor at half the speed digitalWrite( BOT_PIN_MOTOR_LEFT_INPUT1, HIGH ); digitalWrite( BOT_PIN_MOTOR_LEFT_INPUT2, LOW ); softPwmWrite( BOT_PIN_MOTOR_LEFT_ENABLE, 50 ); // full speed softPwmWrite( BOT_PIN_MOTOR_LEFT_ENABLE, 100 ); // stop the motor softPwmWrite( BOT_PIN_MOTOR_LEFT_ENABLE, 0 ); Although software PWM does allow controlling speed of motors, it is not as efficient as hardware PWM. The Wiring Pi library creates a background thread for each software PWM configured, which does frequent updates to the state of selected GPIO pin. As a result it increases CPU load, which in turn discharges battery quicker. However, software PWM not only affects system performance, but also can be affected by it. If CPU load gets high due to handling other computations, the software PWM's thread may not get a chance to update GPIO state at the time intervals required for smooth speed control. Because of the these issues, motors' speed control is disabled by default in PiRex configuration. Distance measurements with HC-SR04 ultrasonic sensor is a very easy task to do as well. Being an extremely popular sensor, it is used a lot in many hobby projects and so finding tutorial about it is not hard. The idea of the sensor is quite simple. It emits an ultrasound wave, which gets reflected from an obstacle and comes back to the sensor. And so it is simply required to measure the time taken after emitting the sound wave and detecting its return. Since speed of sound is known, calculating distance to an obstacle becomes trivial. HC-SR04 does not emit sound waves constantly. Instead, it needs to be told when to emit one and then wait till the sensor gets reflection back. Two GPIO pins are used for interaction with the sensors. The Trigger pin is used to tell sensor when to send a sound wave - it must be set to High for a short period of time and then set back to Low. The Echo pin is then used to detect when sound wave was sent and when it came back. After the measurement was triggered, the Echo pin goes High on sending the wave and gets back to Low on its return. Putting this all into the code may looks something like this: uint32_t start, stop; // time in microseconds // trigger measurement round digitalWrite( BOT_PIN_ULTRASONIC_TRIGGER, HIGH ); delayMicroseconds( 10 ); digitalWrite( BOT_PIN_ULTRASONIC_TRIGGER, LOW ); // wait for the echo wave start start = micros( ); while ( digitalRead( BOT_PIN_ULTRASONIC_ECHO ) == LOW ) { start = micros( ); } // wait for the echo wave stop stop = micros( ); while ( digitalRead( BOT_PIN_ULTRASONIC_ECHO ) == HIGH ) { stop = micros( ); } // calculate the distance to an obstacle (cm) float lastDistance = (float) ( stop - start ) / 58.2f; The above example code represents slightly simplified version, but gives the idea. To improve the code, it is required to handle possible timeouts, when an echo wave did not start/stop at expected time interval. Although the reference GPIO layout was provided above (which Raspberry Pi’s pins connected to what), it does not have to be that way for using PiRex software. As a minimum requirement, it is expected the robot to have camera and the L293D based motor driver. However, the way it is all connected does not really matter. It can be configured instead. Same about the ultrasonic sensor – it is an optional component and so may not be attached at all. In order to customize the build, there is the BotConfig.h header file. It does contain number of #define’s allowing to specify which Raspberry Pi’s pins are used for which purpose. Simply change that to reflect your setup and you are ready to go. BotConfig.h #define’s Building the PiRex code is as easy as running make command. The only thing which must be kept in mind is that release build embeds all web resources directly into the executable, so that default web UI could be always provided without relying on any extra files. This means that the web2h tool must be build first - the tool is used to translate some common web files into C structures defined in header files. make web2h Running bellow commands from the project’s root folder, will produce the required executables in build/release/bin. pushd . cd src/tools/web2h/ make popd pushd . cd src/app/ make popd Note: libjpeg development library must be installed for PiRex build to succeed (which may not be installed by default): sudo apt-get install libjpeg-dev Once the build completes, the PiRex software is ready to run. This means the robot is ready for action, provided the hardware part is also done and the configuration reflects the actual GPIO pins' connections. Note: the are number of command line options, which can be used to change default camera resolution, web port to listen on, authentication settings, etc. All of those were inherited from the cam2web project. Just run the application with the -? key to see the list of available configuration options. As it was already mentioned, the PiRex application comes with a built-in web UI. This means that once application is running, all you need to start controlling your robot is to type IP address:port into a web browser of your choice and get connected to it. width="640" data-src="/KB/Raspberry-Pi/1237052/pirex_web.jpg" class="lazyload" data-sizes="auto" data-> The default view simply shows current view from the robot's camera. However, the "Control" tab allows controlling the robot's movement and getting distance measurements, while the "Camera" tab allows changing different camera's settings. The GitHub repository provides the source code of the default web UI, so if anything needs changing - it is all there. Just don't forget to rebuild the application. Another approach would be to get all required web content into a separate folder and then tell PiRex application to serve static web content from there (using the -web:folder_name option). This would make it quicker to debug the web UI part before embedding final content into the executable. Note: building in debug mode automatically populates the folder with web content and application is serving it from there. Although the PiRex robot can be controlled directly from a web browser, which requires no extra software on the client side, there are cases when a dedicated application may fit better the task. For example, I found that manipulating robot by clicking UI buttons does not give the best control and as a result does not allow performing some of the tricks easily. Instead, using a game pad device and controlling left/right motors with individual axes gives much better control of the robot, allowing to switch faster between different movement patterns. Another example would be to use some image processing and/or computer vision algorithms on the video coming from robot’s camera. A dedicated client application may fit better many of such task, while a browser environment can get much more complicated (if possible at all) implementing them. width="640" data-src="/KB/Raspberry-Pi/1237052/pirex_client.jpg" class="lazyload" data-sizes="auto" data-> To provide extra flexibility in controlling the PiRex robot, a .NET client application is provided as well, which allows viewing robot’s camera and manipulate the robot by means of exposed REST API. To demonstrate alternative way of control, it supports game pad devices, so that robot’s manipulations become much more agile. Combining the .NET client with any of the available computer vision SDKs, may turn the robot into a development platform for many interesting applications. It can be used either for some fun games aimed for finding objects hidden in real world environment, or for some inspections tasks where smaller robots fit better the cluttered environment with limited amount of space to move around. As the above described application suggests, the PiRex bot provides API for interfacing with other applications, so that a native client could be developed and provide more advanced robot control or add extra features, like computer vision, for example. The first thing is to get video stream out of the robot, which is provided in the form of MJPEG stream. It does not provide the best compression - just a stream of individual JPEGs. However, it is very simple to implement and so supported by great variety of applications. The URL format to access MJPEG stream is: In the case an individual image is required, the next URL provides the latest camera snapshot: All the other URLs provide either some information about a robot (version, state, configuration), which is provided in JSON format when performing HTTP GET request, or can be used to control the robot - HTTP PUT request with JSON formatted command. To get information about version of the PiRex bot's software, the URL can be used, which provides information in the format below: { "status":"OK", "config": { "platform":"RaspberryPi", "product":"pirexbot", "version":"1.0.0" } } To find if PiRex bot is equipped with distance measurement sensor or allows speed control of motors, the URL is used. It also reports bot's title, which can be specified as one of the supported command line options. { "status":"OK", "config": { "device":"PiRex Bot", "providesDistance":"true", "providesSpeedControl":"false", "title":"My Home Robot" } } For querying distance measurements performed by PiRex robot, the URL is used. It provides as the most recent measurement in centimetres, as the median value taken from the last 5 measurements. { "status":"OK", "config": { "lastDistance":"128.95", "medianDistance":"127.25" } } For motors control, the URL is used. If GET request is sent, then the reply simply contains current state of the motors. This is not of much use though, since most of the time motors are stationary unless told to move. { "status":"OK", "config": { "leftPower":"0", "rightPower":"0" } } Sending a PUT request, however, is what's needed for telling robot to move. This is done with a simple JSON string, which tells power of both motors in the [-100, 100] range. In the case speed control is not enabled, there are only three possible values: 100 - rotate forward, 0 - don't move, -100 - rotate backward (although the robot will accept intermediate values as well, but threshold them). In the case if speed control is enabled, the speed value can be anything from the mentioned range. For example, the command below makes robot to rotate clockwise (rotate right). { "leftPower":"100", "rightPower":"-100" } Retrieving current configuration of PiRex robot's camera can be done using GET request sent to the URL, which lists current values of all available properties: { "status":"OK", "config": { "awb":"Auto", "brightness":"63", "contrast":"41", "effect":"None", "expmeteringmode":"Average", "expmode":"Night", "hflip":"1", "saturation":"16", "sharpness":"100", "vflip":"1", "videostabilisation":"0" } } Again, for changing any of the properties, a POST request must be sent to the same URL, providing one or more configuration values to set. For example, below is the command for changing both brightness and contrast: { "brightness":"50", "contrast":"15" } To get some of the information about the robot's camera, like its current resolution, the URL is available. { "status":"OK", "config": { "device":"RaspberryPi Camera", "height":"480", "title":"Front Camera", "width":"640" } } Finally, it is possible to query description of all supported camera's configuration properties by using the URL. This API is inherited from the cam2web project, where it does make sense, since that projects supports number of platforms and camera APIs. However, for PiRex it is of little use really - only one camera type is supported for now. It is time to wrap it up. Looking back at what was done to get the PiRex going, I would say it was really interesting experience as from the software development point of view, as from the hardware assembly. It was fun building it all, starting from soldering individual small components, to getting it all together and making sure it really does work. Yes, it was rebuilt couple of times - to replace a burned motor driver, to fit new more powerful motors, to find loose connection, etc. But at the end of the day it was nice seeing it progressing and improving. Was the target goal achieved? Sure, it was. The robot was built within the reasonable budget out of conventional electronic components these days. Since it is all built using smaller individual components rather than specialized robotics controller having all in one, it is much easier to replace/upgrade things. Which works well in repairing things as well – if motor driver got burned, we just need to replace a small chip which costs little, instead of replacing the entire robotics controller. As for the developed software it worked quite good as well. The PiRex robot can be controlled either from a web browser UI or from a dedicated application by calling the exposed REST API. A reference .NET client application is provided to demonstrate how to interface with the robot and how to implement a more agile control with the help of game pad device. Are there any things which could have been done different? If budget allows, a more advanced motor driver could be used, like ThunderBorg, for example, which provides speed control out of the box. Or, an alternative solution could be adding Arduino Nano, which brings enough hardware PWM pins to implement speed control with the L293D motor driver. This option sounds actually more interesting, since an Arduino board brings not only extra digital IO pins, but analog input pins as well, which can be of great use interfacing with different sensors. Anyway, the PiRex software in its current shape is really easy to reuse and extend. The provided embedded server and the rest of infrastructure allows plugging new REST handlers easily, which then interact with additional hardware components, if needed. What could be next? Well, once a robot is built and functions as expected, it could be used as a platform for many different projects. Especially when combining it all with some image processing and computer vision applications. Below is a quick demo of one such projects – hunting glyphs with a PiRex robot. A set of square binary glyphs is hidden in some environment and the target it to find them all by controlling the robot remotely. I must say it was a great fun playing it with kids! Well, I am sure many more great ideas can be implemented. Just be creative and keep going. Have.
https://www.codeproject.com/Articles/1237052/PiRex-remote-controlled-Raspberry-Pi-based-robot
CC-MAIN-2022-27
refinedweb
4,814
51.07
Summary I came across another generic puzzle and hope that someone has some insights. Suppose you have a class with a method f(): public class HasF { public HasF f() { System.out.println("HasF::f()"); return this; } } Here's a class that uses HasF as a bound for its generic parameter T. It stores an object of type T, and since the type parameter erases to its first bound, the methods of HasF are available: class Manipulator4<T extends HasF> { private T obj; public Manipulator4(T x) { obj = x; } public T manipulate() { obj.f(); } } The problem is that, in theory, covariant return types allow a return value to be the specified type or something derived from it. So it would seem that manipulate() would be able to return a HasF or something derived from it, which is exactly what T is bounded to be. So it would seem that the definition of manipulate() is OK, but the compiler gives an error: incompatible types, found : HasF, required: T. This is further confusing because T erases to HasF. Have an opinion? Readers have already posted 17 comments about this weblog entry. Why not add yours? If you'd like to be notified whenever Bruce Eckel adds a new entry to his weblog, subscribe to his RSS feed.
http://www.artima.com/weblogs/viewpost.jsp?thread=135896
CC-MAIN-2016-36
refinedweb
214
62.58
Scroll down to the script below, click on any sentence (including terminal blocks!) to jump to that spot in the video!Cool, got it! Course: Question and Answer Day: March 27th, 2013 Tutorial From Gerard Araujo: What is a typical/ideal bundle and firewall structure for symfony 2 for a project with the following basic requirements: - frontend [ public ] - frontend [ for logged in ] - backend [ for admin ] ... and a few entities that are owned by users like books, media, category... 1. assuming i use fosuserbundle, should i have at least 2 bundles ( 1 for fos extension ) ? more than 2? or only 1? what advantage/disadvantage to i get with each option? 2. is one firewall sufficient? what if i need different login routes? - how many dinosaurs does it take to replace a lightbulb? Hi Gerard! Uh oh, a security question! ... ryan runs away... Actually, this should be pretty painless. The security component in Symfony2 sometimes suffers from being so flexible that it’s not clear how to configure it. Let’s try to clarify a bit. This has nothing to do with security, but is a common question: how many bundles should I have and how do I know when I need to create a new bundle? In this case, Gerard is using FOSUserBundle and is wondering how to organize the bundles in his project. In your project, you will need a bundle for “User” functionality like your User entity, templates that override FOSUserBundle templates, etc etc. As Gerard is eluding to, when you want to override pieces of a vendor bundle, there are typically two strategies: 1) Placing files in the app directory in a specific organization to override some files from a vendor bundle () In the second strategy, you would create a UserBundle (or AcmeUserBundle depending on your “vendor” namespace), set its parent to FOSUserBundle, then begin overriding things. But let’s step back for a second. On a philosophical level, how many bundles should our project have? 1? 5? 50? The answer - like with anything - is up to you. However, don’t fool yourself by thinking that you can separate your features into totally standalone, decoupled bundles. In reality, your bundles will be totally coupled to each other and often times it won’t be clear exactly which bundle some piece of functionality should live in. And that’s ok! We’re building one application with one codebase: not an open-source library. The point is this: don’t create new bundles each time you have a new idea. Try to keep your total number of bundles low, and create a new bundle only wen you feel that things are getting crowded. In our example, I would create a UserBundle in my project, because I personally really like the “bundle inheritance” strategy for overriding parts of a vendor bundle. And because I did this, I would put all my user stuff in here (I wouldn’t create yet another bundle for user stuff that doesn’t relate to FOSUserBundle). Beyond that, it’s up to you. You might choose to create only one other bundle and put everything into it or create several other bundles. Just don’t go overboard.... trust me! One firewall is enough. I can say this almost regardless of what your project looks like. We talk a lot about firewalls and organization in Starting in Symfony2 Episode 2 and while there are good use-cases for multiple firewalls, they’re not very common. Legitimate reasons include: 1) You only use security for one part of your site, that part of your site lives under a specific URL pattern (e.g. /admin), and you’re very very worried about the small performance hit that loading the security system will cause on every page outside of this section. 2) You have an API that authenticates in a completely different way than your frontend, user data is loaded from a different source, and the API is also only accessible under a very specific URL pattern (e.g. /api). Having multiple firewalls can cause a lot of extra work and confusion. If you have a “frontend” and an “admin” section, my advice is to have only one firewall, load users all from the same source (e.g. from the same database table), then control access to different users and areas of your sites via roles and access controls. This will make you much happier :).
https://symfonycasts.com/screencast/question-answer-day/symfony2-security-firewalls-dinos
CC-MAIN-2019-22
refinedweb
735
63.9
Saturday, July 30, 2016¶ I finished working on The Lino Polls tutorial and then wrote to Grigorij: Thanks once more for your patience. The biggest problem was maybe that Django reorganized their beginner tutorial, you must now read the first two chapters. But there were quite some other changes, too, so please refresh your browser and walk through that tutorial once more from the beginning. Yes, I imagine that I am asking much from you. The problem with writing documentation for beginners is that you need a beginner for “testing” whether it works, and every human can be a beginner only once because when he reads some document a second time (after a change), then he’s no longer a real beginner… Let’s hope that many more beginners are coming after you :-) Defining the detail layout of a table¶ I worked on #1076 (Wenn man Aktivität via Statusbericht öffnet, hat man kein komplettes Detail). Here is how to reproduce this problem: Make sure you have yesterday’s version of the The Lino core, The Lino Extensions Library, Lino Così and Lino Voga repositories. Start a development server: $ cd voga/lino_voga/projects/roger $ python manage.py initdb_demo $ runserver Log in as robin. Click on “001 Greece 2014” in the Status Report. The detail window has only three tabs (not four), and in the Enrolments tab there are (among others) two columns “Start date” and “End date” which should not be there. You can see the correct detail window when you use the main menuand double-click on the “Greece 2014” row. The solution was to implement a custom get_detail_action for lino_xl.lib.courses.models.Course: def get_detail_action(self, ar): if self.line_id: area = self.line.course_area if area: table = rt.models.resolve(area.courses_table) return table.detail_action return super(Course, self).get_detail_action(ar)
http://luc.lino-framework.org/blog/2016/0730.html
CC-MAIN-2018-39
refinedweb
303
63.29
Name | Synopsis | Description | Return Values | Errors | Usage | Attributes | See Also #include <stdlib.h> int mkstemp(char *template); int mkstemps(char *template, int slen); char *mkdtemp. The mkdtemp() function makes the same replacement to the template as in mktemp(3C) and creates the template directory using mkdir(2), passing a mode argument of 0700. Upon successful completion, mkstemp() returns an open file descriptor. Otherwise -1 is returned if no suitable file could be created. The mkstemp(), mkstemps(), and mkdtemp() functions can set errno to the same values as lstat(2). The mkstemp() and mkstemps() functions can set errno to the same values as open(2). The mkdtemp() function can set errno to the same values as mkdir(2). It is possible to run out of letters. The mkstemp() function does not check to determine whether the file name part of template exceeds the maximum allowable file name length. The tmpfile(3C) function is preferred over this function. The mkstemp() function is frequently used to create a temporary file that will be removed by the application before the application terminates. The mkstemp() function has a transitional interface for 64-bit file offsets. See lf64(5). See attributes(5) for descriptions of the following attributes: The mkstemp() function is Standard. The mkstemps() and mkdtemp() functions are Stable. getpid(2), lstat(2), mkdir(2), open(2), tmpfile(3C), mktemp(3C), attributes(5), lf64(5), standards(5) Name | Synopsis | Description | Return Values | Errors | Usage | Attributes | See Also
http://docs.oracle.com/cd/E19082-01/819-2243/6n4i0997s/index.html
CC-MAIN-2015-48
refinedweb
242
57.47
Your first example is fine but it may only be used in a declaration. The elements must be implicitly convertible to the element type. The size is determined from the number of elements given. byte[] foo = { 0x32, 0x00, 0x1E, 0x00 }; Alternatively you can also d this byte[] foo = new byte[4]; foo[0] = 0x32; foo[1] = 0x00; foo[2] = 0x1E; foo[3] = 0x00; as stated above that the syntax that you are trying to use can only be used in a declaration. so try like this. public byte[] SetSpeed; private void trackBar1_Scroll(object sender, EventArgs e) { if (trackBar1.Value == 0) { try { stop = true; UpdateSThread.Abort(); Thread.Sleep(350); } catch { } //note it will always create a new array SetSpeed; } }; } You cannot have a final method declared in an interface. Fields are always final but methods are always abstract (and never final). You cannot define an interface method that is to be implemented only by classes in the same package.* From section 9.3 of the Java Language Specification: Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields. and from section 9.4: A character in int А = new Main2().А; is not a UTF-8 character, and is not the same as the one used in the variable name in the Main2 class. Copy-paste the A from the inner class and use that. It will compile. The key that you should pass to this function is a PHP resource object, and not the string representation of the key itself. $pubkey = openssl_get_publickey(base64_decode($row['public_key'])); $success = openssl_public_encrypt($data, $encrypted, $pubkey); The correct way to do this in Cilk would be something like: void task1_task2_task3() { cilk_spawn task1(); cilk_spawn task2(); task3(); } void task4_task5_task6() { cilk_spawn task4(); cilk_spawn task5(); task6(); } void task7_task8_task9() { cilk_spawn task7(); cilk_spawn task8(); task8(); } int main() { cilk_spawn task1_task2_task3(); cilk_spawn task4_task5_task6(); task7_task8_task9(); cilk_sync; finalize_stuff(); return 0; } Remember that cilk_spawn is a suggestion to the scheduler that the code after the cilk_spawn can be stolen, not a requirement. When a cilk_spawn is executed, it pushes a notation on tail of the worker's deque that the continuation is available for stealing. Thieves always steal from the head of the How about this: User Model after_update :update_public_status! def update_public_status! required_fields_present = [ name, state, city, high_school, recruit_year, birthday, stat(:height), stat(:weight) ].all? if required_fields_present make_public! else make_private! end end def make_public! update_attribute :public, true update_attribute :removed_from_listing, false end def make_private! update_attribute :public, false update_attribute :removed_from_listing, true end Cou can combine them as following: public class GPSTracker extends Activity implements LocationListener { } and put all your code of both classes into this one. The onCreatOptionsMenu is only necessary if you're using a menu. The onCreate should be used because your GPSTracker class is an Activity. var Person = function (name, age) { this.name = name; this.age = age; } Person.prototype.scream = function () { // get function screamAge from container WhatToScream, // which is available in the instance of the object, // because it was defined in the prototype // and then call it with thisArg being current this, // which is pointing to current container, // * which at runtime is man this.WhatToScream.screamAge.call(this); } Person.prototype.WhatToScream = { screamAge: function () { alert('I AM ' + this.age + ' YEARS OLD!!!'); }, screamName: function () { alert('MY NAME IS ' + this.name + '!!!') } } var man = new Person('Berna', 21); man.scream(); If you want to keep WhatToScream as a function, you will need to cal From the Java Language Specification, section 8.4.3: If two or more (distinct) method modifiers appear in a method declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for MethodModifier. So they can appear in any order, but there is a recommended ordering. The order is: Annotation public protected private abstract static final synchronized native strictfp How can I call methodOne from methodTwo? You need to access the instance on which you want to call the method (you could as well get it from the prototype and apply on some arbitrary object but I guess that's not what you want). To make it known in the scope of the methodTwo, pass it as a parameter to the function: ClassTwo.prototype.methodTwo = function (one) { one.methodOne(); }; … var classOne = new ClassOne(); var classTwo = new ClassTwo(); classTwo.methodTwo(classOne); Would this fit your need ? (Using a CTE:. I wrote it partially in Notepad++ so I hope there aren't syntax error.) The CTE tASD (stands for tblAssetSubscriptionDetails) gathers only the rows that will be useful. EXISTS should normally be better than Count() > 0 since it doesn't actually need to count everything. WITH tASD(AssetMgmtId, IMEINumber, PhoneNo, SIMNo) AS ( SELECT AssetMgmtId, IMEINumber, PhoneNo, SIMNo FROM tblAssetSubscriptionDetails WHERE AssetMgmtId <> @Id AND ( IMEINumber = @IMEINumber OR PhoneNo = @PhoneNo OR SIMNo = @SIMNo ) ) SELECT @Message = ( CASE WHEN EXISTS (SELECT null FROM tASD WHER like so: HTML <div id = "one"></div><div id = "two"></div><div id = "three"></div> Javascript var bordRad = parseInt(document.getElementById("BD").value, 10); document.getElementById("one").style.borderRadius = bordRad + "px"; i may have misunderstood your question though, please clarify, and/or add some of your code. Yes, pA does not point to the char 'A' anymore, so the reference count is decremented. As it was the only reference to 'A', the reference count reaches zero and the char is deleted. It would be highly surprising and error-prone if you'd have to explicitly release the reference before reassignment. pA.reset(pB) should not compile, as reset can only take a raw pointer, not another shared_ptr. addVectors returns a pointer to a local array, when addVectors returns val becomes garbage data. you could pass in third parameter to addVectors, you need to make sure all vec have at least 3 elements though: void addVectors( double* vec1, double* vec2, double* vec) { for( int i = 0; i < 3; i++ ) vec[i] = vec1[i] + vec2[i]; } double A[3] = {1, 2, 3}; double B[3] = {4, 5, 6}; double C[3] = {}; // initialize all C elements to 0.0 addVectors(A,B,C); My Suggestion is use STL container like std::vector, std::list etc, or use st::array if C++11 is enabled. With STL container could archive your intention: std::vector<double> addVectors(const std::vector<double>& v1, const std::vector<double>& v2) { std:: You can just reassign a pre-initialized cv::Mat to new image data. Here are a few legal ways of assigning new image data to a cv::Mat that was already created. cv::Mat my_mat = cv::imread("some_image.jpg"); my_mat = cv::imread("another_image.jpg"); cv::Mat second_mat = cv::imread("one_more.jpg"); second_mat = my_mat.clone(); If you already have a string representation of the Guid, you can do this: Guid g = new Guid("11223344-5566-7788-99AA-BBCCDDEEFF00"); And if you want a brand new Guid then just do Guid g = Guid.NewGuid(); std::shared_ptr does not let you assign a plain pointer to it directly. When you think about, there are quite convincing reasons to disallow it implicitly happening. First of all, shared_ptr needs an (external, in general) reference counter to be allocated. Consider for example the following (hypothetical) code: std::shared_ptr<A> p1 = obj; std::shared_ptr<A> p2 = obj; What happens when the pointers fall out of scope? Each assignment creates its own reference counter, since there is no way p2 can know about the one created by p1. In effect, obj is deleted twice - UB. Preferred solution is to use library function std::make_shared. It offers a number of benefits over wrapping externally created object: counter is created in the same heap chunk as the object, hence the over current_user.pk has ObjectId type (just id, no info about collection). current_user has LocalProxy type. You can't save reference as ObjectId because there are no information about reference collection and mongo use for this BDRef. You can get DBRef object from mongoengine document with Document.to_dbref method. So mognoenginge check type to get DBRef explicitly or get it from document with to_dbref. For current_user you can call to_dbref to get DBRef object or _get_current_object() to get real User object. Your both expressions are incorrect, It should be: int x, *ra; ra = &x; // pointer variable assigning address of x & is ampersand is an address of operator (in unary syntax), using & you can assign address of variable x into pointer variable ra. Moreover as you question title suggests: Assigning int value to an address. ra is a pointer contains address of variable x so you can assigning an new value to x via ra *ra = 20; Here * before pointer variable (in unary syntax) is deference operator gives value at the address. Because you have also tagged question to c++ so I think you are confuse with reference variable declaration, that is: int x = 10; int &ra = x; // reference at time of declaration Accordingly in case of reference variable, if you wants to as While im not 100% sure what you're asking you can place return values of functions anywhere you like. function roots_widgets_init() { register_sidebar(array( 'name' => __('Footer', 'roots'), 'id' => 'sidebar-footer', 'before_widget' => '<section class="widget span4 %1$s %2$s"><div class="widget-inner">', 'after_widget' => '</div></section>' . get_after_section(), 'before_title' => '<h3>', 'after_title' => '</h3>', )); } Will append the return value of get_after_section to the current value of 'after_widget'. IMPORTANT: All JavaScript developers should know this. It will cause all kinds of weird bugs that is very hard to find. It is a common mistake of people who are new to JavaScript. I've made the same mistake before. A function inside a loop is NOT created for every iteration. It is the same one function object with the same closure scope. Thus, your cells will have the exact same onclick callback. My advice here is NEVER EVER create a function inside of loop. Instead, create and call a function that returns a callback function and assign it to onclick. for (var j = 0; j < 8; j++) { var cell = row.insertCell(j); cell.name = j; cell.onclick = createOnClick(cell); } function createOnClick(cell) { return function () { // do whatever you want to do with cell }); if you want a new GUID every time use Guid guid = Guid.NewGuid(); If you want a specific guid use (wrt your example) Guid guid = new Guid("914aaa44-4e11-e311-96f7-d8d3855b1531"); Is this what you're going for? exports.index = function(req, res){ var deck = require('./../deck'); // No .js required deck.drawCard(function(err, card) { if(err) { res.render('error'); return; } res.render('index', { title: 'Bits AH', card: card }); }); }; You're wrapping the res.render call inside the callback to the drawCard function because you can't return until after the function is completed. It's possible however to load those files when the module is initialized, and then you can convert your drawCard function to be synchronous and then you could use it like you have in your example. As far as I'm aware you can't. Here are valid dimension types: A dimension value defined in XML. A dimension is specified with a number followed by a unit of measure. For example: 10px, 2in, 5sp Valid units: dp, sp, pt, px, mm, in I would just put wrap_content directly in my xml layout or style since wrap_content is wrap_content whatever device/configuration you have. From the looks of it, you try to assign a std::pair<std::string const, std::string> to a std::string. This won't work. Did you mean to write this? t.get<1>() = i->first; First off, are you missing some code in your example? possibly a Starter initialisation in the App class? I get a traceback if I try to run: Traceback (most recent call last): File "test.py", line 165, in <module> main() File "test.py", line 160, in main app = App(root) File "test.py", line 10, in __init__ self.create_widgets() File "test.py", line 57, in create_widgets variable = self.Starter.menue, value = 55, command =self.determine_order AttributeError: App instance has no attribute 'Starter' When using loops like that you need to wrap it in an enclosure function ObservablePropertyList(nameCallbackCollection) { var propertyList = {}; for (var index in nameCallbackCollection) { (function(target){ var private_value = {}; propertyList["get_" + index] = function () { return private_value; } propertyList["set_" + index] = function (value) { // Set the value private_value = value; // Invoke the callback target(value); } })(nameCallbackCollection[index]); } return propertyList; } You want to call the EnableStatic method on the instance of the Win32_NetworkAdapterConfiguration WMI class for the network interface you want to configure. uint32 EnableStatic( [in] string IPAddress[], [in] string SubnetMask[] ); You can see above it takes two parameters. A string array of IP addresses and a string array of subnet masks. It will return an status code. 0 indicates success. Here is PowerShell example code: Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled=true" | ForEach-Object { $result = $_.EnableStatic(("192.168.1.10","10.0.0.10"),("255.255.255.0","255.0.0.0")) if ($result -ne 0) { # handle non-successful response code here. } }
http://www.w3hello.com/questions/Assigning-a-public-ip-to-an-ec2-in-cloudformation-
CC-MAIN-2018-17
refinedweb
2,157
56.25
In Continuation to my previous blog, in this Second part I am going to discuss and demonstrate how we technically developed this solution. The purpose of this blog is you can create an Adobe Interactive Form (AIF) at run time without Webdynpro Java, without logging into Portal and with out user intervention using SAP R/3 4.6c. As I discussed in my previous blog (Part-I) we have scenario to have a java service which runs at regular intervals of 5 minutes, picks the Quotations created in the last 5 minutes span in R/3, Generate AIF on the fly by merging the XDP template with the data from RFC and send it as mail attachment to customers automatically. This AIF (Offline) also contains a WebService to enable the customer submit the form back directly from the desk top without logging into portal h5. How to Implement this Solution We have implemented this Solution by dividing it into 5 Steps. > Creating XDP file > Connecting to SAP and getting data > Generating XML Data String at runtime. > Using PDFDocument API for Dynamic Generation of Adobe Interactive Form > Send the Generated AIF as mail Attachment using Mail API > Scheduling the Entire Project Using KM Scheduler Our Environment Netweaver Developer Studio: 7.0.15 Adobe Reader 9.0 Adobe Live Cycle Designer 8.0 SAP Enterprise Portal 7.0 SP15 with Adobe Document Services Configured h5. Creating XDP file We have designed the Adobe Interactive Form using Adobe Live Cycle Designer 8.0 and placed the resultant XDP file in a shared folder on the Portal Server. Every UI Element is bound to an attribute (The attribute name is very important, as we are going to use the same name while generating the XML Data). Since the entire process has to happen in the background, we are not going to include this as part of any webdynpro application. Connecting to SAP and getting data Since only the .par files can be exposed as KM Scheduler Tasks, we have chosen “Portal Application Project” in Netweaver Developer Studio, for our purpose. While implementing the AIF dynamic generation functionality (in run method) we need to fetch the data that should be populated in the XDP template from RFCs (R/3) and for this we are using JCO client middle layer. Hence we are creating this SAP Connectivity to enable the NWDS generate the proxy classes for us and we are using these proxy classes to pass input parameters, get output parameters and execute the RFC. Also ensure that SAPJCorfc.DLL and sapjco.jar should be present at c:\windows\system32 on Portal Server and we need to restart the server once after placing these files. Generating XML Data String at runtime To be able to Schedule KM Scheduler and enable it to call our Java Application (Portal Application), application should follow Repository Framework. Usually RF is used for extending or customizing the standard delivered KM functionality by SAP (like implementing Repository Filters, Customizing Resource Renderers, Collection Renderers in KM etc..). The same RF can also be used to schedule and call any Job developed as Java Application. Technically this means our class should implement the ISchedulerTask Interface. Within our Portal Application Project, we have to create a Repository Framework and choose “Scheduler Task Wizard”. In the Scheduler Task Wizard’s screen provide a Class name, Package and Eclipse project Name and click finish. NWDS Auto generates the skeleton for the implementation of the interface ISchedulerTask: * *In your java class (example.java) you will find the following template already created by NWDS. We have to write the entire code that is to be called by the KM scheduler in the run method package com.companyName.project; import java.util.Properties; import com.sapportals.wcm.WcmException; import com.sapportals.wcm.service.;</p><p>import com.sapportals.wcm.service.scheduler.;//Written in the Custom Method getExampleDetailRFC //Header data sb = new StringBuffer(0); for( I have many deviations of the same form template, and I want to eliminate the number of forms by using a more dynamic approach, but I’m faced with the client side validation of each form. any ideas? Can you eloborate your question? I am using the same method to generate a PDF file. It works perfectly fine when I am embedding values inside table cells or embedding images. There is an additional requirement however, that I need to change the background color of a cell depending on the value that is shown in that cell. I have looked all over the place, but can’t find a complete solution for my problem. I think you can embed a script in the XML source (setData method) using xfa:contentType=”application/x-formcalc” attribute, but haven’t been able to add a script successfully using this method. Any ideas?? Regards, Navneet Nair. From my under standing we cannot set color dynamically when the text is static. You can change the color of a cell depending on the value that is shown in the cell if the text is in non-editable field (Script type:- Java Script, Code to be written in Initialize method, this.fillColor=”255,102,0″;). If you want to know what values you need to give here for a specific color Steps: 1)Goto Border tab in right pane of Adobe Designer 2)Goto Background fill 3)Select style:-Solid 4)You can see the color icon highlighted 5)Click on that icon 6)Select what ever color you required. 7)When the color is assigned select the specific field 8)Goto XML Source of specific field. 9)You find the code of the color( 10)Copy the value of the color do write the code in the initialize method. 11)Now it is done. Hope your question got resolved. For adobe forums queries you can visit the site:
https://blogs.sap.com/2008/12/30/dynamic-generation-of-offline-adobe-interactive-forms-for-sap-46c-and-ep-70-without-user-interventionpart-ii/
CC-MAIN-2019-04
refinedweb
975
52.9
So, week two of doing TDD and I’m still absolutely loving it. I’ve also rediscovered two tools/libraries I had been using before but that make much more sense to me now that I iterate on tests more frequently. GoConvey GoConvey was one of the first tools I used to run tests in Go back when I learnt the language all these years ago. The project has two main parts: - A testing framework which is supposed to give your tests a slightly nicer structure using a DSL - A test runner that continuously watches your source files, runs the associated tests, and finally present the output to you in a web interface For my purposes, the second aspect is highly relevant. Whenever I now want to change something inside a package, I open a goconvey instance in there. It will start watching the files in that package for changes , run the relevant tests, and let me know if I’m done with my change or not. Let’s say, I’m working on a new helper for tpl inside the internal/world package. Then I change into the folder of that package and run goconvey: $ goconvey ... 2020/01/25 20:34:57 goconvey.go:105: Launching browser on 127.0.0.1:8080 2020/01/25 20:34:57 goconvey.go:178: Serving HTTP at: This will open a browser window and show me all the tests that have just been run: GoConvey also supports sending notifications after every testrun. This means, I don’t have to keep the browser open on a secondary display while coding on the primary one. Instead, I can just leave the browser somewhere in the background and have all my screen-estate for the tests and code to iterate on. This is especially handy while coding on my 13" laptop while at home or on the go. Sadly, notifications are disabled by default but can easily be enabled through the “bell” sign in GoConvey’s UI as shown below: dockertest Dockertest is a little library I had already written about last year: It allow you to easily start up a Docker container, for instance of the database system you’re using in your application, and access its metadata like exposed ports etc. This little library has made my integration tests so much more readable, it’s hard to describe :-) But as I said, I’ve already written about it before. If you want my 2c about it, go here. Go’s crypto package test keys The last one is just a little shout-out to Go’s awesome standard library: I recently also improved some JWT code but ran into the situation where I didn’t felt like checking in some previously valid tokens (as they had already expired) as test objects. What I did instead, was to create my own little RSA keypair using Go’s crypto/rsa package and generate tokens inside my test cases using that: import "crypto/rsa" import "crypto/rand" privateKey, _ := rsa.GenerateKey(rand.Reader) publicKey := privateKey.Public() These two lines of code prevented me from having to check in some pre-generated RSA keys which made the whole test suite much more pleasant to read. It also made testing the underlying code much more flexible because I could generate tokens with whatever properties I needed instead of having to rely on pre-generated ones.
https://zerokspot.com/weblog/2020/01/25/some-tdd-tools-for-go-developers/
CC-MAIN-2020-50
refinedweb
568
56.79
Testing is an essential aspect of any programming language. Testing for ASP.Net applications is possible with the help of Visual Studio.. In this tutorial, you will learn- Introduction to message "Guru99 – ASP.Net" displayed.. Let's look into more detail now and see how we can work on testing in ASP.Net. Creating a .NET Unit Testing Project Before we create a test project, we need to perform the below high-level steps. - Use our 'DemoApplication' used in the earlier sections. This will be our application which needs to be tested. - We will add a new class to the DemoApplication. This class will contain a string called 'Guru99 – ASP.Net.' This string will be tested in our testing project. - Finally, we will create a testing project. This is used to test the ASP.Net application. So let's follow the above high-level steps and see how to implement testing. Step 1) Ensure the DemoApplication is open in Visual Studio. Step 2) Let's now add a new class to the DemoApplication. This class will contain a string called 'Guru99 – ASP.Net.' This string will be tested in our testing project. Follow below step to add a new class. - In Visual Studio, right-click the 'DemoApplication' in the Solution Explorer. - Choose the option Add->Class from the context menu. Step 3) In this step, - Give a name 'Tutorial.cs' for the new class. - Click the 'Add' button to add the file to the DemoApplication. Now, a new class is added to file "DemoApplication." Step 4) Open the new Tutorial.cs file from "DemoApplication". Add the string "Guru99 – ASP.Net." To open the file, double-click on the Tutorial.cs file in the Solution Explorer. The file will have some default code already written. Do not bother about that code, just add the below line of code. namespace DemoApplication { public class Tutorial { public String Name; public Tutorial() { Name = "Guru99 - ASP.Net"; } } } Code Explanation:- - The Name variable is of type string. - Finally in, the constructor of the Tutorial class, assign the value of the Name variable. The value is assigned to "Guru99 – ASP.Net" Step 5) Now go to the demo.aspx file and add the lines of code to display the text "Guru99 – ASP.Net." <!DOCTYPE html> <html xmlns=""> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server”> <div> <% DemoApplication.Tutorial tp=new DemoApplication.Tutorial();%> <%=tp.Name%> </div> </form> </body> </html> Code Explanation:- - The first line create's an object of the class 'Tutorial'. This is the first step when working with classes and objects. The name given to the object is 'tp'. - Finally we call 'tutorial.cs' from demo.aspx file. It displays the value of the Name variable. When you run the above program in Visual Studio, you will get the following output. Output:- From the output, you see the message "Guru99 – ASP.Net" displayed. Step 6) Now let's add our test project to the Demo Application. This is done with the help of Visual Studio. - Right-click the Solution – DemoApplication. - In the context menu, choose the option 'New Project'. Step 7) The step involves the addition of the Unit Test project to the demo application. - Click on item type as 'Test' from the left-hand panel. - Choose the item as 'Unit Test Project' from the list, which appears in the center part of the dialog box. - Give a name for the test project. In our case, the name given is 'DemoTest'. - Finally, click the 'OK' button. You will eventually see the DemoTest project added to the solution explorer. With this, you can also see other files like UnitTest1.cs, properties, etc. are generated by default. Running the Test Project The test project created in the earlier section is used to test our ASP.Net application. In the following steps, we are going to see how to run the Test project. - The first step would be to add a reference to the ASP.Net project. This step is carried out so that the test project has access to the ASP.Net project. - Then we will write our test code. - Finally, we will run the test using Visual Studio. Step 1) To test our Demo Application, first test project needs to reference the Demo Application. Add a reference to the Demo.aspx solution. - Right-click the Demo Test project - From the menu choose the option of Add->Reference. Step 2) The next step is to add a reference to the DemoApplication. - Select the Projects option from the left-hand side of the dialog box - Click on the check box next to DemoApplication - Click on the 'OK' button. This will allow a demotest project to test our DemoApplication. Step 3) Now it's time to add the test code to our test project. - For this first double-click on the UnitTest1 (UnitTest1 file is automatically added by Visual Studio when the Test project is created) file in the Solution Explorer. - This is the file which will be run to test the ASP.Net project. You will see the below code added by Visual Studio in the UnitTest1.cs file. This is the basic code needed for the test project to run. Step 4) The next step is to add the code which is used to test the string "Guru99 – ASP.Net." using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using DemoApplication; namespace DemoTest { [TestClass] public class UnitTestl { [TestMethod] public void TestMethodl() { Tutorial tp = new Tutorial(); Assert.AreEqual(tp.Name,"Guru99 - ASP.Net"); } } } - Create a new object called 'tp' of the type Tutorial - The Assert.AreEqual method is used in .Net to test if a value is equal to something. So in our case, we are comparing the values of tp.Name to Guru99 – ASP.Net. Step 5) Now let's run our test project. For this, we need to go to the menu option Test->Run->All Tests Output:- A test Explorer window will appear in Visual Studio. This will show the above result and display that a successful test was run in Visual Studio. Summary - ASP.Net can add Unit Testing for applications. - To test an application, you need to add a Unit Test project to the ASP.Net solution. - All tests can be made to run in Visual Studio. A test explorer will show the results of all of the tests.
http://www.test3.guru99.com/asp-net-unit-testing-project.html
CC-MAIN-2020-10
refinedweb
1,056
69.28
Single Round Match 713 Editorials We now have some of the SRM 713 Editorials published. We are awaiting or reviewing the submissions for some of them. If you would like to contribute an editorial for those problems you may do so by submitting to their respective challenge. Thanks to stni, pakhandi, marcose18 , GoogleHireMe for contributing to the SRM 713 editorials. Single Round Match 713 Round 1 – Division II, Level One SymmetryDetection by pakhandi The problem can be solved by traversing the matrix and checking for symmetry in a greedy / ad-hoc way. Let us first solve the problem for the vertical-symmetry. We want to check if, for every cell [i][j], if it is equal to [i][cols – j – 1]. In this case we don’t need to visit every cell. We only need to check this condition for cells in all the rows but only half the columns. The proof of this optimization is very trivial and is left as an exercise for the reader. For the horizontal-symmetry, we can use the same method for all the columns but half the rows, comparing [i][j] with [rows – i – 1][j]. The method is very similar to what is used for checking palindrome. Please check the implementation below for details. class SymmetryDetection { public: string detect(vector board) { bool h = 1, v = 1; int rows = board.size(); int cols = board[0].size(); for(int i = 0; i < rows; i++) { for(int j = 0; j <= cols / 2; j++) { if(board[i][j] != board[i][cols - j - 1]) { v = 0; } } } for(int i = 0; i <= rows / 2; i++) { for(int j = 0; j < cols; j++) { if(board[i][j] != board[rows - i - 1][j]) { h = 0; } } } if(h && v) { return "Both"; } else if(h) { return "Horizontally symmetric"; } else if(v) { return "Vertically symmetric"; } else { return "Neither"; } } }; Single Round Match 713 Round 1 – Division II, Level Two PowerEquationEasy by marcose18 In this question we will iterate through all the values & it’s powers which are less than n. Now we will calculate answer for a number i & it’s powers in one go . Now for some power of i, let’s assume i ^ x we have to calculate all such values where (i ^ x) ^ c = (i ^ y) ^ d such that c, d & i ^ y <= n. Now clearly x, y <= maxpow where i ^ maxpow <= n while i ^ (maxpow + 1) > n. Also (i ^ x) ^ c = (i ^ y) ^ d implies x * c = y * d. In short (x / y) = (d / c). So for fixed values of x, y we have to find c & d such that it satisfies above equation while it is also <= n. So to find such c & d, reduce x & y to it’s lowest form by dividing both x & y by gcd(x, y). Now it’s easy to see that total possible values = n / max(tempx, tempy) where tempx & tempy are x / gcd & y / gcd respectively. Do the above for all values of i and add it to answer. One final thing to note here is if i > sqrt(n) then it contains no power that is less than n i.e i ^ x = i ^ y only for x = y = 1. So each of them will contribute n to the final answer and thus we will loop only upto sqrt(n) instead of n. Below is the code of above explanation. Here HashSet is used to keep track of visited numbers and their powers. import java.util.*; import java.util.regex.*; import java.text.*; import java.math.*; public class PowerEquationEasy { // Calculating gcd of two numbers. static int gcd(int a, int b) { if (a < b) { int temp = a; a = b; b = temp; } if (b == 0) return a; return gcd(b, a % b); } public int count(int n) { long ans = n * 1L * n; long mod = (long) 1E9 + 7; ans %= mod; HashSet set = new HashSet<>(); // Iterate through all values but not those which are stored in the hashset which are nothing but powers of earlier values and we have calculated answers for them before. for (int i = 2; i * i <= n; i++) { if (set.contains(i)) continue; int maxpow = 0; int temp = i; while (temp <= n) { ++maxpow; set.add(temp); temp *= i; } // Find the answer for all x & y such that (i ^ x) ^ c = (i ^ y) ^ d. for (int x = 1; x <= maxpow; x++) for (int y = 1; y <= maxpow; y++) { int g = gcd(x, y); int tempx = x / g, tempy = y / g; ans += n / Math.max(tempx, tempy); while (ans >= mod) ans -= mod; } } // All numbers greater than sqrt(n) will have no power that is less than n and for each of them there will be ‘n’ identities. ans += (n - set.size() - 1) * 1L * n; ans %= mod; return (int) ans; } } Single Round Match 713 Round 1 – Division II, Level Three DFSCountEasy by GoogleHireMe In this problem, you have to calculate number of different paths to traverse the graph using depth first search. First of all, let’s try to set the possible upper bound for the answer. There are exactly N! (n-factorial) permutations of numbers from 1 to N. All of those sequences will be valid when we have a complete graph. So, the maximal possible answer can reach 13! = 6227020800, and this means that a brute force (trying all the possible paths) wouldn’t fit into time bounds. To solve this problem, we can use dynamic programming. In every dynamic programming problem you have to detect four things: - a) define a state - b) find a way to split the problem into subproblems - c) define the base state: the subproblem for which you know the solution immediately, without splitting it into subproblems. - d) find a way to combine the subproblems’ solutions to get the solution of the main problem Let’s tackle this step by step: a) Let’s define our problem’s state as a pair of <start_node, available_nodes>, where start_node is the node from which we start building the path, and available_nodes – set of nodes which are not yet visited. Then, to find the solution to the initial problem, we would have to sum up all solutions of subproblems with all possible start nodes when all nodes as available. Let’s consider the following example: node 1 is not available (since it was visited before) and start_node is 2; State: start_node=2, available_nodes={3, 4, 5, 6, 7, 8, 9} b) To split the problem into subproblems, we can just try to extend our existing path and make a one DFS call to one of the available In the example, we can go to the next possible subproblems (2 is no longer available, start_node highlighted with blue color): c) The base state can be the state with only one available node – it means that there is nowhere else to go, and the answer is 1 (only that node, and that’s the end). d) Now, we have to find a way to combine the solutions to the subproblems. And this is the place where things get really interesting: The first thing we should notice is that once we decided which child to go next, all other children that are connected (directly or via available nodes) will not be available once the dfs() will return, since they will be marked as used in one of the dfs()’s subcalls of the call on that child. For instance, in the example above, when we call dfs for node 3 from the node 2, it will mark nodes 4, 5 and 6 as used. Thus, after the end of the call, we wouldn’t be able to call dfs for the node 6 from the node 2 anymore. Let’s call the subset of the “reachable” nodes as the component. In the example above, once we consider node 2 as start_node and node 1 as unavailable, we will have to components: consisting of nodes {3, 4, 5, 6} and {7, 8, 9}. Since you can pick only one node per component to move to, the number of dfs() calls from the start_node equals to the number of components in that state. Since the components are independent from each other, the result for the given state will be the multiplication of number of paths for all components separately. Also, because of the independance of those components (you cannot reach one from another), we can do those above mentioned dfs() calls in any order, that means that we have to multiply the result by K! (k-factorial) where K is the number of components for the current state. One more thing we still have to consider – what if one component contains more than one neighbour of the start_node. Since we can “enter” the component only once (after that all nodes of the component will be marked as used), the number of different paths for the component will be the sum of those subproblems with different children as start_node. A few notes on the implementation: the recursive solution looks nice, however, to avoid solving the same subproblem multiple times, it’s important to implement this recursion with memoization of the answers for every state previously calculated. We can achieve this with map data structure. In my solution I use breadth first search to find the components. Also, I use the bitmask to represent available nodes instead of the set, since the number of the nodes is small, and bit operations are generally “cheaper” (in terms of performance) than the operations on the set. Here, 1 on the ith position of the binary representation of the mask variable means that the ith node is in available_nodes set. Complexity: Let n be equal to the number of nodes. In the worst case, for every state (2^n * n) we will perform breadth first search ( O(n*n)) for every neighbor (n). Thus O(2^n * n * n * n^2) = O( 2^n * n^4 ) To sum up, the solution will look like follows: #include <string> #include <vector> #include <map> #include <queue> using namespace std; class DFSCountEasy { int n; vector<string> G; map<pair<int, int>, long long> cache; long long f(int mask, int v) { // Remove current node from the available nodes mask = mask & (~(1 << v)); if (cache.count({mask, v})) { // The solution for this subproblem was calculated before return cache[{mask, v}]; } map<int, long long> components; for (int i = 0; i < n; i++) { if (G[v][i] == 'Y' && (mask & (1 << i))) { // BFS for child i queue<int> q; q.push(i); // Bitmask for the set of nodes included in the corresponding component int submask = 1 << i; while (!q.empty()) { int u = q.front(); q.pop(); for (int j = 0; j < n; j++) if (mask & (1 << j)) { if (G[u][j] == 'Y' && !(submask & (1 << j))) { submask |= 1 << j; q.push(j); } } } components[submask] += f(submask, i); } } long long res = 1; for (auto x : components) res *= x.second; for (int i = 0; i < components.size(); i++) res *= i + 1; return cache[{mask, v}] = res; } public: long long count(vector<string> _G) { G = _G; n = G.size(); long long res = 0; for (int i = 0; i < n; i++) res += f((1 << n) - 1, i); return res; } }; Single Round Match 713 Round 1 – Division I, Level One PowerEquation by stni If a=c, b=d, we have n*n identities. Here, 1^1=1^2=1^3=…=1^n,—-(n-1) 1^2=1^1=1^3=…=1^n,—-(n-1) … 1^n=1^1=1^2=…=1^(n-1) —-(n-1) For a=1 and b=1, we need to add another n*n-1. So we already have n*(2*n-1) identities obviously. For a != c: Without loss of generality, we say ac. For all integers not power of other integers p, let a=p^i, c=p^j number of c we can choose from equals to number of powers of least common multiple(LCM) of a and c. j/gcd(i,j) is the min distance between powers of LCM, n/(j/gcd(i,j)) is the number of such identities in [1..n] multiply 2 for symmetry of a-c, b-d Complexity is O(n) #include<set> using namespace std; typedef long long ll; const ll mod=1e9+7; ll gcd(ll a,ll b){ return a?gcd(b%a,a):b; } class PowerEquation{ public: int count(int n0){ ll n=n0; set<ll>se; //all power bases ll ans=n*(n*2-1)%mod; for(ll p=2;p*p<=n;p++){ if(se.count(p)) continue; //we already calculated p's base ll t=p; ll k=0;//number of powers of t while(t<=n){ se.insert(t); t*=p; k++; } for(ll i=1;i<=k;i++){ for(ll j=i+1;j<=k;j++){ ans+=n/(j/gcd(i,j))*2; ans%=mod; } } } return (int)ans; } }; Single Round Match 713 Round 1 – Division I, Level Two DFSCount by stni We have n nodes, each has n potential positions. Complexity is O(n^2) #include<vector> #include<array> #include<string> using namespace std; typedef long long ll; vector<string>G; vector<array<pair<ll,ll>, 15>>mem; class DFSCountEasy{ public: pair<ll,ll> dfs(ll visited, ll last){ if(mem[visited][last].second)return mem[visited][last]; pair<ll,ll> r(0,0); for(int i=0;i<G.size();i++){ if((last!=G.size()&&G[last][i]=='N')||(visited&(1ll<<i)))continue; pair<ll,ll>t1=dfs(visited|(1<<i), i); pair<ll,ll>t2=dfs(t1.second,last); r.first+=t1.first*t2.first; r.second=t1.second|t2.second; } if(r.second==0){ r=make_pair(1, visited); } return mem[visited][last]=r; } ll count(vectorG){ ::G=G; mem.clear(); mem.resize(1<<G.size()); pair<ll,ll> r=dfs(0,G.size()); return r.first; } }; Single Round Match 713 Round 1 – Division I, Level Three CoinsQuery We are awaiting the submission for the following editorial. If you would like to contribute an editorial for this problem you may do so by submitting to this challenge.
https://www.topcoder.com/blog/single-round-match-713-editorials/
CC-MAIN-2019-09
refinedweb
2,340
67.28
Dear all, I would like to share with you a customized redesign of the Wave Collapse Function algorithm that works in Processing. My wish is that someone, someday, can port this sketch from Python to Java and make this algorithm available to the whole Processing community (more on that below). What is the Wave Function Collapse algorithm ? It is an algorithm written in 2016 by Maxim Gumin that can generate procedural patterns from a sample image or from a collection of tiles. You can see it in action here (2D “overlapping model”) and here (3D “tiled model”). If you’re a game programmer / designer you’ve probably already heard of it as it has been used to generate terrain / buildings / cities proceduraly in a couple of recent games (see Bad North example). Goal of this implementation: To boil down the algorithm to its essence and avoid the redondancies and clumsiness of the original C# script (surprisingly long and difficult to read). This is an attempt to make a shorter, clearer and Processing compatible version of this algorithm, that can be understood and used by as many people as possible. Characteristics of this implementation: This is a rewritting of the 2D overlapping model in Processing Python mode. Unlike the original version, this implementation: - is not object oriented, making it easier to understand / closer to pseudo-code - is using 1D arrays instead of 2D arrays - is using array slicing for matrix manipulation - is populating the Wave with Python sets of indices whose size decrease as cells are “collapsed” (replacing large fixed size lists of booleans). - is storing data in dictionnaries whose keys are progressively deleted when possible. - is also storing data in tuples instead of lists - is skipping entropy computations (first entropy calculation not needed since equiprobable high level of uncertainty at start) - is displaying cells once (avoiding storing them in an array and redrawing at each frame) For all these reasons, and also because it is Python (one-liner list comprehensions, minimalist syntax, …), this implementation is a lot, lot shorter than the original script (and its various ports) with only 70 lines of code against nearly 800 lines for the latter. It is also faster in theory, but for obvious reasons (Jython under the hood) the following version won’t run as fast. It should also be pointed that this implementation stores all the rotated and reflected matrices of each pattern and, like most versions, doesn’t use a backtracking system. Full script You’ll need to download a tiny bitmap picture (usually 8x8 or 16x16 pixels) beforehand to load it as an input. You can find a whole bunch on this dedicated github page. from collections import Counter from itertools import chain from random import choice, sample w, h, s = 96, 50, 9 N = 3 def setup(): size(w*f, h*f, P2D) background('#FFFFFF') frameRate(1000) noStroke() global W, A, H, directions, patterns, freqs img = loadImage('Flowers.png') iw, ih = img.width, img.height kernel = tuple(tuple(i + n*iw for i in xrange(N)) for n in xrange(N)) directions = ((-1, 0), (1, 0), (0, -1), (0, 1)) all = [] for y in xrange(ih): for x in xrange(iw): cmat = tuple(tuple(img.pixels[((x+n)%iw)+(((a[0]+iw*y)/iw)%ih)*iw] for n in a) for a in kernel) for r in xrange(4): cmat = zip(*cmat[::-1]) all.append(cmat) all.append(cmat[::-1]) all.append([a[::-1] for a in cmat]) all = [tuple(chain.from_iterable(p)) for p in all] c = Counter(all) freqs = c.values() patterns = c.keys() npat = len(freqs) W = dict(enumerate(tuple(set(range(npat)) for i in xrange(w*h)))) A = dict(enumerate(tuple(set() for dir in xrange(len(directions))) for i in xrange(npat))) H = dict(enumerate(sample(tuple(npat if i > 0 else npat-1 for i in xrange(w*h)), w*h))) for i1 in xrange(npat): for i2 in xrange(npat): if [n for i, n in enumerate(patterns[i1]) if i%N!=(N-1)] == [n for i, n in enumerate(patterns[i2]) if i%N!=0]: A[i1][0].add(i2) A[i2][1].add(i1) if patterns[i1][:(N*N)-N] == patterns[i2][N:]: A[i1][2].add(i2) A[i2][3].add(i1) def draw(): global H, W if not H: print 'finished' noLoop() return emin = min(H, key = H.get) id = choice([idP for idP in W[emin] for i in xrange(freqs[idP])]) W[emin] = {id} del H[emin] stack = {emin} while stack: idC = stack.pop() for dir, t in enumerate(directions): x = (idC%w + t[0])%w y = (idC/w + t[1])%h idN = x + y * w if idN in H: possible = {n for idP in W[idC] for n in A[idP][dir]} if not W[idN].issubset(possible): intersection = possible & W[idN] if not intersection: print 'contradiction' noLoop() return W[idN] = intersection H[idN] = len(W[idN]) - random(.1) stack.add(idN) fill(patterns[id][0]) rect((emin%w) * s, (emin/w) * s, s, s) Fully annotated version from collections import Counter from itertools import chain from random import choice, sample w, h = 96, 50 # dimensions of output (array of wxh cells) f = 9 # size factor N = 3 # dimensions of a pattern (NxN matrix) def setup(): size(w*f, h*f, P2D) background('#FFFFFF') frameRate(1000) noStroke() global W, A, H, directions, patterns, freqs, xs, ys img = loadImage('Flowers.png') # path to the input image iw, ih = img.width, img.height # dimensions of input image xs, ys = width//w, height//h # dimensions of cells (rect) in output kernel = tuple(tuple(i + n*iw for i in xrange(N)) for n in xrange(N)) # NxN matrix to read every patterns contained in input image directions = ((-1, 0), (1, 0), (0, -1), (0, 1)) # (x, y) tuples to access the 4 neighboring cells of a specific cell all = [] # array list to store all the patterns found in input #### Stores the different patterns found in input for y in xrange(ih): for x in xrange(iw): ''' The one-liner below (cmat) creates a NxN matrix with (x, y) being its top left corner. This matrix will wrap around the edges of the input image. The whole snippet reads every NxN part of the input image and store the associated colors. Each NxN part is called a 'pattern' (of colors). Each pattern can be rotated or flipped (not mandatory). ''' cmat = tuple(tuple(img.pixels[((x+n)%iw)+(((a[0]+iw*y)/iw)%ih)*iw] for n in a) for a in kernel) # Storing rotated patterns (90°, 180°, 270°, 360°) for r in xrange(4): cmat = zip(*cmat[::-1]) # +90° rotation all.append(cmat) all.append(cmat[::-1]) # vertical flip all.append([a[::-1] for a in cmat]) # horizontal flip #### Flatten pattern matrices + count occurences ''' Once every pattern has been stored, - we flatten them (convert to 1D) for convenience - count the number of occurences for each one of them (one pattern can be found multiple times in input) - select and store unique patterns only ''' all = [tuple(chain.from_iterable(p)) for p in all] # flattening arrays c = Counter(all) # Python counter freqs = c.values() # number of occurences for each unique pattern patterns = c.keys() # list of unique patterns npat = len(freqs) # number of unique patterns #### Initializes the 'wave' (W), entropy (H) and adjacencies (A) array lists ''' Array W (the Wave) keeps track of all the available patterns, for each cell. At start start, all patterns are valid anywhere in the Wave so each subarray is a list of indices of all the patterns''' W = dict(enumerate(tuple(set(range(npat)) for i in xrange(w*h)))) ''' Array H should normally be populated with entropy values. Entropy is just a fancy way to represent the number of patterns still available in a cell. We can skip this computation and populate the array with the number of available patterns instead. At start all patterns are valid anywhere in the Wave, so all cells share the same value (npat). We must however pick one cell at random and assign a lower value to it. Why ? Because the algorithm in draw() needs to find a cell with the minimum non-zero entropy value. ''' H = dict(enumerate(sample(tuple(npat if i > 0 else npat-1 for i in xrange(w*h)), w*h))) ''' Array A (for Adjacencies) is an index datastructure that describes the ways that the patterns can be placed near one another. More explanations below ''' A = dict(enumerate(tuple(set() for dir in xrange(len(directions))) for i in xrange(npat))) # explanations below #### Computation of patterns compatibilities (check if some patterns are adjacent, if so -> store them based on their location) ''' EXAMPLE: If pattern index 42 can placed to the right of pattern index 120, we will store this adjacency rule as follow: A[120][1].add(42) Here '1' stands for 'right' or 'East'/'E' 0 = left or West/W 1 = right or East/E 2 = up or North/N 3 = down or South/S ''' # Comparing patterns to each other for i1 in xrange(npat): for i2 in xrange(npat): ''' (in case when N = 3) If the first two columns of pattern 1 == the last two columns of pattern 2 --> pattern 2 can be placed to the left (0) of pattern 1 ''' if [n for i, n in enumerate(patterns[i1]) if i%N!=(N-1)] == [n for i, n in enumerate(patterns[i2]) if i%N!=0]: A[i1][0].add(i2) A[i2][1].add(i1) ''' (in case when N = 3) If the first two rows of pattern 1 == the last two rows of pattern 2 --> pattern 2 can be placed on top (2) of pattern 1 ''' if patterns[i1][:(N*N)-N] == patterns[i2][N:]: A[i1][2].add(i2) A[i2][3].add(i1) def draw(): global H, W # Simple stopping mechanism ''' If the dict (or arraylist) of entropies is empty -> stop iterating. We'll see later that each time a cell is collapsed, its corresponding key in H is deleted ''' if not H: print 'finished' noLoop() return #### OBSERVATION ''' Find cell with minimum non-zero entropy (not collapsed yet).''' emin = min(H, key = H.get) #### COLLAPSE ''' Among the patterns available in the selected cell (the one with min entropy), select one pattern randomly, weighted by the frequency that pattern appears in the input image.''' id = choice([idP for idP in W[emin] for i in xrange(freqs[idP])]) # index of selected pattern ''' The Wave's subarray corresponding to the cell with min entropy should now only contains the id of the selected pattern ''' W[emin] = {id} ''' Its key can be deleted in the dict of entropies ''' del H[emin] #### PROPAGATION ''' Once a cell is collapsed, its index is put in a stack. That stack is meant later to temporarily store indices of neighoring cells ''' stack = {emin} ''' The propagation will last as long as that stack is filled with indices ''' while stack: ''' First thing we do is pop() the last index contained in the stack (the only one for now) and get the indices of its 4 neighboring cells (E, W, N, S). We have to keep them withing bounds and make sure they wrap around. ''' idC = stack.pop() # index of current cell for dir, t in enumerate(directions): x = (idC%w + t[0])%w y = (idC/w + t[1])%h idN = x + y * w # index of negihboring cell ''' We make sure the neighboring cell is not collapsed yet (we don't want to update a cell that has only 1 pattern available) ''' if idN in H: ''' Then we check all the patterns that COULD be placed at that location. EX: if the neighboring cell is on the left of the current cell (east side), we look at all the patterns that can be placed on the left of each pattern contained in the current cell. ''' possible = {n for idP in W[idC] for n in A[idP][dir]} ''' We also look at the patterns that ARE available in the neighboring cell ''' available = W[idN] ''' Now we make sure that the neighboring cell really need to be updated. If all its available patterns are already in the list of all the possible patterns: —> there’s no need to update it (the algorithm skip this neighbor and goes on to the next) ''' if not available.issubset(possible): ''' If it is not a subset of the possible list: —> we look at the intersection of the two sets (all the patterns that can be placed at that location and that, "luckily", are available at that same location) ''' intersection = possible & available ''' If they don't intersect (patterns that could have been placed there but are not available) it means we ran into a "contradiction". We have to stop the whole WFC algorithm. ''' if not intersection: print 'contradiction' noLoop() return ''' If, on the contrary, they do intersect -> we update the neighboring cell with that refined list of pattern's indices ''' W[idN] = intersection ''' Because that neighboring cell has been updated, its number of valid patterns has decreased and its entropy must be updated accordingly. Note that we're subtracting a small random value to mix things up: sometimes cells we'll end-up with the same minimum entropy value and this prevent to always select the first one of them. It's a cosmetic trick to break the monotony of the animation''' H[idN] = len(W[idN]) - random(.1) ''' Finally, and most importantly, we add the index of that neighboring cell to the stack so it becomes the next current cell in turns (the one whose neighbors will be updated during the next while loop) ''' stack.add(idN) #### RENDERING ''' The collapsed cell will always be filled with the first color (top left corner) of the selected pattern ''' fill(patterns[id][0]) rect((emin%w) * xs, (emin/w) * ys, xs, ys) The need for a Processing Java version The reasons are threefold: A lot of Processing users like to create games. As mentionned above, the WFC algorithm can be very useful for game design: generating terrains, buildings or even entire cities, be it in 2D or 3D. This could be a welcomed contribution for any designer who want to speed-up and expand his creative process. Long-awaited Coding Challenge. This algorithm has been submitted a couple of times on the Coding Train’s github (and mentionned multiple times on the YT channel) as an idea for a future Coding Challenge. It seems Daniel Shiffman really liked the suggestion but never had the chance to tackle it. Providing a clear and simple example sketch in Java could be a great opportunity to revive the submission and maybe have the chance to finally see the algorithm explained to a larger audience. The generative nature of the algorithm is closely related to the philosophy of Processing. In my opinion, Processing is mostly about generating things: design, art, drawings, colors, shapes… It is a tool to explore the vast field of possibilites that a simple idea can lead to. So far, the WFC algorithm has primarly been used in the field of game design but I cannot help but to think there’s so much more to do with it. Some have started generating music with it, others poetry or even wine descriptions… and I believe Processing is the perfect environement to explore the possibilities even further. It is in its DNA. Original Algorithm The following explanations are here to help understanding the orginal algorithm, as it was designed by Maxim Gumin. It is not an exact representation of the Python implementation above but can be a good introductory step to the code. 1/ Read the input bitmap, store every NxN patterns and count their occurences. ( optional: Augment pattern data with rotations and reflections.) For example, when N = 3: 2/ Precompute and store every possible adjacency relations between patterns. In the example below, patterns 207, 242, 182 and 125 can overlap the right side of pattern 246 3/ Create an array with the dimensions of the output (called W for wave). Each element of this array is an array holding the state ( True of False ) of each pattern. For example, let’s say we count 326 unique patterns in input and we want our output to be of dimensions 20 by 20 (400 cells). Then the “Wave” array will contain 400 (20x20) arrays, each of them containing 326 boolan values. At start, all booleans are set to True because every pattern is allowed at any position of the Wave. W = [[True for pattern in xrange(len(patterns))] for cell in xrange(20*20)] 4/ Create another array with the dimensions of the output (called H ). Each element of this array is a float holding the “entropy” value of its corresponding cell in output. Entropy here refers to Shannon Entropy and is computed based on the number of valid patterns at a specific location in the Wave. The more a cell has valid patterns (set to True in the Wave), the higher its entropy is. For example, to compute the entropy of cell 22 we look at its corresponding index in the wave ( W[22] ) and count the number of booleans set to True . With that count we can now compute the entropy with the Shannon formula. The result of this calculation will be then stored in H at the same index H[22] At start, all cells have the same entropy value (same float at every position in H ) since all patterns are set to True , for each cell. H = [entropyValue for cell in xrange(20*20)] These 4 steps are introductory steps, they are necessary to initalize the algorithm. Now starts the core of the algorithm: 5/ Observation: Find the index of the cell with the minimum nonzero entropy (Note that at the very first iteration all entropies are equal so we need to pick the index of a cell randomly.) Then, look at the still valid patterns at the corresponding index in the Wave and select one of them randomly, weighted by the frequency that pattern appears in the input image (weighted choice). For example if the lowest value in H is at index 22 ( H[22] ), we look at all the patterns set to True at W[22] and pick one randomly based on the number of times it appears in the input. (Remember at step 1 we’ve counted the number of occurences for each pattern). This insures that patterns appear with a similar distribution in the output as are found in the input. 6/ Collapse: We now assign the index of the selected pattern to the cell with the minimum entropy. Meaning that every pattern at the corresponding location in the Wave are set to False except for the one that has been chosen. For example if pattern 246 in W[22] was set to True and has been selected, then all other patterns are set to False . Cell 22 is assigned pattern 246 . In output cell 22 will be filled with the first color (top left corner) of pattern 246. (blue in this example) 7/ Propagation: Because of adjacency constraints, that pattern selection has consequences on the neighboring cells in the Wave. The arrays of booleans corresponding to the cells on the left and right, on top of and above the recently collapsed cell need to be updated accordingly. For example if cell 22 has been collapsed and assigned with pattern 246 , then W[21] (left), W[23] (right), W[2] (up) and W[42] (down) have to be modified so as they only keep to True the patterns that are adjacent to pattern 246 . For example, looking back at the picture of step 2, we can see that only patterns 207, 242, 182 and 125 can be placed on the right of pattern 246. That means that W[23] (right of cell 22 ) needs to keep patterns 207, 242, 182 and 125 as True and set all other patterns in the array as False . If these patterns are not valid anymore (already set to False because of a previous constraint) then the algorithm is facing a contradiction and the whole algorithm must be stopped. This process doesn’t stop to the 4 direct neighbors of the collapsed cell and has to be extended recursively to the neighbors of the neighbors, and so on, until all constraints are propagated. 8/ Updating entropies Because a cell has been collapsed (one pattern selected, set to True ) and all its surrounding cells updated accordingly (setting non adjacent patterns to False ), the entropy of these cells have changed and needs to be computed again. (Remember that the entropy of a cell is correlated to the number of valid pattern it holds in the Wave.) In the example, the entropy of cell 22 is now 0, ( H[22] = 0 , because only pattern 246 is set to True at W[22] ) and the entropy of its neighboring cells have decreased (patterns that were not adjacent to pattern 246 have been set to False ). By now the algorithm arrives at the end of the first iteration and will loop over steps 5 (find cell with minimum non zero entropy) to 8 (update entropies) until all cells are collapsed. Useful additionnal ressources: This detailed article from Stephen Sherratt and this explanatory paper from Karth & Smith. Also this comprehensive blogpost by Trasevol_Dog.
https://discourse.processing.org/t/wave-collapse-function-algorithm-in-processing/12983
CC-MAIN-2022-40
refinedweb
3,561
53.44
Custom Fonts Note: Before progressing to this tutorial, please update source project to Daggerfall Unity 0.11.3 or later. This version has fixes required to complete this part in series. In Part 3 of this series, we noted the Korean (ko) locale would print out question mark characters (?? ???) instead of proper glyphs. This happens because Daggerfall Unity does not yet have an appropriate font asset to render these characters. The default fonts have a full complement of Latin characters but non-Latin languages require a new font to display their unique alphabet. This tutorial will demonstrate how to add a custom Korean font with a Hangul alphabet to Daggerfall Unity, but the same process can be used to add Cyrillic fonts, Kanji fonts, or even just a custom default font. The font we’ll be using is Noto Serif KR from Google Fonts. Click Download family on that page to download the font used in this tutorial, or substitute with another TTF/OTF font for your language. Once downloaded, unzip the whole font family and locate NotoSerifKR-Regular.otf. This is the specific font we’ll be using. To start with, we’ll add this font to our Unity project. - In Project view, navigate to our DemoTranslationMod/Resources folder. - Drag and drop the NotoSerifKR-Regular.otf font into this folder with other resources. Unity will import this like below. Create TextMeshPro Font Daggerfall Unity uses TextMeshPro (TMP) fonts. Before we can see this font in game, we need to create a TMP font asset. - Click Window menu > TextMeshPro > Font Asset Creator - Set NotoSerifKR-Regular in Source Font File by clicking the circle selector on right-hand side then selecting font Now we need to determine which character codes our TMP font will support. This will vary based on many factors unique to the target language, but the core concept is that we want to inform Font Asset Creator which character codes from your alphabet to compile into your TMP font. Any characters not added to TMP font asset will continue to display as question marks in game. There are multiple ways to describe which characters to use. You can select from a basic list of settings, use decimal/hex ranges, import from another TMP font, import from a file, etc. Whatever method you use, keep track of the settings so you can add to it later if any characters are found missing. In this example, we’re going to use a subset of Hangul alphabet by directly entering the characters required. It’s better to start with a subset of characters for the region/dialect you’re targeting rather than just trying to include everything. Some languages have thousands of characters which can result in an unusable TMP atlas without enough fidelity. - In Font Asset Creator, drop down Character Set selector and choose Custom Characters - Copy and paste the following custom characters into the Custom Character List text box. Note the very first character is a space character. ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz가개갸거게겨고괴괘교구귀궤규그긔기나내냐너네녀노뇌놰뇨누뉘눼뉴느늬니다대댜더데뎌도되돼됴두뒤뒈류드듸디라래랴러레려로뢰뢔료루뤼뤠류르릐리마매먀머메며모뫼뫠묘무뮈뭬뮤므믜미바배뱌버베벼보뵈봬뵤부뷔붸뷰브븨비사새샤서세셔소쇠쇄쇼수쉬쉐슈브븨비아애야어에여오외왜요우위웨유으의이자재쟈저제져조죄좨죠주쥐줴쥬즈즤지차채챠처체쳐초최쵀쵸추취췌츄츠츼치카캐캬커케켜코쾨쾌쿄쿠퀴퀘큐크킈키타태탸터테텨토퇴퇘툐투튀퉤튜트틔티파패퍄퍼페펴포푀퐤표푸퓌풰퓨프픠피하해햐허헤혀호회홰효후휘훼휴흐희히역을선택십시1234567890‘?’“!”(%)[#]{@}/&\<-+÷×=>®©$€£¥¢:;,.*… The above characters are enough for this tutorial, but will need to be expanded for full language support. This is how it looks in Font Asset Creator. We’re also adding the basic English alphabet to have a well-rounded font that can still display any untranslated English text. Click Generate Font Atlas to render all the specified characters into a TMP atlas. Once you’ve created the atlas, you’ll see all the characters packed like below. Click for full size. TextMeshPro renders glyphs using signed distance fields (SDF). How this works is outside the scope of this tutorial, but to summarise it’s a way of representing fonts using mathematical values that can maintain smooth shapes at any resolution. In the output field, take note of the Missing characters, Excluded characters, and “characters missing from font file”. This will display any character codes you requested but could not be found in the provided TTF/OTF font. If your source font is missing any important characters, then it’s necessary to locate another TTF/OTF font containing those characters. Depending on your font requirements, you might want to increase Atlas Resolution, e.g. to 4096×4096 or higher to support more characters with good fidelity. You can also adjust packing method, sample size, etc. for your specific font needs. For this tutorial, the atlas generated above is good enough. Click the Save button and save your new TMP font to DemoTranslationMod/Resources. We’ll use the default name in a moment, please don’t change it. This creates a new TMP font asset like below with the name “NotoSerifKR-Regular SDF”. This new SDF asset contains the atlas and other information required to render the TMP font in Daggerfall Unity. You can come back and recreate the font later with different properties or more characters if needed. Associate Font With Locale There’s one more step before can see this font in game. We need to associate our custom font with the correct locale so that Daggerfall Unity knows to use it. This is done using the StartupScript.cs code we created previously. Open StartupScript.cs in your code editor and replace the entire contents with below. Don’t forget to save your changes! using UnityEngine; using UnityEngine.Localization; using UnityEngine.Localization.Settings; using DaggerfallWorkshop.Game; using DaggerfallWorkshop.Game.Utility.ModSupport; using DaggerfallWorkshop.Game.UserInterface;); } Debug.Log("StartScript has completed."); } } } Let’s take a look at what changed. To start with, we added some new using statements. These import some extra functionality to the script. using UnityEngine.Localization; using UnityEngine.Localization.Settings; using DaggerfallWorkshop.Game.UserInterface; Then we added the following code to associate our custom font with the KO locale to Daggerfall’s FONT003. This is the default font used in most parts of the game. //); } First, we create a custom DaggerfallFont called font_ko. By default we’re loading FONT003, but we’ll replace this in a moment with our custom font. Second, we tell font_ko to load our custom font asset using LoadSDFFontAsset(). Any font created using the TextMeshPro Font Asset Creator should load OK. Reminder: you need to be on Daggerfall Unity 0.11.3 or later. Finally, we try to get the “ko” locale and only continue if this locale is found. If the locale is found, we associate our custom DaggerfallFont with the “ko” locale using RegisterLocalizedFont(). When this code executes at startup, Daggerfall Unity now knows it should use a different font when rendering FONT003 within the Korean (ko) locale. You can associate the same SDF font with FONT001, FONT002, etc. but you might want to use different styles of typefaces to better match the desired look and feel in your translation. Make sure your changes are saved, then we can try this font in game. - Click Play to start the game and click through to title menu. - Use the locale drop-down to select Korean (ko) in Game view. - Click Start New Game in title menu. If everything works as expected, our custom font will be selected and used with our translated text example. Click Play again to stop game. To summarise, creating a custom font requires the following steps: - Locate appropriate TTF/OTF source fonts for your language. These fonts must contain all the alphabet characters you need for your translation. - Import the TTF/OTF font into Unity project. - Use the Font Asset Creator to generate a custom TMP font asset with the required characters and resolution. - Associate new font with your custom locale and related Daggerfall font in startup C# script. You might need to recreate font several times when creating your translation mod, either to add new characters, change resolution, or just finetune the look and feel. If you change the asset name, don’t forget to update this in your startup script. Now that we have a custom font, we can move on to packaging our localisation to standalone files. This will be covered in Localizing Strings in Daggerfall Unity – Part 7.
https://www.dfworkshop.net/localizing-strings-in-daggerfall-unity-part-6/
CC-MAIN-2021-25
refinedweb
1,334
66.54
Continued assistance through writing and revision till final submission by the professional and experienced writers. 10 subjects 2,10,1000 solved Questions 500 Solved Questions Added Everyday Download Solution in Seconds All Subject Accounting Finance Engineering Science Computer Science Economics Management Writing See More; } /** * get average speed for activity, in km/h */ public double averageSpeed() { // to be completed } The class Activity records details of an individual fitness event. The averageSpeed() method is incomplete. a) Complete the body of the averageSpeed() method, to calculate the average speed in kilometres per hour. Note that seconds can be converted to hours by dividing by 3600. [4 marks] [CSC8001] Page 3 of 5 A separate class, Log, will maintain a list of Activity objects together with the name of the person doing the activities. The class has been partially written, as follows: import java.util.ArrayList; public class Log { private String name; private ArrayList // constructor method to be completed public Activity bestSpeed() { Activity topAct; // find activity with highest speed return topAct; } } b) Write a constructor method for the Log class. New Log objects should have a name initialised using a parameter to the constructor method, and an empty list of activities. [6 marks] c) Write a method, addActivity, to class Log, to add a new activity to the activities ArrayList. [4 marks] [CSC8001] Page 4 of 5 d) The bestSpeed()method will search all recorded activities and return the activity with the highest average speed. This method has been partially written in the class declaration shown on the previous page. Complete the body of the bestSpeed() method. [6 marks] e) The activities list has the following type declaration: private ArrayList Use of an ArrayList to store the Log entries may be a problem if a large number of activities are to be recorded, for example over the course of several years. Users of the system have said they would like to be able to find an activity using the date when the activity took place. Suggest an alternative collection type that could be used to store log entries, and access them by date (represented as a String). Provide a type declaration for your chosen collection type. [5 marks] Question B2 The personnel management program at the University of Outer Hebrides must handle information about the people employed there. Employees may be on permanent or fixed-term contracts. Write declarations for the following: a) A class Employee, containing six fields specifying the name, personnel number, address, designation (e.g., “lecturer”, “technician”, etc.), department and salary of the person concerned (choose appropriate names and types). Values for those state variables should be passed as parameters to the class’s constructor. This class should include appropriate accessor and mutator methods. [6 marks] [CSC8001] Page 5 of 5 b) Classes Permanent and FixedTerm, which extend the Employee class. Class Permanent adds a starting date of an employee’s permanent contact (passed as a parameter to the constructor). Class FixedTerm adds the duration of a fixed term employee’s contract (passed as a parameter to the constructor). [7 marks] c) A method called z, which prints out the names of all employees on permanent contracts in the department of Zoology, and also prints out the total salary bill of that department. The method should take as a parameter an ArrayList, which contains Employee objects representing all employees in the University. [12 marks] END Solution in attached zip file
https://www.livewebtutors.com/view-solution/question-b1a-fitness-application-has-been-written-/52
CC-MAIN-2018-39
refinedweb
569
52.6
Breadth and depth first search - part 1 Breadth and depth first search - part 3 As I've written in the previous post Breadth and depth first search - part 1 - I'll dive in more details and explain how to use the breadth and depth search methods. We'll execute a test case using the Romania map shown bellow, print the traveled paths in the screen, calculate the shortest path possible between two cities using Dijkstra's algorithm and print such a path in the screen. To accomplish all the above let's start presenting the data structures used to represent the map in the C# programming language: public class Node { public Node(string key, object data); public Node(string key, object data, AdjacencyList neighbors); public virtual object Data { get; set; } public virtual string Key { get; } public virtual AdjacencyList Neighbors { get; } public virtual Node PathParent { get; set; } protected internal virtual void AddDirected(EdgeToNeighbor e); protected internal virtual void AddDirected(Node n); protected internal virtual void AddDirected(Node n, int cost); } The Node class will be used to represent each city of the map. Each city has its name represented by the key property and some other relevant data represented by the data property. Each city also has an adjacency list implemented by a specific class called AdjacencyList. This adjacency list represents the neighbors cities of a given city. For example, in the above map the neighbors cities of Bucharest are: Urziceni, Giurgiu, Pitesti and Fagaras. Let's see the code of another class: public class Graph { public Graph(); public Graph(NodeList nodes); public virtual int Count { get; } public virtual NodeList Nodes { get; } public virtual void AddDirectedEdge(Node u, Node v); public virtual void AddDirectedEdge(string uKey, string vKey); public virtual void AddDirectedEdge(Node u, Node v, int cost); public virtual void AddDirectedEdge(string uKey, string vKey, int cost); public virtual void AddNode(Node n); public virtual Node AddNode(string key, object data); public virtual void AddUndirectedEdge(Node u, Node v); public virtual void AddUndirectedEdge(string uKey, string vKey); public virtual void AddUndirectedEdge(Node u, Node v, int cost); public virtual void AddUndirectedEdge(string uKey, string vKey, int cost); public virtual void Clear(); public virtual bool Contains(Node n); public virtual bool Contains(string key); } The Graph class has a property that references a collection of nodes, that is, a collection of cities. This collection of cities is represented by the class NodeList that implements the so used interface IEnumerable. As you can see the Graph class has methods that add directed or undirected edges to the graph. Each line that connects two cities (vertexes) in the Romania map is considered an edge. The map above contains only undirected edges because they aren't defined just as one way paths between the cities. It's possible to go from Bucharest to Urziceni and then come back to Bucharest for example. So it's a two way path. Above each line in the map is a value that represents the path cost between two cities. Let's consider this cost as the distance in miles between the cities. The path cost could be any other variable, for example, the time spent to traverse the distance (edge). The cost variable can vary according to the problem. I implemented a class called Pathfinding as follows: class Pathfinding { private static Graph graph = new Graph(); ... public static void BreadthFirstSearch(Node start, Node end) { ... } public static void DepthFirstSearch(Node start, Node end) { ... } ... } This class has additional properties and methods as ShortestPath and PrintPath. I won't spend time explaining its additional methods because they are already well explained in Part 5: From Trees to Graphs (article by Scott Mitchell). So, let's run a test case. For this we need to fill the graph with the Romania map data. class Program { static void Main(string[] args) { Pathfinding pathFinding = new Pathfinding(); Node start, end; // Vertexes pathFinding.Graph.AddNode("Arad", null); pathFinding.Graph.AddNode("Bucharest", null); pathFinding.Graph.AddNode("Craiova", null); pathFinding.Graph.AddNode("Dobreta", null); pathFinding.Graph.AddNode("Eforie", null); pathFinding.Graph.AddNode("Fagaras", null); pathFinding.Graph.AddNode("Giurgiu", null); pathFinding.Graph.AddNode("Hirsova", null); pathFinding.Graph.AddNode("Iasi", null); pathFinding.Graph.AddNode("Lugoj", null); pathFinding.Graph.AddNode("Mehadia", null); pathFinding.Graph.AddNode("Neamt", null); pathFinding.Graph.AddNode("Oradea", null); pathFinding.Graph.AddNode("Pitesti", null); pathFinding.Graph.AddNode("Rimnicu Vilcea", null); pathFinding.Graph.AddNode("Sibiu", null); pathFinding.Graph.AddNode("Timisoara", null); pathFinding.Graph.AddNode("Urziceni", null); pathFinding.Graph.AddNode("Vaslui", null); pathFinding.Graph.AddNode("Zerind", null); // Edges // Arad <-> Zerind pathFinding.Graph.AddUndirectedEdge("Arad", "Zerind", 75); // Arad <-> Timisoara pathFinding.Graph.AddUndirectedEdge("Arad", "Timisoara", 118); // Arad <-> Sibiu pathFinding.Graph.AddUndirectedEdge("Arad", "Sibiu", 140); // Bucharest <-> Urziceni pathFinding.Graph.AddUndirectedEdge("Bucharest", "Urziceni", 85); // Bucharest <-> Giurgiu pathFinding.Graph.AddUndirectedEdge("Bucharest", "Giurgiu", 90); // Bucharest <-> Pitesti pathFinding.Graph.AddUndirectedEdge("Bucharest", "Pitesti", 101); // Bucharest <-> Fagaras pathFinding.Graph.AddUndirectedEdge("Bucharest", "Fagaras", 211); // Craiova <-> Dobreta pathFinding.Graph.AddUndirectedEdge("Craiova", "Dobreta", 120); // Craiova <-> Pitesti pathFinding.Graph.AddUndirectedEdge("Craiova", "Pitesti", 138); // Craiova <-> Rimnicu Vilcea pathFinding.Graph.AddUndirectedEdge("Craiova", "Rimnicu Vilcea", 146); // Dobreta <-> Mehadia pathFinding.Graph.AddUndirectedEdge("Dobreta", "Mehadia", 75); // Eforie <-> Hirsova pathFinding.Graph.AddUndirectedEdge("Eforie", "Hirsova", 86); // Fagaras <-> Sibiu pathFinding.Graph.AddUndirectedEdge("Fagaras", "Sibiu", 99); // Hirsova <-> Urziceni pathFinding.Graph.AddUndirectedEdge("Hirsova", "Urziceni", 98); // Iasi <-> Neamt pathFinding.Graph.AddUndirectedEdge("Iasi", "Neamt", 87); // Iasi <-> Vaslui pathFinding.Graph.AddUndirectedEdge("Iasi", "Vaslui", 92); // Lugoj <-> Mehadia pathFinding.Graph.AddUndirectedEdge("Lugoj", "Mehadia", 70); // Lugoj <-> Timisoara pathFinding.Graph.AddUndirectedEdge("Lugoj", "Timisoara", 111); // Oradea <-> Zerind pathFinding.Graph.AddUndirectedEdge("Oradea", "Zerind", 71); // Oradea <-> Sibiu pathFinding.Graph.AddUndirectedEdge("Oradea", "Sibiu", 151); // Pitesti <-> Rimnicu Vilcea pathFinding.Graph.AddUndirectedEdge("Pitesti", "Rimnicu Vilcea", 97); // Rimnicu Vilcea <-> Sibiu pathFinding.Graph.AddUndirectedEdge("Rimnicu Vilcea", "Sibiu", 80); // Urziceni <-> Vaslui pathFinding.Graph.AddUndirectedEdge("Urziceni", "Vaslui", 142); start = pathFinding.Graph.Nodes["Oradea"]; end = pathFinding.Graph.Nodes["Neamt"]; Console.WriteLine("\nBreadth First Search algorithm"); Pathfinding.BreadthFirstSearch(start, end); foreach(Node n in pathFinding.Graph.Nodes) n.Data = null; Console.WriteLine("\n\nDepth First Search algorithm"); Pathfinding.DepthFirstSearch(start, end); Console.WriteLine("\n\nShortest path"); Pathfinding.ShortestPath(start, end); pathFinding.Graph.Clear(); Console.ReadKey(); } } Firstly we create a new instance of the Pathfinding class and two instances of the Node class that will reference the start and end city respectively. The pathfinding object has a graph property that we use to store the nodes, that is, the cities of the map. To accomplish this the method AddNode of the Graph class is used. The key that represents the node is the name of the city in this case. After adding the cities to the graph it's time to connect the cities by means of the edges between them. For each undirected edge of the map the fourth overload of the AddUndirectedEdge method is used. The method receives as arguments the names of the edge's vertexes and the path cost. Supposing we want to go from Oradea to Neamt, we must set the start and end node appropriately and that is done when the start and end node are assigned the values already present in the graph. After everything is set up we can run the the breadth and depth first search methods. To start I call the the method BreadthFirstSearch already presented in the previous post Breadth and depth first search - part 1. The method receives the start and end nodes as arguments and traverses the graph according to the breadth first search algorithm. During the traversal it prints the paths in the screen so that it's easier to visually debug the code. We use the same graph data to run the depth first search method but to avoid a wrong behavior it's necessary to set the data property of each graph's node to null. It's because such property is used to store a value indicating if that node was already visited during the path traversal of the breadth first search method. OK. Now that the graph data is prepared we can run the depth first search method invoking the DepthSearchMethod of the Pathfinding class. This method receives the start and end nodes as arguments and traverses the graph according to the depth first search algorithm. During the traversal it prints the paths in the screen so that it's easier to visually debug the code. The last and so important method is the ShortestPath one. The shortest path problem can be calculated through different algorithms. In this case the algorithm used (Dijkstra's algorithm) is suitable because we don't have negative costs otherwise we should use other algorithms. The ShortestPath method of the Pathfinding class receives as arguments the start and end nodes and prints in the screen the total distance of such a path and the cities travelled. See the screenshot of the output: Note: if you want to see a C++ implementation of the breadth and depth first search, check the third part of this series: Breadth and depth first search - part 3. Get the complete code (Microsoft Visual C# 2008 solution) and executable of this post at: To try out the code you can use the free Microsoft Visual C# 2008 Express Edition that you can get at:
https://www.leniel.net/2008/01/breadth-and-depth-first-search-part-2.html
CC-MAIN-2019-13
refinedweb
1,508
58.18
240 million emergency 911 calls are made in the United States per year. That averages out to roughly 600,000 calls per day. However, many of those calls are not emergencies. First responders often respond to barking dog complaints when people in need could use those resources. It’s estimated that nearly 10,000 lives could be saved every year if emergency response times were reduced by one minute. Is there a way to visualize emergency calls by their type? Can we analyze the result and measure how to limit wasting resources on non-emergencies? Can we help increase the well-being of others when they’re having an emergency? The answers are Yes, Yes, and Yes! We can combine speech-to-text using Deepgram and turn transcripts into data visualizations using a Python package like Matplotlib. Let's see why these two technologies are a perfect match. What is Deepgram? Deepgram is an automated speech recognition voice-to-text company that allows you to build applications that transcribe speech-to-text. You’ll receive an actual transcript of the person speaking or a conversation between multiple people. One of the many reasons to choose Deepgram over other providers is that we build better voice applications with faster, more accurate transcription through AI Speech Recognition. We offer real-time transcription and pre-recorded speech-to-text. The latter allows uploading of a file that contains audio voice data to be transcribed. We recently published a few blog posts on using our Python SDK to do live transcription with some of the most popular Python web frameworks, including FastAPI, Flask, Django, and Quart. The Deepgram Python SDK Project With Matplotlib Visualization Now that you have a better understanding of Deepgram, let’s see how we can use the Deepgram speech-to-text Python SDK to turn transcripts into data visualizations with a package like Matplotlib. In the following project, let’s transcribe pre-recorded audio with Deepgram and use a bar graph to analyze the types of emergency calls and how many of those calls are received. Setting Up the Deepgram Speech-to-Text Python Project Before we start, it’s essential to generate a Deepgram API key to use in our project. We can go to the Deepgram Console. We'll make sure to copy it and keep it in a safe place, as we won’t be able to retrieve it again and will have to create a new one. In this tutorial, we’ll use Python 3.10, but Deepgram supports some earlier versions of Python. Next, we'll make a directory anywhere we’d like. mkdir deepgram-dashboard Then we'll change into that directory to start adding things to it. cd deepgram-dashboard We’ll also need to set up a virtual environment to hold the project and its dependencies. We can read more about those here and how to create one. It’s recommended in Python to use a virtual environment so the project can be installed inside a container rather than installing it system-wide. We need to ensure the virtual environment is activated because we’ll install dependencies inside. If the virtual environment is named venv, we'll need to activate it. source venv/bin/activate We'll install the dependencies for the project by running the below pip installs from the terminal inside the virtual environment. pip install deepgram-sdk pip install python-dotenv pip install matplotlib We now can open up an editor and create an environment variable file to store the Deepgram API Key from the Deepgram Console. Create a new file called .env at the project level and add the following Python environment variable, replacing [YOUR_API_KEY] with the API Key from the console: DEEPGRAM_API_KEY=”[YOUR_API_KEY]” Lastly, files with audio need to be added to the project so Deepgram can transcribe them. This project uses small audio-created samples using the PCM recorder lite for Apple or Android. This app will create .wavaudio files but please note that Deepgram supports over 100+ audio formats and encodings. The Code for the Deepgram Speech-to-Text Python Project with Matplotlib Graphing Now to the fun part! Let’s create a file called transcribe-with-deepgram.py, which holds all of the code in this project. The project structure looks like this: The Python Imports Let’s open the file transcribe-with-deepgram.py and add the following imports: import asyncio import os from collections import Counter from deepgram import Deepgram from dotenv import load_dotenv from matplotlib import pyplot as plt from matplotlib.ticker import MaxNLocator import asynciohelps with writing asynchronous code in Python with the asyncand awaitkeywords. import oshelps working with files and directories. from collections import Counterhelps to count key/value pairs in an object which is needed to track the words from the transcript and how many times they were spoken. from deepgram import Deepgramallows access to the Deepgram Python SDK and its types like pre-recorded and live streaming transcription. from dotenv import load_dotenvreads the key/value pairs from the .envfile and sets them as environment variables. from matplotlib import pyplot as pltcreates a figure, a plotting area in a figure, plots some lines in a plotting area and decorates the plot with labels. from matplotlib.ticker import MaxNLocatorhelps provide the graph with friendly integer tick values. The Python Globals Let’s add this code underneath the imports: load_dotenv() DEEPGRAM_API_KEY = os.getenv('DEEPGRAM_API_KEY') files = [filename for filename in os.listdir() if filename.endswith('.wav')] words_list = [] The first line load_dotenv() loads the environment variables from the .env file and makes them available in the project. This line DEEPGRAM_API_KEY = os.getenv('DEEPGRAM_API_KEY') uses os.getenv() to return the value of the environment variable key, if it exists, and sets it to a variable. The files variable holds all of the files in our directory that end in wav as we loop through each, indicated by the list comprehension [filename for filename in os.listdir() if filename.endswith('.wav')]. Finally, an empty list called words_list is created, storing the words extracted from the JSON response Deepgram returns. Get the Deepgram Speech-to-Text Transcript Let’s add our first function to the transcribe-with-deepgram.py file. async def get_transcript(): deepgram = Deepgram(DEEPGRAM_API_KEY) words_count = Counter() for file in files: with open(file, 'rb') as audio: source = {'buffer': audio, 'mimetype': 'audio/wav'} response = await deepgram.transcription.prerecorded(source, {'punctuate': True}) if 'results' in response: get_words = response['results']['channels'][0]['alternatives'][0]['words'] for words in get_words: word = words['word'] words_list.append(word) words_count += Counter([w.lower() for w in words_list if w.lower() not in ['a', 'the', 'is', 'this', 'i', 'to', 'and']]) return words_count Here deepgram = Deepgram(DEEPGRAM_API_KEY) Deepgram is initialized by providing the API Key from variable DEEPGRAM_API_KEY below the imports. words_count = Counter() creates a Counter object that holds key/value pairs of the words spoken in the transcript and how many times they appear. In the below code snippet, we iterate through the .wav audio files in our directory and open each one. The source is set to a dictionary with the buffer value as audio and mimetype as audio/wav. If we were using .mp3 files the mimetype would be audio/mp3. The next line is where the actual Deepgram transcription happens with the pre-recorded audio await deepgram.transcription.prerecorded(source, {'punctuate': True}). Notice the source is passed in along with a dictionary {'punctuate': True}, which is a Deepgram feature that adds punctuation and capitalization to the transcript. for file in files: with open(file, 'rb') as audio: source = {'buffer': audio, 'mimetype': 'audio/wav'} response = await deepgram.transcription.prerecorded(source, {'punctuate': True) To get the words from the transcript, let’s check the JSON response object for results. Then we loop through the response and parse it to find each word in the transcript and append it to our list called words_list that was defined earlier. if 'results' in response: get_words = response['results']['channels'][0]['alternatives'][0]['words'] for words in get_words: word = words['word'] words_list.append(word) In the last part of the function, we take our words_count Counter and create a list comprehension that appends all the words in the list words_list with counts. For example, it will have key/value pairs with each word from the transcript and how many times they appeared. The last line, return words_count returns it, so it’s accessible outside our function when we need it. words_count += Counter([w.lower() for w in words_list if w.lower() not in ['a', 'the', 'is', 'this', 'i', 'to', 'and']]) return words_count Data Visualization with Matplotlib Let’s look at turning transcripts into data visualizations by creating a function called get_graph(). async def get_graph(): words = await get_transcript() x = range(len(words.keys())) width = 0.35 fig, ax = plt.subplots() ax.set_ylabel('Word Count') ax.set_xlabel('Emergency Call Types') ax.set_title('Deepgram Transcript') ax.set_xticks(x) ax.set_xticklabels(words.keys()) ax.yaxis.set_major_locator(MaxNLocator(integer=True))() A lot is going on in this function, so let’s simplify it by looking at the code in bigger chunks. Let’s get the returned value of words_count from the previous function by creating a new object words = await get_transcript(). The code below sets the labels on the x and y-axis, sets the title of the bar graph, and grabs the keys. The keys are the words in the transcript from the word object. Then it places each in the chart. ax.set_ylabel('Word Count') ax.set_xlabel('Emergency Call Types') ax.set_title('Deepgram Transcript') ax.set_xticks(x) ax.set_xticklabels(words.keys()) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) Lastly, we get the exact word count above each bar in the graph, loop through the graph, and create the height and width of the bars. plt.show() will display the bar graph.() Now, run the project by going to a command line prompt in the terminal and type: python3 transcribe-with-deepgram.py A beautiful bar graph with Deepgram Python speech-to-text transcription and Matplotlib data visualization will get generated and look something like this (depending on the audio files used): Conclusion of Deepgram Speech-to-Text with Python and Matplotlib There are many other use cases for why one might want to use Python with Deepgram for voice-to-text transcription and data visualization. This project is just an example, and it’s encouraged to continue brainstorming innovative and game-changing ideas for speech-to-text and graphing. Can you think of other use cases for Deepgram and our Python SDK? To let us know, you can Tweet us at @deepgramdevs. We would love to hear from you! Discussion (1) Great article! Makes me wanna learn Python :)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/deepgram/how-to-turn-transcripts-into-data-visualizations-with-python-2fji
CC-MAIN-2022-33
refinedweb
1,779
56.86
Contents ‣ Programs ‣ Accessories ‣ ‣ Programs ‣ Python 2.2 ‣ ‣. On Windows 2000, (). You can link to Python statically or dynamically. Linking statically means linking against pythonNN.lib, while dynamically linking means linking against pythonNN.dll. The drawback to dynamic linking is that your app won’t run if pythonNN.dll does not exist on your system. (General note: pythonNN.lib is the so-called “import lib” corresponding to python.dll. It merely defines symbols for the linker.) Linking dynamically greatly simplifies link options; everything happens at run time. Your code must load pythonNN.dll using to command. ‣ Options ‣ Tabs,. Use the msvcrt module. This is a standard Windows-specific extension module. It defines a function kbhit() which checks whether a keyboard hit is present, and getch() which gets one character without echoing it. To terminate a process, you can use ctypes: import ctypes def kill(pid): """kill function for Win32""" kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(1, 0, pid) return (0 != kernel32.TerminateProcess(handle, 0)):..)). The Python installer issues a warning like this: This version uses ``CTL3D32.DLL`` which is not the correct version. This version is used for windows NT applications only. Tim Peters:”.
https://docs.python.org/2.6/faq/windows.html
CC-MAIN-2014-15
refinedweb
194
63.36
A Partridge In A Pear Tree December 23, 2016 We first define the gifts, then iterate through the verses of the song in two nested loops: (define gifts '( ("first" "a partridge in a pear tree") ("second" "two turtle doves") ("third" "three french hens") ("fourth" "four calling birds") ("fifth" "five golden rings") ("sixth" "six geese a-laying") ("seventh" "seven swans a-swimming") ("eighth" "eight maids a-milking") ("ninth" "nine ladies dancing") ("tenth" "ten lords a-leaping") ("eleventh" "eleven pipers piping") ("twelfth" "twelve drummers drumming"))) (define (christmas) (let loop ((gifts gifts) (rev-gifts (list))) (when (pair? gifts) (display "On the ") (display (caar gifts)) (display " day of Christmas my true love gave to me ") (display (cadar gifts)) (let rev-loop ((rev-gifts rev-gifts)) (when (pair? rev-gifts) (display (if (< 1 (length rev-gifts)) ", " " and ")) (display (cadar rev-gifts)) (rev-loop (cdr rev-gifts)))) (display ".") (newline) (loop (cdr gifts) (cons (car gifts) rev-gifts))))) You can run the program at. Advertisements I wish you a Merry Christmas and a Happy New Year. 425 character in Common Lisp: Oops, sorry, the bzip2 -9 file is actually only 429 bytes: Here’s a little C program (there are a couple of Obfuscated C competition programs that are worth a look). Not quite as short as Pascal’s (hard to compete with a language with built-in printing of numbers as ordinals): Here’s some JS as well: Merry Christmas all. Here’s the 12 days in MUMPS: twelvedays ; n i,j,nth f i=1:1:12 d . s nth=$p($t(days),”;”,i+1) . w !,”On the “,nth,” day of Christmas my true love gave to me” . f j=i:-1:1 d . . w ” ” . . w $p($t(presents+j),”;”,2) . . i j>2 w “,” . . e w $s(j=2:” and”,1:”.”) q ; days ;first;second;third;fourth;fifth;sixth;seventh;eighth;ninth;tenth;eleventh;twelfth presents ; I thought I would try in Python: gifts = { 'twelvth': 'twelve drummers drumming', 'eleventh': 'eleven pipers piping', 'tenth': 'ten lords a-leaping', 'ninth': 'nine ladies dancing', 'eighth': 'eight maids a-milking', 'seventh': 'seven swans a-swimming', 'sixth': 'six geese a-laying', 'fifth': 'five golden rings', 'fourth': 'four calling birds', 'third': 'three French hens', 'second': 'two turtle doves and ', 'first': 'a partridge in a pear tree.', } days = ('first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelvth') def first_part(day): print("On the {} day of Christmas" " my true love gave to me ".format(day), end="") def second_part(gift, comma=True): print(gift, end="") print(end=", ") if comma else None for day in days: first_part(day) for i in range(days.index(day), -1, -1): comma = False if (i == 0 or i == 1) else True gift = gifts[days[i]] second_part(gift, comma) print() Actually, I quite like the obfuscated C version, and it is easy to de-obfuscate: (let ((p “On the ~:r day of Christmas my true love gave to me ~a~%”) .”)) (let loop ((i ‘(236 215 196 176 157 137 113 90 69 48 26 0)) (c 1)) (if (not (null? i)) (begin (format #t p c (substring r (car i))) (loop (cdr i) (+ c 1)))))) But a constructive version could also make use of format, although its dsl is very unschemely: (let ((p “On the ~:r day of Christmas my true love gave to me ~a~%”)) (let loop ((r ‘(“turtle doves” “French hens” “calling birds” “golden rings” “geese a-laying” “swans a-swimming” “maids a-milking” “ladies dancing” “lords a-leaping” “pipers piping” “drummers drumming”)) (s “a partridge in a pear tree.”) (c 1)) (format #t p c s) (if (not (null? r)) (begin (loop (cdr r) (format #f “~r ~a~a ~a” (+ c 1) (car r) (if (= c 1) ” and” “,”) s) (+ c 1)))))) @Michael: Thanks, I wasn’t particularly intending to be obfuscated, just compact. For real C obfuscation see, eg: That program does actually print out The Twelve Days of Christmas, if it’s not clear from the code. Happy New Year to all.
https://programmingpraxis.com/2016/12/23/a-partridge-in-a-pear-tree/2/
CC-MAIN-2017-09
refinedweb
660
69.96
TL;DR this could be solvable by abstracting over non-value types. That seems a very good point. In fact, it is somewhat orthogonal to implicits and applies to the reader monad as well, though it matters less there. I think the current syntax should mean option 2 for consistency (I haven’t checked what’s implemented, I’d call 1 a bug), but there is a consistent way (though I’m not 100% happy with it). Nowadays we can’t abstract over parts of a method type, because method types are not value types, but type alias only support value types. We know that f1 and f2 aren’t equivalent operationally because of the function-method distinction, while f2 and f3 are equivalent. def f1(a: A)(b: B): C = foo def f2(a: A): B => C = b => foo def f3(a: A): Reader[B, C] = b => foo type Reader[S, T] = Function1[S, T] To abstract over parts of a method type, you might consider something like this, with f4 behaving like f1, ignoring the concrete syntax: type ImaginedReader[S, T] = (s: S): T def f4(a: A): ImaginedReader[B, C] = b => foo I don’t know the concrete syntax for the body of f4, what I wrote doesn’t make so much sense (trick questions: is s in scope in foo? Why is closure syntax not creating a closure?). But let me ignore syntax bikeshedding for this post—also because this problem doesn’t appear in the implicit case. I’m not sure how this would look in Haskell syntax happens to support this better (I’m not 100% sure this actually works in Haskell, but it makes sense): type ImaginedReader s t = s -> t f4: A -> ImaginedReader B C f4 a b c = foo Allowing that is a non-trivial extension, but at least it fits in what we understand — the compiler should just eagerly inline such type aliases. Note 1: I considered having a separate keyword from type, but couldn’t pick a decent one—I had picked non-value-type as a strawman but it was so ugly I didn’t like my own idea. Note 2: “eagerly inline type aliases” is actually very non-trivial since all type definitions in Scala are mutually recursive, so I expect significant implementation restrictions and I’m not sure such aliases could be exported. Back to @Ichoran’s concern, it could be solved by type ImplicitReader[S, T] = (implicit s: S): T // or maybe it's // type ImplicitReader[S, T] = implicit (s: S): T // ? I'm not sure, though `implicit` outside parens makes more sense. def f5: ImplicitReader[Foo, Bar] = f5body // no abstraction here needed, just like the blog post, so fewer syntax questions Do we want literally that? More brainstorming needed, please, but I think that’s a start. And it turns out this goes in a similar direction—if one understands type ImplicitTuple3[A, B, C] = ... as a non-value type alias to be inlined at each use site (which I think gives the effect you want). A technical problem is that nowadays a parameter block is not a type at all, just part of the syntax of method types, but changing that sounds conceptually plausible. Alternatively, just abstract over the whole binder. Another technical problem is that various non-value types (such as method types) have not only free type variables but free term variables. So you can write foo1 and foo2, but Baz and foo3 aren’t allowed. def foo1(ctx: Context)(tree: ctx.Tree): ctx.Tree type Bar = (ctx: Context)(tree: ctx.Tree): ctx.Tree def foo2: Bar type Baz(ctx: Context) = (tree: ctx.Tree): ctx.Tree def foo3(ctx: Context): Baz(ctx) But you could generally allow type members to abstract over paths, like it happens in DOT — for non-eager types, the value arguments could be erased during compilation. Right now, any such abstraction can only be done by defining Baz as a class, and it’s less obvious ctx can be erased there.
https://contributors.scala-lang.org/t/implicit-function-types/219?page=2
CC-MAIN-2018-22
refinedweb
674
65.25
The scope of this tool is very simple. Here the thing: - A modeler after has made his model in Maya runs the tool, a prompt window appears and into it he needs just to type the name of file, little digression , within Maya is possible to activate the History, it's a record of your operations which gives you the opportunity to go back and forth along the scene graph for modifing some steps of what you have done if you wish. - At this point the file will be saved in two different folder on a server, just call them, update and backup, what fantasy, isn't? They are two copies of the same file, but in the update folder will be only one instance of the scene file without its History, while in the backup folder will be the file with that indexed name and its whole History. My code seems to work properly, but there's a problem with the indexes when I save a scene with different name or save the egual scene with same name at some point after. More clear, we suppose having in the update folder a file named "Anto" and in the backup folder we already have "Anto_1" and "Anto_2", if I save another scene, said "Bobo", it will be saved not with "Bobo_1" but, instead, with "Bobo_3" or if I do another saving of "Anto" after that I will have "Anto_4" an so on, I need to correct this behaviour. Here my code, I'm doing my endeavours straight on my computer for trying to avoid other technical issues of different order. import maya.cmds as cmds import dircache update_dir = "C:\Users\ASUS\Desktop\ProvaPython\\" backup_dir = "C:\Users\ASUS\Desktop\ProvaPython1\\" file_list = dircache.listdir(backup_dir) unique_project_list = [] list_lenght = len(file_list) + 1 selected_item = 0 fname = '' counter = 0 status = 'No' #copy function definition def copy_file(fname): cmds.file(rename = (update_dir + fname)) cmds.delete(ch = True) cmds.file(save = True, type = 'mayaAscii') cmds.file(rename = (backup_dir + fname + "_" + str(list_lenght))) cmds.file(save = True, type = 'mayaAscii') cmds.confirmDialog(title='Saved', message='Save success', defaultButton='Close', cancelButton='Close') return print("\n") while counter < len(file_list): if file_list[counter][0 : file_list[counter].index( '_' ) ] not in unique_project_list: unique_project_list.append (file_list[counter][0 : file_list[counter].index( '_' ) ]) counter = counter + 1 while counter < len(unique_project_list): print(str(counter) + " = " + unique_project_list[counter]) counter = counter + 1 selected_item = cmds.promptDialog(title='Choose an option', message='Enter displayed number:' + ' ' + str(len(unique_project_list)) + ' ' + 'for a new scene', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') fname = raw_input('type a name file for backup\n') if fname not in unique_project_list: copy_file(fname) elif fname in unique_project_list: status = cmds.confirmDialog(title='Confirm', message='WARNING!!:' + fname + ' ' + 'already exist.' + ' ' + 'Do you want to overwrite it?', button=['Yes','No'], defaultButton='Yes', cancelButton='No') if status == 'Yes': fname = raw_input('type a name file for backup\n') #cmds.promptDialog(title='Save File', message='Type a name file for backup:', button=['Save', 'Cancel'], defaultButton='Save', cancelButton='Cancel', dismissString='Cancel') copy_file(fname) else: cmds.confirmDialog(title='Close', button=['Close'], defaultButton='Close', cancelButton='Close') Now I was thinking to make a test into the function copy_file() I have defined, before to run those commands that save a file in the backup folder. Here the code of my idea: import maya.cmds as cmds import dircache backup_dir = "C:\Users\ASUS\Desktop\ProvaPython1\\" file_list = dircache.listdir(backup_dir) fname = 'Anto' unique_project_list = [] sub_backup_list = [] print file_list[0][0 : file_list[0].index( '_' ) ] counter while counter < len(file_list): if file_list[counter][0 : file_list[counter].index( '_' ) ] == fname: sub_backup_list.append (file_list[counter]) print file_list[counter] counter = counter + 1 print ("\n") print file_list print sub_backup_list print len(sub_backup_list) So, from "file_list" I can set apart another list which I called "sub_backup_list" where it will be only the file instances with the current name stored in the "fname" variable and counting them by len(sub_backup_list), I want to use this information for generating an index, just the sublist's lenght, and using it in the command inside copy_file(), as cmds.file(rename = (backup_dir + fname + "_" + str(list_lenght))) ,but str(list_lenght) returns me an integer value one unit back than len(sub_backup_list). How can I fix it? Thanks a lot for any help or suggestions and I'm sorry again for any grammar mistakes or improper language eventualy, as I already said the English is just a second language for me. Gabriele.
http://www.dreamincode.net/forums/topic/327378-a-pipeline-with-python-in-maya/
CC-MAIN-2017-39
refinedweb
727
52.7
This is a C++ Program to generate random numbers using Middle Square method. In mathematics, the middle-square method is a method of generating pseudorandom numbers. In practice it is not a good method, since its period is usually very short and it has some severe weaknesses, such as the output sequence almost always converging to zero. Here is source code of the C++ Program to Generate Random Numbers Using Middle Square Method. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below. #include <iostream> #include <math.h> #include <stdlib.h> using namespace std; int a[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 }; int middleSquareNumber(int numb, int dig) { int sqn = numb * numb, next_num = 0; int trim = (dig / 2); sqn = sqn / a[trim]; for (int i = 0; i < dig; i++) { next_num += (sqn % (a[trim])) * (a[i]); sqn = sqn / 10; } return next_num; } int main(int argc, char **argv) { cout << "Enter the #-digit random numbers you want: "; int n; cin >> n; int start = 1, end = 1; start = a[n - 1]; end = a[n]; int number = ((rand()) % (end - start)) + start; cout << "The random numbers are:\n" << number << ", "; for (int i = 1; i < n; i++) { number = middleSquareNumber(number, n); cout << number << ", "; } cout << "..."; } Output: $ g++ MiddleSquare.cpp $ a.out Enter the #-digit random numbers you want: 5 The random numbers are: 10041, 16426, 796264, -276041, -115546, ... Sanfoundry Global Education & Learning Series – 1000 C++ Programs. Here’s the list of Best Reference Books in C++ Programming, Data Structures and Algorithms.
http://www.sanfoundry.com/cpp-program-generate-random-numbers-using-middle-square-method/
CC-MAIN-2017-26
refinedweb
255
69.62
You want to identify problems within a component of your web application, but your attempts to do so don’t seem to work. When you make a call to Trace.Write in the business object, either you get a compilation error or the debugger jumps right over the call and no output ever appears in the trace sequence. Import the System.Web namespace and reference the current HTTP context when performing a Trace.Write from within the component. In the component class, use the .NET language of your choice to: Import the System.Web namespace. Reference the current HTTP context when performing a Trace.Write, as in HTTPContext.Current.Trace.Write. The sample component we’ve written to illustrate this solution appears in Example 10-7 (VB) and Example 10-8 (C#). Example 10-9 shows the .aspx file used to test the sample component. The code-behind for the test page appears in Example 10-10 (VB) and Example 10-11 (C#). Figure 10-4 shows some sample output, including the resulting trace sequence. Figure 10-4. Trace sequence from testing the component In order for Trace.Write to work from within a component, you must be able to access the context for the current HTTP request. The easiest way to accomplish this is to import the System.Web namespace and access the HTTPContext.Current property from within the component. If a component ... No credit card required
https://www.oreilly.com/library/view/aspnet-cookbook/0596003781/ch10s05.html
CC-MAIN-2018-43
refinedweb
238
69.89
in reply to $threads->join() only returns one argument??? BUG? This is pretty obviously a bug. The context that is applied to the $thr->join call is the context that the threads->new call was in. That is: my $thr = threads->new( sub { return (1,2,3) }); my @a = $thr->join(); print "return is @a\n"; [download] ..fails, while.. my ($thr) = threads->new( sub { return (1,2,3) }); my @a = $thr->join(); print "return is @a\n"; [download] ..works fine. Note the difference in parens on the my $thr line. I'm going to poke at the threads code on this one. Update: Upon reflection and looking at the code, it makes sense in a perverse way. Because the subroutine/thread starts execution upon creation, someone could call wantarray from it off the top. If the context was determined at join time, there would be no way to determine the proper wantarray value. In fact, this behavior is documented in bleedperl's threads.pm (search for "context"). perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER' use Thread; $thr = new Thread \&sub1; @ReturnData = $thr->join; print "Thread returned @ReturnData"; sub sub1 { return "Fifty-six", "foo", 2; } [download] 20100226 Janitored by Corion: Added formatting, code tags, as per Writeup Formatting Tips Priority 1, Priority 2, Priority 3 Priority 1, Priority 0, Priority -1 Urgent, important, favour Data loss, bug, enhancement Out of scope, out of budget, out of line Family, friends, work Impossible, inconceivable, implemented Other priorities Results (252 votes), past polls
http://www.perlmonks.org/?node_id=265269
CC-MAIN-2015-32
refinedweb
257
63.29
On using WebUI.closeBroswer(), It only close browser, but chromeDriver,exe is still running on my machine. how to exit the chromeDriver.exe On using WebUI.closeBroswer(), It only close browser, but chromeDriver,exe is still running on my machine. how to exit the chromeDriver.exe Hi there, My chromedriver.exe is terminated when I call ‘Close Browser’ step. Please double check again if your browser is closed completely or not, or there are multiple chromedriver instances on your side If you want to terminate chromedriver.exe anytime after execution, you can check on ‘Terminate Drivers’ option from Project -> Settings -> Execution Thanks Edited: @Russ_Thomas Same here, after running many testcases, I have a large numbers of chromedrivers.exe still running. I use WebUI.closeBrowser() and it does close the browser, but let the driver run. Manual work-around: Create a batch file with the following contents: taskkill /f /im chromedriver.exe pause Create a custom keyword as below and call it either at end or at the beginning of the test case. This will kill all instances of chrome.exe and chrome driver.exe public class killProcess{ @Keyword def killProcess() { Runtime.getRuntime().exec(“taskkill /im chromedriver.exe /f”) Runtime.getRuntime().exec(“taskkill /im chrome.exe /f”) } } Getting errors when using this Keyword. Which imports / includes need to be added? Personally, I prefer to keep this kind of thing out of my tests. I have a batch script which I run when needed. It contains just three lines, one for each webdriver module: taskkill /f /im geckodriver.exe taskkill /f /im chromedriver.exe taskkill /f /im IEDriverServer.exe Hi Russ, Thanks for your feed-back. I use a similar batch script as well. I don’t always remember to run the script so I was thinking it might be good to add a keyword to kill the driver(s) when I call my single logoff case. Also I use Windows Scheduler to run cases over-night so having the killProcess will help for that testing. Cheers, Dave Found the solution (I had to use single quotes): public class killProcess { @Keyword def KILLWebdriver() { Runtime.getRuntime().exec(‘taskkill /f /im chrome.exe’) Runtime.getRuntime().exec(‘taskkill /f /im chromedriver.exe’) Runtime.getRuntime().exec(‘taskkill /f /im geckodriver.exe’) Runtime.getRuntime().exec(‘taskkill /f /im IEDriverServer.exe’) Runtime.getRuntime().exec(‘taskkill /f /im firefox.exe’) } }
https://forum.katalon.com/t/using-closebroswer-it-only-close-browser-but-still-chromedriver-is-not-killed-how-to-killed-chrome-driver/6090
CC-MAIN-2022-05
refinedweb
391
70.8
Code. Collaborate. Organize. No Limits. Try it Today. Smart. A Smart Pointer is a C++ object that acts like a pointer, but additionally deletes the object when it is no longer needed. "No longer needed" is hard to define, since resource management in C++ is very complex. Different smart pointer implementations cover the most common scenarios. Of course, different tasks than just deleting the object can be implemented too, but these applications are beyond the scope of this tutorial. Many libraries provide smart pointer implementations with different advantages and drawbacks. The samples here use the BOOST library, a high quality open source template library, with many submissions considered for inclusion in the next C++ standard. Boost provides the following smart pointer implementations: shared_ptr<T> T" shared_ptr scoped_ptr<T> intrusive_ptr<T> T weak_ptr<T> shared_array<T> scoped_array<T> scoped_ptr Let's start with the simplest one: scoped_ptr is the simplest smart pointer provided by boost. It guarantees automatic deletion when the pointer goes out of scope..(); } Using "normal" pointers, we must remember to delete it at every place we exit the function. This is especially tiresome (and easily forgotten) when using exceptions. The second example uses a scoped_ptr for the same task. It automatically deletes the pointer when the function returns 8 even in the case of an exception thrown, which isn't even covered in the "raw pointer" sample!) The advantage is obvious: in a more complex function, it's easy to forget to delete an object. scoped_ptr does it for you. Also, when dereferencing a NULL pointer, you get an assertion in debug mode. NULL std::auto_ptr Reference counting pointers track how many pointers are referring to an object, and when the last pointer to an object is destroyed, it deletes the object itself, too. The "normal" reference counted pointer provided by boost is shared_ptr (the name indicates that multiple pointers can share the same object). Let's look at a few examples: void Sample2_Shared() { // (A) create a new CSample instance with one reference boost::shared_ptr<CSample> mySample(new CSample); printf("The Sample now has %i references\n", mySample.use_count()); // should be 1 // (B) assign a second pointer to it: boost::shared_ptr<CSample> mySample2 = mySample; // should be 2 refs by now printf("The Sample now has %i references\n", mySample.use_count()); // (C) set the first pointer to NULL mySample.reset(); printf("The Sample now has %i references\n", mySample2.use_count()); // 1 // the object allocated in (1) is deleted automatically // when mySample2 goes out of scope } Line (A) creates a new CSample instance on the heap, and assigns the pointer to a shared_ptr, mySample. Things look like this:. Note: If you never heard of PIMPL (a.k.a. handle/body) or RAII, grab a good C++ book - they are important concepts every C++ programmer should know. Smart pointers are just one way to implement them conveniently in certain cases - discussing them here would break the limits of this article.: typedef boost::shared_ptr<CMyLargeClass> CMyLargeClassPtr; std::vector<CMyLargeClassPtr> vec; vec.push_back( CMyLargeClassPtr(new CMyLargeClass("bigString")) ); Very similar, but now, the elements get destroyed automatically when the vector is destroyed - unless, of course, there's another smart pointer still holding a reference. Let's have a look at sample 3: void Sample3_Container() { typedef boost::shared_ptr<CSample> CSamplePtr; // (A) create a container of CSample pointers: std::vector<CSamplePtr> vec; // (B) add three elements vec.push_back(CSamplePtr(new CSample)); vec.push_back(CSamplePtr(new CSample)); vec.push_back(CSamplePtr(new CSample)); // (C) "keep" a pointer to the second: CSamplePtr anElement = vec[1]; // (D) destroy the vector: vec.clear(); // (E) the second element still exists anElement->Use(); printf("done. cleanup is automatic\n"); // (F) anElement goes out of scope, deleting the last CSample instance } A few things can go wrong with smart pointers (most prominent is an invalid reference count, which deletes the object too early, or not at all). The boost implementation promotes safety, making all "potentially dangerous" operations explicit. So, with a few rules to remember, you are safe. There are a few rules you should (or must) follow, though: Rule 1: Assign and keep - Assign a newly constructed instance to a smart pointer immediately, and then keep it there. The smart pointer(s) now own the object, you must not delete it manually, nor can you take it away again. This helps to not accidentally delete an object that is still referenced by a smart pointer, or end up with an invalid reference count. Rule 2: a _ptr<T> is not a T * - more correctly, there are no implicit conversions between a T * and a smart pointer to type T. : struct CDad; struct CChild; typedef boost::shared_ptr<CDad> CDadPtr; typedef boost::shared_ptr<CChild> CChildPtr; struct CDad : public CSample { CChildPtr myBoy; }; struct CChild : public CSample { CDadPtr myDad; }; // a "thing" that holds a smart pointer to another "thing": CDadPtr parent(new CDadPtr); CChildPtr child(new CChildPtr); // deliberately create a circular reference: parent->myBoy = child; child->myDad = dad; // resetting one ptr... child.reset(); parent still references the CDad object, which itself references the CChild. The whole thing looks like this: parent CDad CChild If we now call dad.reset(), we lose all "contact" with the two objects. But this leaves both with exactly one reference, and the shared pointers see no reason to delete either of them! We have no access to them anymore, but they mutually keep themselves "alive". This is a memory leak at best; in the worst case, the objects hold even more critical resources that are not released: Strong vs. Weak References: A strong reference keeps the referenced object alive (i.e., as long as there is at least one strong reference to the object, it is not deleted). boost::shared_ptr acts as a strong reference. In contrast, a weak reference does not keep the object alive, it merely references it as long as it lives. Note that a raw C++ pointer in this sense is a weak reference. However, if you have just the pointer, you have no ability to detect whether the object still lives. boost::weak_ptr<T> is a smart pointer acting as weak reference. When you need it, you can request a strong (shared) pointer from it. (This can be NULL if the object was already deleted.) Of course, the strong pointer should be released immediately after use. In the above sample, we can decide to make one pointer weak: boost::weak_ptr<T> struct CBetterChild : public CSample { weak_ptr<CDad> myDad; void BringBeer() { shared_ptr<CDad> strongDad = myDad.lock(); // request a strong pointer if (strongDad) // is the object still alive? strongDad->SetBeer(); // strongDad is released when it goes out of scope. // the object retains the weak pointer } }; See the Sample 5 for more. shared_ptr offers quite some services beyond a "normal" pointer. This has a little price: the size of a shared pointer is larger than a normal pointer, and for each object held in a shared pointer, there is a tracking object holding the reference count and the deleter. In most cases, this is negligible. intrusive_ptr provides an interesting tradeoff: it provides the "lightest possible" reference counting pointer, if the object implements the reference count itself. This isn't so bad after all, when designing your own classes to work with smart pointers; it is easy to embed the reference count in the class itself, to get less memory footprint and better performance. intrusive_ptr To use a type T with intrusive_ptr, you need to define two functions: intrusive_ptr_add_ref and intrusive_ptr_release. The following sample shows how to do that for a custom class: intrusive_ptr_add_ref intrusive_ptr_release #include "boost/intrusive_ptr.hpp" // forward declarations class CRefCounted; namespace boost { void intrusive_ptr_add_ref(CRefCounted * p); void intrusive_ptr_release(CRefCounted * p); }; // My Class class CRefCounted { private: long references; friend void ::boost::intrusive_ptr_add_ref(CRefCounted * p); friend void ::boost::intrusive_ptr_release(CRefCounted * p); public: CRefCounted() : references(0) {} // initialize references to 0 }; // class specific addref/release implementation // the two function overloads must be in the boost namespace on most compilers: namespace boost { inline void intrusive_ptr_add_ref(CRefCounted * p) { // increment reference count of object *p ++(p->references); } inline void intrusive_ptr_release(CRefCounted * p) { // decrement reference count, and delete object when reference count reaches 0 if (--(p->references) == 0) delete p; } } // namespace boost This is the most simplistic (and not thread safe) implementation. However, this is such a common pattern, that it makes sense to provide a common base class for this task. Maybe another!). There is a "little" problem with VC6 that makes using boost (and other libraries) a bit problematic out of the box. The Windows header files define macros for min and max, and consequently, these respective functions are missing from the (original) STL implementation. Some Windows libraries such as MFC rely on min/max being present. Boost, however, expects min and max in the std:: namespace. To make things worse, there is no feasible min/max template that accepts different (implicitly convertible) argument types, but some libraries rely on that.. Please note: While I am happy about (almost) any feedback, please do not ask boost-specific questions here. Simply put, boost experts are unlikely to find your question here (and I'm just a boost noob). Of course, if you have questions, complaints, or recommendations regarding the article or the sample project, you.
http://www.codeproject.com/Articles/8394/Smart-Pointers-to-boost-your-code?fid=111912&df=90&mpp=10&noise=1&prof=True&sort=Position&view=Expanded&spc=None&select=935314&fr=42&PageFlow=FixedWidth
CC-MAIN-2014-23
refinedweb
1,530
53.1
by Rich Feit 01/10/2006 JavaServer Faces (JSF) is a technology for building Web application user interfaces. It goes beyond JavaServer Pages (JSP) by offering true server-side event handling within a page, and component-based pages that can live across multiple server requests. Apache Beehive is the evolution of the BEA WebLogic Workshop 8.1 runtime, which is now an open-source project of the Apache Software Foundation. Page Flow is Beehive's annotation-based Web controller technology, built on Apache Struts. JSF is great for building pages by wiring up components and events, but, like all view technologies, it needs a controller to separate out the navigation decisions between pages, and to provide a link to the business tier. It comes with a very basic navigation handler that is meant to be swapped out for a full-featured one. Page Flow provides the base for creating reusable, encapsulated flows of pages, and it works alongside a view layer. It is a full-featured navigation handler that treats JSF pages as first-class citizens. This article looks at how to integrate these two technologies to leverage the strengths of both. To set up a Beehive/JSF application, first you'll enable Page Flow, and then add support for JSF. The place to start is with a basic NetUI-enabled project. (NetUI is the piece of Beehive that contains Page Flow.) Set up a basic NetUI-enabled Web application according to these instructions. For this article, assume that it's called "jsf-beehive," and can be reached at. Next, install and configure JSF. Page Flow should work with any JavaServer Faces 1.1-compliant implementation, and it is tested against two popular ones: Apache MyFaces and the JSF Reference Implementation. Install JSF into your new Web application according to the instructions for one of the following: MyFaces v1.0.9 or later, the JSF Reference Implementation v1.1_01, or your preferred implementation. After that, you can enable Page Flow integration with one simple entry in WEB-INF/faces-config.xml, below the <application> tag and above the <navigation-rule> tag(s): <factory> <application-factory> org.apache.beehive.netui.pageflow.faces.PageFlowApplicationFactory </application-factory> </factory> Adding this gives Page Flow a chance to provide its own version of JSF framework objects in order to customize its behavior. In general, JSF behavior is modified only when you are using Page Flow features; the basic behavior of JSF is not changed. The most basic use of Page Flow in JSF is the raising (invoking) of actions from a JSF page. While your JSF page can handle intra-page events, a Page Flow action is the way to navigate from page to page. First, create a directory called "example" in your Web application, and in it create a Page Flow controller class: package example; import org.apache.beehive.netui.pageflow.Forward; import org.apache.beehive.netui.pageflow.PageFlowController; import org.apache.beehive.netui.pageflow.annotations.Jpf; @Jpf.Controller( simpleActions={ @Jpf.SimpleAction(name="begin", path="page1.faces") } ) public class ExampleController extends PageFlowController { @Jpf.Action( forwards={ @Jpf.Forward(name="success", path="page2.faces") } ) public Forward goPage2() { Forward fwd = new Forward("success"); return fwd; } } There are two actions in this Page Flow: a begin action that forwards to page1.faces, and a goPage2 action that forwards to page2.faces. The reason for making goPage2 a method action (rather than a simple action) is because you'll be expanding on it later. When you construct your pages, you should create page1 and page2 with the ".jsp" extension; the JSF servlet processes each ".faces" request and ultimately forwards to the associated JSP. So forwarding to "page1.faces" will end up showing your page1.jsp, which looks something like this: <html> <body> <f:view> <h:form> <h:panelGrid> <h:outputText <h:commandLink </h:panelGrid> </h:form> </f:view> </body> </html> Raising an action from a JSF page is simple; just use the action name in the action attribute of a command component. In the example above, the commandLink points to action goPage2. With Page Flow integration, this means that the goPage2 action will be run in example.ExampleController. That's it. To try this out, build your application and hit, which forwards you through the begin action to page1.faces. Click the "Go to page 2" link, which will raise the goPage2 action and will take you to page2.faces. The Page Flow framework can manage a "backing bean" that is associated with your JSF page. This class is a convenient place for event handlers and state that are related to the page. Think of it as a single place to put all the code that runs when you interact with the page. When you hit a JSF page, Page Flow will determine if there is a class with the same name and package, for example, class example.page1 for page /example/page1.faces. If such a class exists, and if it is annotated with @Jpf.FacesBacking and extends FacesBackingBean , it will create an instance of it. When you leave the JSF page by going to an action or any other page, the backing bean will be destroyed. The backing bean lives and dies with your JSF page. Here is a very simple backing bean for page1.faces, with a property "someProperty." The filename is page1.java: package example; import org.apache.beehive.netui.pageflow.FacesBackingBean; import org.apache.beehive.netui.pageflow.annotations.Jpf; @Jpf.FacesBacking public class page1 extends FacesBackingBean { private String _someProperty = "This is a property value from" + getClass().getName() + "."; public String getSomeProperty() { return _someProperty; } public void setSomeProperty(String someProperty) { _someProperty = someProperty; } } In your JSF page (page1.jsp), you can bind to this property using the backing binding context: <h:outputText The example above displays the value of someProperty (ultimately calling getSomeProperty() on the backing bean). Setting the value is similar: <h:inputText Note that in this example, no event handlers or component references are present in the backing bean. This simply shortens the code; a backing bean is a great place to put all your page's event handlers and component references!
http://www.oracle.com/technetwork/articles/entarch/integrating-jsf-beehive-090260.html?ssSourceSiteId=otnes
CC-MAIN-2015-18
refinedweb
1,016
57.27
Hi, I have wrote a program that allows me to enter the length of an oblong and then the height of an oblong and then it calculates the Oblong length, Oblong height , Oblong area, Oblong perimeter. For example: Please enter the length of your oblong: 20 Please enter the height of your oblong: 20 Oblong length is 20.0 Oblong height is 20.0 Oblong area is 400.0 Oblong perimeter is 80.0 Code: public class Oblong2 { public static void main (String[] args) { /* declare two variables to hold the length and height of the oblong as input by the user */ double oblongLength, oblongHeight; // declare a reference to an Oblong object Oblong myOblong; // now get the values from the user System.out.print("Please enter the length of your oblong: "); oblongLength = EasyIn.getDouble(); System.out.print("Please enter the height of your oblong: "); oblongHeight = EasyIn.getDouble(); // create a new Oblong object myOblong = new Oblong(oblongLength, oblongHeight); /* use the various methods of the Oblong class to display the the lenght, height, area and perimeter of the Oblong */ System.out.println("Oblong length is " + myOblong.getLength()); System.out.println("Oblong height is " + myOblong.getHeight()); System.out.println("Oblong area is " + myOblong.calculateArea()); System.out.println("Oblong perimeter is " + myOblong.calculatePerimeter()); } } Now I want to make this so that I am able to input the length and height of two oblongs and then see a message on the screen saying which one, if any, has the greater area. Any help would be appeciated. Hi Buddy, Your logic is fine but I feel that you can acheive at what you asked if u make use of the object oriented concept well. I'm assuming that you want to make use of the same class and create two objects and check which one's area is greater. If this is the case then you have to shift the entire logic(calculation of perimeter and area) into the class definition and then create two objects of the class in the main function and then retrieve their areas and compare them. Thats it. I suppose your requirement will be over if you do that. You can ask me if I'm not clear. Good Luck :-) Thanks Narayana. WillisTi, You also may wish to check your computation of area and perimeter. What you have calculated there is the area and perimeter of a rectangle (which is larger than an oblong). So if you're doing this for a class project, you may wish to plug in the correct formula. Thanks for your suggestions Forum Rules Development Centers -- Android Development Center -- Cloud Development Project Center -- HTML5 Development Center -- Windows Mobile Development Center
http://forums.devx.com/showthread.php?135943-creating-my-own-linked-list-class-very-new-to-this&goto=nextnewest
CC-MAIN-2014-52
refinedweb
443
63.29
Hello everyone, Recently we got chance to work on excel download/upload/open functionality from CRM UI. In result table view of custom application we have some field of type hyperlink, on click of these hyperlink fields we have to display different data of customers in excel form. The issue we were facing that the open of excel was working only first time means when we were opening excel on click of hyperlink field it was opening perfectly only for first time but second time none of hyperlink field was working. Event if we were opening same excel twice , it was not working. I searched this issue on SCN and find number of incomplete threads on the same , so just sharing a small solution that is working fine to remove this issue. We are using callback class approach to open excel and using window.open() method in .HTM page to oprn excel URL. After preparing all data in callback class when we were opening the URL from HTM page with Window.open() , system was considering the every URL as same one. So to remove this one we have to pass unique URL every time on click of any hyperlink field. so in HTM page we change our final URL as:: <script type = “text/Javascript” language = “Javascript” > <% IF lv_our_URL is not initial. %> Window.open(“<% lv_our_url %> , <% sy-uzeit %> “); <% Clear lv_our_url. endif . %> </script> Above code made URL unique each time and open excel without any issue. Hope it will Help. Regards, Harish kumar. Good one Harish
https://blogs.sap.com/2015/11/09/common-issue-when-open-excelurl-cache-issue/
CC-MAIN-2018-05
refinedweb
253
73.68
Creative Boycotts CeBit Over MP3s 195 underwhelm writes "According to ZDNet, Creative Labs is boycotting CeBit because the trade show has banned all MP3-related devices, presumably at the behest of the 'content industry.'" panic: kernel trap (ignored) Re:Unverifiable (Score:2) if you'll note carefully, that is a fault on all of their pages, currently. I'd send them an email telling them they have a problem but they 1) are probably aware of it 2) i can't access their email contact page because of the following error message: Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server] The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. /global/inc/banner.asp, line 192 Unintentional Troll. (Score:1) Re:MP3's are like guns (Score:1) I like the way you threw my comments back at me. Very witty. To put my original point in a more precise way - Associating MP3s with guns is a fucked idea. Sorry, this is about as off topic as I get. go molest someone else. Re:MP3's are like guns (Score:1) Re:...Or is it the other way around? (Score:1) no make that, you got *the* point :-) Re:Not hardware...and BTW, blame Sony for this... (Score:1) Here's 10 minidiscs and a player; here's an MP3 player with 64Mb of Ram for the same price. Now, the minidisc gives 740 minutes of play time, and the MP3 player, say 90minutes. Now, you can get more expensive HD MP3 players but watch the price shoot up. See... *price* *performance*... Re:ONLY THE ORIGINAL ENCODER WAS "PROPRIETARY"! (Score:1) Fraunhaufer is relatively benevolent right now, because MP3 users are armed with the power to change format, and so they have ot be. But the history of GIF and others (esp. trademarks) teaches us that as soon as the power shifts into the hands of the corporation, the benevolence will end. So that's why I say burn all mp3s. ZD Net didn't do their homework? (Score:1) Someone Put A Leash On The Music Industry (Score:1) I think it's really sad when record companies are stifling technological innovation just because it means the end of the Big Five screwing artists and the consumers by getting fat on big profits. If CD's weren't the price they were today chances are you would be worrying less about piracy and the "threat" of MP3 to the current order of things. MP3 is the format that puts the power back to the artist and the consumer where it belongs. You can't stop it, so the only smart thing to do is not to fight it but to roll with it. Take advantage of the MP3 explosion. If MP3 is so widespread then use it to spread word about new music (like MP3.com) and to make more money. But unless the Big Five pulls their head of their ass then they'll suffer the consequences. Self Bias Resistor "You'll never need more then 640k of memory." -Bill Gates Re:Not hardware...and BTW, blame Sony for this... (Score:2) No, but I'm not spreading FUD, unless by FUD you mean truth. > Not true. You have 2 routes, convert to ATRAC, or wrap the file with a SDMI compliant > wrapper which leaves the file in MP3 format but lets the player handle it like any other file. Fine, so there is an alternative to the ATRAC conversion--an alternative which *STILL* requires an extra, unnecessary, step. So, my point stands, since either way it's adding unneeded complexity. Is there any reason that to use an mp3 you already have, you would have to wrap it in SDMI bullshit? Umm, no, since you already have the mp3 in a non-SDMI format, there is no logical reason to impose this highly useless step. Bah. >>This takes time and effort and makes the files almost twice as large as a normal mp3. > > Nope. ATRAC is as efficent, if not more so than MP3 than file compression. Yes, ATRAC is efficient; but you, evidently, are not. Had you been paying attention, you would have seen that I was talking about converting an existing mp3 file to ATRAC for use with Sony's badly designed mp3 players, mp3 players which do not in fact play standard mp3s since you have to either convert the mp3 file to ATRAC or, as you pointed out, give it an SDMI wrapper. Converting an mp3 file into an ATRAC file causes the file size to nearly double in many cases--I suppose this is a result of recompressing the file into an entirely different compression format. > You are > obviously repeating half remembered stuff from other No, you are obviously not paying attention. I'm repeating what I know FROM PERSONAL KNOWLEDGE. I'd never buy one of these Sony monstrosities, but a friend of mine has one that I've played with. Yes, from personal experience, recompressing an mp3 into ATRAC can double file size. I didn't even know the option existed to put an SDMI wrapper around an mp3 file and use that instead of ATRAC, which means that the software is either extremely bad or the type of Sony player my friend had doesn't have this option (I believe Sony makes at least 3 "mp3" players). > It can be suggested that > it will take twice the space because you'd have 2 copies of the file, one wrapped/ > converted, one unwrapped. No, as I said you're just not paying attention. Try to read *before* you flame, kay? >>They obviously want to make it more complicated than necessary to use their mp3 players, > > Insert CD. Select autocheckout. Press record. Player loaded. Hey, maybe you should > try using the stuff first? I never mentioned ripping from CDs to the mp3 player, something fewer people would want to do than to just download to the player mp3s which are already on his HD. As I said, using existing mp3 files is a pain in the ass. Why should they have to be converted first? Because Sony wants to make it difficult to use mp3 players, so that everyone will stay with/switch to MiniDisc. Sony needs to make one themselves to compete with the other companies making mp3 players, but that doesn't mean that Sony wants to make them easy to use; Sony has a long history of discouraging products even as they make them, to try to get people to switch to formats they better approve of. Umm, remember Beta, and how Sony tried to get everyone to switch from VHS to that but prices were never on par since Sony demanded royalty fees for each Beta-format product, whereas VHS was more affordable because Sony wasn't milking everyone? >> so that customers will switch back to CDs and MiniDiscs. > > You mean them minidiscs which offer better price performance than MP3? Now you're just being retarded, comparing a type of media to a file format. Well, mp3s could easily be stored on MiniDiscs, you know. And, how pray tell do MiniDiscs offer better price/performance than mp3 players? Last time I went to Best Buy, MiniDiscs were pretty damned expensive. I could buy a whole spindle of quality Imation 12x 80min CD-Rs for the same price as a paltry few MiniDiscs, thanks to Sony's insane licensing fees. News flash: MiniDisc is losing, because of Sony's excessive royalty demands, just like consumer Beta lost for the same reason. MiniDisc devices have been out for far longer than mp3 players have, but with that huge advantage they haven't conquered the market. And, they won't, because of Sony's greed over their pet proprietary formats. mp3 players are getting cheaper and gaining larger capacities, but I have yet to see any significant evolutionary developments in MiniDic players. Sony's SACD format will fail for the same reason, especially since other companies are moving towards DVD-Audio; why should they pay Sony to license SACD, when they can use DVD-Audio for free (the major labels are all part of the DVD Consortium). But, I digress. My point stands about Sony's mp3 players being unnecessarily complicated in requiring ATRAC or SDMI conversion for existing mp3 files, and I continue to support my statement that Sony is supporting mp3 players half-heartedly, to try to take marketshare away from real mp3 player manufacturers like Creative and Diamond, while simultaneously using a poor implementation to try to leave consumers with a bad taste in their mouths which they'll unfairly blame on mp3 devices in general instead of on Sony in particular. What's the basis for making laws? (Score:1) A good indicator of a corrupt government is the number of laws they pass - they gain a lot of power by making everybody a criminal in one form or another. Then, for example, if a group of people is peacefully protesting the government, they can shut them up by arresting them on other charges. This is a dangerous position to leave the government in. We need to speak up and have unjust laws overturned - the DCMA, UCITA, drug laws, encryption laws, and other vicimless crimes (including punching someone in the dark -- Codecs are dangerous things! (Score:2) Codec's are software, software is the implementation of an idea, and ideas are _very_ dangerous things if you are the status quo. ---- Remove the rocks from my head to send email CeBIT did *not* ban Creative or MP3. (Score:5) As someone who has worked on CeBIT as booth personnel, let me tell you that multimedia booths are a real problem. There are regulations against too loud exhibitors, but many companies on CeBIT don't care. The organizers are now trying to enforce these rules a little bit more. CeBIT did *not* ban Creative, but *Creative* decided not to be there. Instead, Creative will be on next years' largest German consumer fair, the "Funkausstellung". This fair is not a specific IT business fair, but targets your average TV / vcr / dvd / stereo / videogame consumer. I *am* getting a bit nervous about Slashdot's namecalling recently. ------------------ Re:Corporate bashing trash (Score:1) Corperation's first responsibility is to thier sock holders. It is all well and good that they can be on the right side here but it is thier job to make money. Not to uphold the rights of computer users. Horses (Score:1) I bet that back in the day, the average person felt that Justice was on his side. Nowadays, Justice is half crap-shoot / half payola. The real Threed's --Threed NOT a boycott, NOT a censorship case. (Score:1) CeBIT [cebit.de] is a business-, not a consumer-oriented trade show, or at least the makers want it to be. Since Creative's plans involved (again) to have a very large, very loud booth praising their consumer-devices, CeBIT told them they couldn't do that. That specifically. Creative pulled out entirely, and booked IFA [ifa-berlin.de] instead. CeBIT has since changed its mind, but Creative don't want to change their plans again, understandably enough. Details at (for example, this is in German): Re:MP3 we love thee (Score:1) Following the same reasoning... (Score:1) YEAH! Re:BULLSHIT. MP3 IS EXPENSIVE. VERY. (Score:1) For a player that fits into the world envisioned by Thomson & Fraunhofer IIS-A, it's really not that expensive to make a cool MP3 player... ...like this one that I've been working on lately [pjrc.com]. <shameless plug> </shameless plug> ONLY THE ORIGINAL ENCODER WAS "PROPRIETARY"! (Score:1) Fraunhaufer had the original encoder. That's where the stickiness is. You can get non-proprietary encoder, which LAME is now. Maybe they renamed the program now it is its own encoder. All the encoder really is is a piece of software that decides which parts of the signal should be represented in the compressed file. The format decoders are totally free of proprietary IP and patents, IIRC. Some are shareware, freeware, GPL, although some are totally closed source payware, but no decoder pays royalties to read the format itself. Some might to use someone else's code tree though. There is a significant difference. SDMI enabled formats are definitely proprietary in every way and are far worse in this respect. Re:Go Creative! (Score:1) Re:AUGH!! NO! (Score:1) There are also plugins available for most mp3 players to use it, so you may want to give it a try. After all, it's completely unencumbered by patents, and it doesn't look like big business will try to get ahold of it just, so you can still feel like a rebel. Re:Serious Case of Product Discrimination & Prejud (Score:2) Re:ONLY THE ORIGINAL ENCODER WAS "PROPRIETARY"! (Score:1) Are there any patent restricitions other than the Fraunhoffer encoder? I haven't heard about it. AFAIK the Fraunhoffer encoder is the *only* proprietary thing about it, and Fraunhoffer *already* tried to crack down on its use. The encoder is only a human-psycho-acoustic model for stuffing the best bits into the file. Build your own psycho-acoustic model and encoder and you are set, AFIAK. Maybe you know more about the math than I do, but that's long been my impression. I support a move to make a totally free audio format, but in my opinion, the only reason corporate pressure will be applied to removing MP3 is to move us to much more *closed* formats rather than try to milk the MP3 for cash, because they want to milk some closed format for even more cash. Also, I was wrong on something else you didn't notice, I think it's an ISO standard, not IEEE, part of the MPEG-1 standard. Remember that? MPEG-1 Layer 3? The ISO reference code has some of Fraunhoffer's work and that's how these encoders got out in the first place, the reference code was freely available. Banning a codec?! (Score:3) I just can't believe it...What would you think if SIGGRAPH banned jpeg? This insane! Beware the dangerous codec!!! Re:ONLY THE ORIGINAL ENCODER WAS "PROPRIETARY"! (Score:1) There is an MP3 IP FAQ [a-net.nl] which answers the question "16. If I don't use their source, can I make my own MP3 encoder without paying FhG?" with "If you infringe on their techniques, it is within their rights to seek recourse, whether or not you had help from them, or whether or not you intentionally or knowingly infriged." As to my claim that it may not be mathematically possible to create an MP3 encoder without infringing Fraunhaufer's patents -- I was just repeating what I have heard from many knowledgeable people. I doubt anyone has proved that it is impossible, but the bottom line is that nobody has done it yet, and the best policy is probably to refrain from using MP3 until someone does, if someone does. Or how about this: just don't use any patented encoders. That includes all existing MP3 encoders, so you'd better stick with OGG! For a complete overview of the MP3 patent situation see this page from mp3-tech.org mirrored on LAME's site: ht tp://javatest.a-net.nl/servlet/pedit.Main/http:// w ww.mp3-tech.org/patents.html [a-net.nl]. Select quote: "You can try to write an MP3 encoder without using this [Fraunhaufer's patented] encoding scheme, so in this case you will not have to pay, but it's obvious that it's nearly impossible." the enemy of my enemy is my friend (Score:2) Just watch your back. Conspericy (Score:1) At the time I was like "How could technology be illegal".. Now I'm putting this all together... That was the launch pad for a sinister plot to strip us of advanced technology. To allow government agentcys to deside what we can and can not have. Eventually technology will be regulated by an agentcy like the FDA or FCC... Who will deside what medications you can have or who can brodcast and what they can broudcast. They will strip you of your freedoms.. Deside you can not have things like encryption and eventually even deside you can not publish certen information on the Internet as it could be used to instruct terrorists. They may even go so far as to require computers at ISPs so they can scan e-mail or implant back doors in software so that they may spy on other governments. I tell you the day is comming when you don't buy software but rent it.. When you don't buy a computer but get it as part of a pacage deal with your Internet provider... I tell you they may even go so far as change the way TV is broudcast... We must stop this madness... log into your local BBS and send FidoNet mail to Presedent Ronald Regan about the potental treat to the future of techology... I mean when they are able to have portable digital file players I want mine.... Note: This is a joke... Please note the diffrence between what the slashdot editor says and what the artical submitor said... In the case of this story... Slashdot didn't say a word... Anyway... It looks to me CeBit is basicly saying "No more MP3s" as a way to make the booths quieter. They are basicly trying to get rid of the consummer stuff and return to busness and kinda pushed Creative off to the home show... a smaller show that really isn't paying off... It's not really about MP3s.. it's about being loud during a busness expo... For the love of God , Mp3's are not illegal! (Score:1) Must give kudos to Creative though, surely others will follow suit. What bullshit. -- Re:Are there any computers at CeBit? (Score:1) Electrical wiring... even structural technologys... Hmm I guess we'll be holding this expo in a cave... animal skins only.... AUGH!! NO! (Score:3) Please, think about the future. Consider Vorbis [vorbis.org] instead. It's "out of the frying pan and into the fire" if you stick with MP3. [remember the patents?] MP3 we love thee (Score:5) Finally one of the panel stood up and said. I'm sorry, MP3s are here you're too late. There is hardware available, consumers like it and it has already been adopted as the defacto standard. You have no place to decide whether it gets adopted or not. I stood up and clapped. Re:MP3's are like guns (Score:1) CeBit fair = professional NOT ENDCONSUMER (Score:1) It seems that the fair agency tried to suppress the presentation of MP3 Players in relation to ENDCONSUMERS. Creative stated that a presentation for business purposeses is NOT LIKE CREATIVE WANTS TO PRESENT THEIR DEVICES. I can understand this move pretty good. The fair agency wants to keep the CeBit fair as a "professional" fair for business to business relations. Several years ago the Cebit has become more and more a fair for games and the average age of visitors dropped. This lead to an inacceptable bias for any professional visitior. The solution was to split the Cebit up into CeBit (professional) and Cebit Home (Endconsumer). Yey for the boycott! (Score:1) $.02 Re:MP3's are like guns (Score:1) I've owned guns and shot guns since I was 5 years old and never had an incedent where someone was harmed. I've owned and used a hammer since I was 5 years old and done more harm to my self with it than I care to mention. But then I've also killed more deer with a car than I've killed with a gun ( I only shoot competition ). So those are only my personal facts but it seems to me that mp3 are as safe as a gun to me. Neither has caused any harm when I was around. In fact both have caused me to spend money that I would not have otherwised spent. Re:RIGHT ON CREATIVE! (Score:1) Re:AUGH!! NO! (Score:1) Re:Banning a codec?! (Score:1) err... they banned DeCSS, why not MP3? Re:Go Creative! (Score:1) More modern drives have a "digital audio out", which does digitally encoded audio to the soundcard, but I'm not sure if it's really an exact copy of the CDDA data It is an SPDIF output, thus a perfect copy of the digital data on the disc (there is a copybit thing though, but it's not difficult to get rid of it) ...Or is it the other way around? (Score:2) I think I'll boycott Cebit too. (Score:3) Re:MP3's are like guns (Score:5) Not hardware...and BTW, blame Sony for this... (Score:3) I myself got the Live! Value OEM, and am very happy with it. I just wish I could have afforded the Live! Platinum, since the LiveDrive is both cool and useful. I mean, having all those audio connections mounted on a front drive bay is just plain cool looking, plus I'm always reaching behind the computer to switch audio connections anyway since I use it for a DVD player (Hollywood+ cards rock). But, the very idea of banning any mp3 players at CeBit is just disgusting. I mean, it's just a type of audio player, which you can use with your own paid-for CDs after all, just as you can legally make a mix tape or CD from CDs and tapes you bought. Funny how they're not banning MiniDisc devices, since they can be used to pirate music too with any soundcard that has an SP/DIF connector--just decompress the mp3s and burn them to MiniDisc. But, oh, wait, Sony makes a fortune from every MiniDisc device and media sold, so it's okay to have them present. And yes, Sony makes mp3 players, but half-heartedly--after all, at least one of their "mp3 players" requires that mp3 files be converted to the proprietary Sony "ATRAC" format before downloading them to the player. This takes time and effort and makes the files almost twice as large as a normal mp3. They obviously want to make it more complicated than necessary to use their mp3 players, so that customers will switch back to CDs and MiniDiscs. And, am I the only one who notices the ironic sound of "ATRAC," so similar to the doomed "8-track" format? Arrgh, the more I learn about Sony, the more I start to think that they're the most evil corporation this side of the future "Disney's AOL/Time-Warner" which I'm convinced will happen one day... They introduce a proprietary format for everything, in the attempt to keep people from using better, open formats--like trying to get their new 1.3GB CDs to be used by consumers instead of the better DVD and DVD-R formats which they are actively trying to hamper. But, I digress. All I can say is, you can bet that Sony had a hand in ensuring that mp3 devices would be banned from Cebit. I personally buy nothing Sony, and nothing by another brand which I know is made for them by Sony. Re:Not about rights or freedom (Score:2) Agreed. Creative is doing the right thing for the wrong reasons, which in my mind is about the same as just doing nothing. Except that doing the right thing for the wrong reason has the potential to actually accomplish something, whereas doing nothing doesn't. If Creative receives support from the people who want the right thing for the right reason, it will encourage other companies to join the boycott. That would be a good thing, even though those companies would also be doing it for the wrong reason. TheFrood Clap Clap (Score:2) *applause* I believe the geek/hacker/techie community is a great group of people for a company to have on their side - in general we have a large amount of disposable money to frivolously spend on expensive gadgets and gizmos, and I believe listen pretty well to word of mouth about the quality of a company's products. MP3 format illegal? (Score:2) I mean, if its in MP3 format, then i guess it should automatically be made illeagal [sic] right? If you're not an MP3 patent licensee [mp3licensing.com], yes. But there's always the patent-free Vorbis [vorbis.com] codec. <O ( \ XGNOME vs. KDE: the game! [8m.com] I asked CeBIT; here's what they said (Score:3) Thank you very much for your e-mail! We would like to inform you that we in fact never banned MP3 Players or the MPEG storage format from CeBIT. There will be around 25 companies in hall 9 this yearshowing MP3 players. ObviouslyCreativeLabs released a press article serveral days ago, saying that they are cancelling the CeBIT becausewe excluded MP3players from our nomenclature. This isdefinately not true and wedo not understand the reasons for such an article. Sincerely Deutsche Messe AG Interesting, no? BULLSHIT. MP3 IS EXPENSIVE. VERY. (Score:4) Commercial decoding: 15k annual pre-pay + 2.50 / item shipped. Commercial encoding: Their object code: 15k annual $250k minimum $5.00/copy shipped Their patents: 15k annual $2.50/copy shipped. This is US dollars. I hardly consider this "free" by any means. They have over 13 patents on the format alone, who cares if you can encode it? You can't USE it unless you pay! Our project was scrapped because of these costs, and management's inability to grasp that there are other formats. Vorbis is free. Period. You can get and change the code. You can make free players. You can make commerical players. You can use it in your other products. No one will come after you with a team of lawyers for not paying for Vorbis. I get sick of hearing about how "open" mp3 is. Re:MP3 we love thee (Score:2) And the Clue Meter reads 11 (on a scale of 1 to 10 -- I borrowed Spinal Tap's meter). CeBIT Website and Contact Info (Score:3) -- Re:Why on earth.... (Score:2) 1. Old, slow executives who are too tired to learn a new way of doing business. 2. Young, cynical lawyers and consultants who are making a mint by telling those in group 1: "Yes, you can stop MP3s. By the way, here's my bill for last month." It makes me wonder if anybody hung around on the Titanic, selling pails. Francis Hwang Don't forget... (Score:2) Re:Not hardware...and BTW, blame Sony for this... (Score:2) but its not a true spdif output. its resampled. meaning: the internals of the card force a resampling of even the most common rate (44.1k) to the internally required 48k. yes, the spdif out will drive an outboard DAC or a DAT deck, etc. but regardless of what the input samplerate is, the output is ALWAYS 48k ;-( the sample-rate conversion is a bit noisy and adds noticeable distortion. don't ask me why they resample up to 48k when 99% of all the audio sources out there are cd-based which is 44.1. sigh... -- Re:Go Creative! (Score:2) the digital audio out (of most modern ide cdrom drives) is a bastardized form of spdif. its the spdif logical frame format but the physical levels are TTL rather than the real standard of 0.5v p-p. but for most devices that take spdif-in, the TTL levels are ok and will work. and yes, it is a bit-for-bit extraction of the audio frames; its just that its 1:1 speed; ie, realtime. for better than realtime, you need to use a drive that has dae (digital audio extraction). its worth noting (for you power rippers out there) that very few cdrom changers will support DAE. I wonder why that is? is it because DAE is "just barely tolerated" by the bigWigs? and if you put the power of DAE into a changer, that could cause ALL SORTS OF CHAOS out there? makes me wonder.. but at any rate, you could use the spdif out of the ide cdrom drives as a last resort to get digital audio without an intermediate analog step. -- Re:Why on earth.... (Score:4) Exactly. Just like Marijuana is illegal, as are "bongs." And we know nobody uses those right....right? There's only one thing more powerful than big business - and that's the will of the people. When the public is divided, politicians can do whatever they want. In this case, i think we all know where the public stands (the vast majority, at least) - all the corporate money in the world won't save a politician once he's been voted out of office. FluX After 16 years, MTV has finally completed its deevolution into the shiny things network Re:Not hardware...and BTW, blame Sony for this... (Score:2) Good, now let's tell Creative we're happy. (Score:2) Oldthink thinkcrime doubleplus ungood all mp3 related devices? (Score:3) does this include sound cards, speakers, hard drives, RAM (which is evil because it loads mp3's partially into memory before playing them)?? FluX After 16 years, MTV has finally completed its deevolution into the shiny things network Re:MP3 we love thee (Score:2) [ogg vorbis for digital audio] [xiph.org] MP3's are bad mmmmkay! (Score:3) This is not simply stupid, or careless, it's just plain WRONG! This is just another case of people assuming that MP3's themselves are bad! ***NEWSFLASH - MP3 is just a FILE FORMAT*** Regardless of how people use it, MP3's and all their associated gadgets have done nothing wrong, they are a part of technology as much as anything else! I say "go Creative", because it's about time that someone, or some company had the guts to take a stand! In fact, we should all take a stand, because I've had about enough of this. I like to be able to listen to all my songs without changing CD's. I also like to be able to have a backup of them all on one CD and on my HDD! It's time we showed some support for this move and all Boycott CeBit too, and instead use the time and money to go out and buy a Nomad! Power to the People! "How much truth can advertising buy?" - iNsuRge [insurge.com.au] - AK47 Good news for IFA (Score:2) So does that mean... (Score:2) A car analogy would be more appropriate (Score:2) I would choose a car analogy instead because MP3 has much more in common with a vehicle (maybe a pizza delivery van Also, I think most people can better identify with the ownership/usefulness of a vehicle. numb Re:Go Creative! (Score:3) Did the VCR destroy the movie industry? Sadly, no. Did the tape recorder destroy the music industry? Um... no. *Damn* Did CD Burners kill the CD music business? Nooooo! *SOB* Cease your cruel, cruel taunts! Will the CD-ROM drives that allowed Digital Audio Extraction kill the CD market? Will MP3 do it either? WE CAN DREAM, CAN'T WE?! Seriously, these technologies are not "okay" because the music and film industries will still rake in bucketloads of money despite them. Rather, they are "okay", period-- even if Jack Valenti and Edgar Bronfman are left sharing a tin of tuna warmeded over a back-alley fire. Sorry, dreaming again. Re:According to the local press... (Score:2) In fact the splitting of CeBit didn't go exactly according to plan, most see the business part as the real thing and don't see sense in visiting what's mostly a big advertisement for the newest games/gadgets. So most people still go for CeBit (not "CeBit home") as can be seen from the fact, that there's really a lot of people there at Weekends while real business is done mostly in the week. Re:MP3's are like guns (Score:2) According to the local press... (Score:5) CeBit is currently a large fair, in fact it is the larges computer trade show on earth. Hannover cannot longer take all the people. CeBit tried to split the show into a consumer show called "CeBit Home" and tried to promote the curent CeBit as a strictly business tradeshow. They have not been doing well: CeBit Home is actually shrinking, and many consumer product specialists are showing on the main CeBit. Specifically: Creative undermined their marketing strategy at the last CeBit by having a loud and gaming oriented booth at the supposedly business oriented main CeBit. CeBit directorate wanted Creative to switch over to CeBit home, but Creative was not interested into a shrinking low profile fair. Re:Why on earth.... (Score:2) > Just like Marijuana is illegal, as are "bongs." And we know nobody uses those right....right? Which means that if you're carrying a bong which tests positive for once having had marijuana smoke passed through it, you get busted for "drug paraphenalia". Likewise - owning an MP3 player will be fine. Owning a computer will be fine. But owning an MP3 player will be probable cause for an officer to seize the computer and examine it for MP3 files. Even if you've deleted the MP3 files, if they can recover evidence (e.g. old bytes in the FAT portion of the disk) that the MP3 files were there, you go to jail. > In this case, i think we all know where the public stands (the vast majority, at least) - all the corporate money in the world won't save a politician once he's been voted out of office. Support for marijuana legalization is remarkably high in the US. Please explain why no major political candidate supports legalization. Even a small portion of the corporate money in the world appears to be quite sufficient to thwart the public's will. Re:MP3's are like guns (Score:4) Ohh, righty then, we better call for some new laws then ... -- Why pay for drugs when you can get Linux for free ? Well good for them (Score:3) It's nice to see the larger players in the whole multimedia finally saying out loud that the whole MP3 thing is getting way out of hand. The RIAA are doing everybody a massive dis-service by their actions. What I find very offensive is that an American company's whinging and bitching is telling me what I can and can't do here in Australia. Still, money buys influence just as well in Australia as it does in the US, so I shouldn't be surprised. Re:Why on earth.... (Score:2) 1) Never doubt the power of government(s) making something illegal. It would only take a couple of major governments together (the US, the EU, AU/NZ, and Japan) declaring that all A/V file formats MUST support digital rights management, possibly implemented under WIPO so countries have very little choice in passing laws to support it, for this format to be declared wiped from all servers. And when your shoices are A) Delete it or B) 5 years in jail... Lots of people will choose A. If it is not listed on US/EU search engines, it will drop off the public radar fairly quickly, and only be available on slower offshore servers. Still there if you search for it, but much less easily available. 2) Ditto with #1, declare the format illegal, and you cannot manufacture or import devices that support that format in(to) the country. Without a device to buy, consumers will find something else that fulfills the same basic purpose. There are 2 or 3 competing audio file formats that are suitable for consumer devices, and support DRM. 3) Frankly, businesses are more concerned with controlling what consumers want, through marketting/PR and other means, and selling controlled products, than in creating new markets... Large entrenched businesses, at least. Why do you think the first MP3 player wasn't from Sony? The CeBit organizers are people that depend on the goodwill of the major electronics/entertainment industry firms. This means that when most of the big members of an organization like the MPAA or RIAA says "Don't support this format" the trade show organizers will listen. No overt threats, no bribery, just a large powerful organization making known its wishes. ZD Net UK tells the story differently from the US (Score:2) Re:Go Creative! (Score:2) When you "play an audio CD" on a standard old-school CDROM in a machine with some old soundblaster, the CDROM drive itself processes the CDDA data into an analog audio signal, which is then passed to the soundcard through that little CD audio cable like any line-level audio signal. More modern drives have a "digital audio out", which does digitally encoded audio to the soundcard, but I'm not sure if it's really an exact copy of the CDDA data. There's there Digital Audio Extraction (DAE), which is the ability of a drive to allow software to directly read the bitstream of an audio file from the CD disc as if it were a file. While most newer CDROMs support this feature on their buzzword list, many have compatibility problems in the real world, which makes finding a "good" CDROM drive for DAE (for converting later to MP3) a bitch sometimes. While we're talking about boycotts... (Score:2) Bruce Well, of course. (Score:4) And everyone knows that MP3s and related technology are'nt enjoyed by people that will spend rediculously large percentages of their personal income buying gadgets, right? Its just a fad, and its a good thing that the MPAA and its friends are keeping the research going on 8-tracks, as thats where its at. -- Crutcher -- #include <disclaimer.h> Re:MP3's are like guns (Score:2) You are obviously properly trained in the use of guns. But lets take someone who isn't properly trained in guns, and isn't properly trained in MP3s. They could harm someone with a gun, but not with an MP3. That's why guns aren't as safe as MP3s. --- RIAA wants to push SDMI? (Score:3) MP3's are like guns (Score:3) ------------------------------------------ If God Droppd Acid, Would he see People??? Re:RIGHT ON CREATIVE! (Score:2) Do as I say, not as I do. I have all those CDs on my shelf too :P Serious Case of Product Discrimination & Prejudice (Score:2) Isn't this illegal somehow? If I have a product - a perfectly legal product - which I want to sell, why can't I showcase it an industry meeting? I wonder what other past technologies this HIGHLY-QUESTIONABLE practice has been able to stifle? So, whoever owns CeBit gets to decide the course of the industry and not the industry itself? This sticks to high heaven. -- Ironic (Score:2) It's ironic that you mention that--with your apparent Netscape background.. I was using Netscape 5PR2 for Windows .. Your expertise required: Bug with Netscape 5PR2 returning a nonstandard header? or careless programming on Creative Labs' end? Mozilla/5.0 (Windows; U; Win98; en-US; m17) Gecko/20000807 Netscape6/6.0b2 Re:Ironic (Score:2) Sorry .. Requested, not Required Banned Shmanned (Score:2) All I'm saying is instead of bitching, maybe we should all get up and start to do something. Lets organize a serious boycott of the companies who are pulling these tactics, bug our friends and family until they too participate, do whatever you can to squash these assholes. Look, Napster may be violating their rights to a degree (like they haven't been fucking us in the ass for years), but it's unstoppable, and to make these blanket attacks on consumers and even manufacturers is out of hand. Re:MP3 we love thee (Score:2) Just a quick question... (Score:2) what kind of hold could RIAA have over CeBit (apart from Sony pulling out) to get CeBit to ban any and all MP3 related devices from the show? Surely there are manufacturers other than Creative who have a vested interest in this as well... M@T Re:Not hardware...and BTW, blame Sony for this... (Score:2) Why on earth.... (Score:3) 1) The software exists. There is no way mp3 encoding/playing software is going to go away. 2) The hardware exists. Plenty of mp3 players have been sold, and continue to be sold. There's no basis for a lawsuit against hardware manufacturers, as there's nothing remotely illegal about playing or creating mp3s. 3) Consumers *love* mp3. Isn't the whole point of business (and by extension, trade shows) to create, market, and sell products and services that consumers want? This seems to indicate that either the CeBit organizers or some MAJOR participants had a very good motive to get mp3 devices off the floor. Bribery or stock deals (really just another form of bribery) wouldn't surprise me. Perhaps one of the exhibitors will be showing off some new audio encoding technology and use the fact that they're the only thing being shown to impress people? Thank You Big Brother (Score:3) Still, I feel a great need to send a big hug and kiss to the people at Creative Labs. Even if your beating on the bully for your own reasons... the little guy who got his milk money taken last week will still be there to laugh and enjoy it. I'll start taking it like a man when I'm done crying Not about rights or freedom (Score:2) Creative is doing the right thing for the wrong reasons, which in my mind is about the same as just doing nothing. Re:...Or is it the other way around? (Score:2) Er, yeah, but ever heard of Creative's Nomad line of portable MP3 players? The most popular players out there? I suspect that's a bigger concern for them. Re:Minidisc is expensive? (Score:2) Getting media on a spindle doesn't mean it's not high-quality; Imation, for example, makes a very high quality disc, and uses the same discs on its spindles that it uses in its nice slimline cases. On sale, you can get them sometimes for as little as $30 for 50. And, the media will last in excess of fifty years, and probably closer to a century, without bit-rot. There was a story on You're right that not all burners can use an 80-min CD-R to full capacity, but that's pretty much irrelevant since most people aren't using 4 year old 1-2x CD burners. My own Craetive burner was purchased two years ago, and has no problem with them. But, even very, very ancient CD players will be able to use an 80-min audio CD--I have a walkman from when I was in high school which plays them glitchlessly. Aside from which, a good CD burner and a decent portable CD player cost less new than a new MD player/recorder. If you want to go the uber-cool route, you could shell out a few more $$ and instead of getting a plain-Jane CD player, get something like a portable Encino Voyager CD MP3 player--easily fitting 150 high-quality mp3 recordings (192kbps or greater) onto a single medium. And contrary to the FUD surrounding the issue, mp3 sound is as high quality as most other compressed formats, probably including ATRAC. The key is to remember that bitrate affects audio quality immensely--a 128k mp3 will sound flat and dull on even a mid-range stereo system, if you're an audiophile; but, a 192k mp3 sounds as good as a CD on a high-end system, unless you have better hearing than most people do; and, anything greater than that sounds indistinguishable from CD audio even to highly skilled audiophiles with great hearing. I believe Ars Technica did an mp3 comparison which touched on these issues. Personally, I use HQ VBR mp3 encoding, which varies the bitrate up to 320kbps and down to 96kbps as necessary, depending on the demands of the stream at any given time. It produces absolutely flawless sound, as good as any CD. So, claims of CD-quality sound are absolutely true, if you create a high quality file. I find plenty of them on Napster, too, so I'm not the only audiophile who's keen to this. The resulting files are usually about 6-10MB, depending on bitrate--HQ VBR can produce smaller files than 256kbps files, and often they're even smaller than 192kbps files. And, you can call it piracy if you want, but I gleefully download any songs older than 14 years without any concern for copyright since the Constitution specified a copyright term of 14 years, and the extensions to this have been gained by heavy-handed and too-powerful corporations acting against the interests of the people. I also don't feel *too* bad about downloading new stuff from companies who are responsible for the DMCA and other extensions of copyright against the public interest. The only CDs I purchase any more are from bands who actually deserve my support, like Kittie, Chuck D, and people affiliated with indie labels. The music industry--and by that I mean the big corporations who are witholding IP from the public domain indefinitely, whereas it was originally supposed to be public domain after a reasonable 14 year term--don't deserve my money for abusing and taking away the rights of the people to public domain IP, but we *do* deserve to take from them since they withold IP which should rightfully be in the public domain. As David Boies, Napster attorney who was instrumental in the DoJ's case against Microsoft, pointed out, if a company or group of companies abuses its copyrights to gain or illegally exploit a monopoly, they lose their legal rights to those copyrights. I have nothing against the MD formet in itself--it's Sony's control of it I dislike, and that's why I will never use it. Sony tried to control us with Beta, they tried to prevent resale of CDs, and they're making a very flawed version of mp3 players, and they are among the worst offenders of the DVD Consortium and one of the multinationals responsible for the DMCA. I don't trust them, and in fact hate the world they want to create, where all content and IP is encrypted, rented, and no one can touch it but them. I've been to CeBIT last year... (Score:2) And the reason? To protect the content providers? That's absolutely crazy. Most people who buy MP3 players actually do mostly use them to play music from their own CD collection, or maybe one or two songs snatched from Napster. I don't understand how a huge and influential organisation like CeBIT could possibly decide to ban all MP3-related stuff from their fair. Now that Creative is boycotting CeBIT, I'm pretty sure others like Diamond and Thomson may follow. And then suddenly CeBIT isn't the biggest computer fair anymore... Oh, if anybody does go to CeBIT despite all this, don't forget to check out the Münchner Halle. Ugly waitresses, but good beer and a nice stereotypical German atmosphere )O( Never underestimate the power of stupidity Re:Gotta watch it with them codecs (Score:2) )O( Never underestimate the power of stupidity Ogg Vorbis (Score:2) What I plan to do is rip the surrond tracks from my dvds when ogg reaches maturity, and encode them for playing through a computer. What I _really_ would like to see is a CAR STEREO that has surround sound cabability. I mean, they're ALREADY hooked up to front and rear left and right. If I had a car stereo that could play ogg AND was surround sound aware, that would be just spiffy. "What a waste it is to lose one's mind. Or not to have a mind is being very wasteful. How true that is" Re:RIAA wants to push SDMI? (Score:2) Re:MP3 we love thee (Score:2) Ogg works now in WinAmp, Sonique and XMMS. For WinAmp it's as easy as downloading a plugin and double clicking the With plans to allow streaming ogg it can almost become a drop in replacement for MP3. SDMI requires it's whole authentication sceme to play files. The real barier to entry in a case like this is not the format but the changes the end users have to make. With Ogg there is little to none. With SDMI the end user is forced to adopt a new way of thinking about the music they listen to. Re:short article (Score:2) You can't even say that. :) The Diamond Rio is by, well, Diamond. (Who have recently been absorbed into S3) Creative's players are the Nomads. Go Creative! (Score:2) We don't have to take this crap from these steenking artists any more. Did the VCR destroy the movie industry? Did the tape recorder destroy the music industry? Did CD Burners kill the CD music business? Will the CD-ROM drives that allowed Digital Audio Extraction kill the CD market? Will MP3 do it either? Isn't this crap obvious??????!?!@#!@# RIGHT ON CREATIVE! (Score:2) Represent the customers by declining to go to a trade show that doesn't want to display what they want. Another sign that the RIAA will eventually have to bow to popular demand - we got our music, and we aren't going back to the stone age on account of "intellectual property" or "copy protection", regardless of what congress belches out or how illegal they make it. The revolution has begun! --
https://slashdot.org/story/00/09/12/2057216/creative-boycotts-cebit-over-mp3s
CC-MAIN-2017-17
refinedweb
8,421
71.75
Groovy: Best Practices Developed From Distributed Polyglot Programming Recorded at:. About Groovy Gotchas by Sargis Harutyunyan class Name { String id = "Sargis" } def name = new Name() println name.id println name.getId() println name['id'] def c = 1 println c.getClass().getName() def b = 1.1 println b.getClass().getName() def a = 1.1d println a.getClass().getName() ============================================================================ Output groovy> class Name { groovy> String id = "Sargis" groovy> } groovy> def name = new Name() groovy> println name.id groovy> println name.getId() groovy> println name['id'] groovy> def c = 1 groovy> println c.getClass().getName() groovy> def b = 1.1 groovy> println b.getClass().getName() groovy> def a = 1.1d groovy> println a.getClass().getName() Sargis Sargis Sargis java.lang.Integer java.math.BigDecimal java.lang.Double seems everything is ok Avoid list.each{}, prefer for (a in list) by Olivier Gourment Hello stranger!You need to Register an InfoQ account or Login or login to post comments. But there's so much more behind being registered. Get the most out of the InfoQ experience. Tell us what you think
http://www.infoq.com/presentations/Groovy-Best-Practices/
CC-MAIN-2014-49
refinedweb
177
73.24
Related Reads Web Scraping with Python Part 1 – The Basics August 31, 2017 6008 Social Media Can be a Threat To Your Information S ... June 26, 2018 By: Cofense Inc. 187 Very few coding activities expose us to so many exciting technologies at once – the web (HTTP/HTML/XML/CSS/JS), data mining, NLP, and security (IPS/WAF evasion) like the Web bots. Yet, with the proliferation of the automated tools and Google, this once mainstream skill is becoming either black hat only or too “old-school”. None of this should be the case and in this series of tutorials I will introduce you, who has never done it before, to the web scraping and show how easy and exciting it could be. By the end of this series, you will have programmed and gained knowledge enough to write your own decent web scrapers suited for the ideas of your own. This series will cover: LEGAL ADVICE: I am not a lawyer, so my only legal advice for you is, do NOT do anything that may require you to look for legal advice. The best way to follow it – use anything I talk about only on a system you own, which is very easy to have today – virtual machines, your own website. On the real life experience side of things, web scraping is NOT illegal by itself. After all, the scraper does mostly what the website owner allows it and meant to do – requesting website pages. The problems start when a bad scraper shows at the website doors. By the ‘bad scraper’ I mean the one which behaves way too aggressively and differently from a regular human browsing the site. I will talk about making our scrapers neighborhood friendly but still, it is not a guarantee that the site owner will be happy with it, so to be on a safe side read my ‘legal advice’ above. In addition, any scraping can be made illegal by the ‘Terms of Service’ agreement enforced by a website which explicitly prohibits using automated tools for whatever reason or way. Why use web scrapers (or don’t we have browsers for that)? The web scrapers, also called web bots, web spiders, screen scrapers, web crawlers, site downloaders and web site mirror downloaders have actually existed since the very Internet became commonly available. Httrack, one of the most popular open source scrapers, has been available starting 1998. The very first web crawlers were the search engines themselves which proved so crucial to the usability of the Internet. The reason to have them today are many, ranging from very legitimate to very illegitimate, there are few things people do with them based on real life cases. Legal ones: Illegal ones: But can’t we just use browsers, especially with built-in scripting? Yes and no. Yes, we can browse manually or use iMacros/Autoit and other tools we can script standalone browsers as well to some degree, but this has few disadvantages. They require a user to use them, even if automated they don’t scale well, they don’t have ‘brains’ or logic built in them, so the user has to decide what is relevant for her and what is not, the speed of retrieving data is also incomparable slow. Web scrapers make weaknesses of a browser their strengths. What (do scrapers do)? That is simple – given the website, they crawl all of its pages following internal and (optionally) external links, saving the content to where you want to. How do they do it? They connect over the network to the server hosting the website, request via HTTP protocol some page(s), parse them to distinguish between the content and HTML/XHTML/CSS mark up, save the content locally to a file or a database, extract links from the pages, follow them and do the whole sequence again. Assumptions: you know basics of Python or any other programming language, the code will be very essential and therefore easy to understand, no object oriented programming, no complex data structures (linked lists/stacks – hey, we are having fun and not surviving a CS course!), the error checking/exception handling will be done when needed. All the code will be posted also in a Github repository here Software used: Websites used: Ok, enough with theory, let’s code something. We will start with the 1st step in any web scraping, that is connecting to a server and requesting its home page. We have many modules and possibilities here, but to start simple we do it with a standard urlopen module and de-facto standard module requests. The 1st one is installed by default but we have to download the requests module. My personal tip – for learning purposes I always use Anaconda from free package distribution which is ideal for experimenting with Python code and also makes installing packages just a matter of search/click/install. I highly recommend it, especially if you don’t have the already set up environment to use it for learning. The usual way will do as well: `#pip install requests` While we are on it go ahead and install BeautifulSoup 4 (BS4) as well: `# pip install beautifulsoup4` Task 1: Connect to the server using both HTTP and HTTPS, request its home page, and check for errors in doing so. NOTE: If the code gets formatted badly look in the Github repository I mentioned. Using standard module urlopen: Solution 1.0: `from urllib.request import urlopen from urllib.error import HTTPError def getSinglePage(url): try: rawPage = urlopen(url) print(rawPage.read) except HTTPError as ee: print(ee.reason) print(ee.code) return None urlToGet = r’’ ourPage = getSinglePage(urlToGet)` First, we import the needed functions to retrieve a page, also getting access to the errors it can potentially produce. Next, we create a function getSinglePage() to get us a page from the supplied URL, it is better to start separating functionality into functions from the very beginning. This function uses urlopen() function which returns object representing the retrieved page from the server. Then we invoke read() to read the page content and print it to the console. If some error happens we catch it with the built-in HTTPError object in the except part of the function. We can even know the exact error by printing its response code (part of HTTP standard – the 200 means ok, 404 being the dreaded Not Found error) with .code property and its string explanation with .reason property. I introduce error processing for a reason – the errors in retrieving data happen all the time, and your scraping code has to account for them. Some errors may be ignored, some should be acted upon. If you decide not to process errors – your scraper won’t go too far. We will just notice the errors for now. Finally, we use this function getSinglePage by supplying it with the URL . You will notice that we got the page as a stream of not formatted printable bytes. That is the good and the bad of urlopen library – it is more low level than requests library and expects us to make most of the decisions. One of the decisions is about the encoding of the retrieved page – urlopen assumes nothing, you have to explicitly tell it. The requests, on the other hand, look at the server HTTP response header and uses this advertised encoding to represent the page. Let’s see the difference by adding manually encoding for the page which in this case is UTF-8 and using HTTPS on the way: Solution 1.1 from urllib.request import urlopen from urllib.error import HTTPError def getSinglePage(url): try: rawPage = urlopen(url) print(rawPage.read .decode(‘utf-8′)) except HTTPError as ee: print(ee.reason) print(ee.code) return None urlToGet = r’’ ourPage = getSinglePage(urlToGet) As you see the page is formatted much better now, this is to show that the advantage of urlopen is in being standard module while the disadvantage is it requires more manual work. Switching to https is just a matter of specifying HTTPS in the URL. We will do the same task with the requests module: Solution 1.2 import requests def getSinglePage(url): try: rawPage = requests.get(urlToGet) print(rawPage.text) except: print(rawPage.status_code) print(rawPage.reason) urlToGet = r’’ getSinglePage(urlToGet) The differences are: Today we have learned to connect to a server by HTTP/HTTPS and request the page specified in a user-supplied URL. In the next lesson we will continue with our best friends urllib and requests and learn to extract hyperlinks from web pages and then use them to build a small link verification bot. Resources: – Code – my site with Web scraping/crawling and other recipes in other languages like C# / C Donate Here to Get This Month's Donor Badge Did You Know? Cybrary training is FREE Just create an account now for lifetime access. Members login here. We recommend always using caution when following any link Are you sure you want to continue? thank you for sharing this. This is great content I look forward to your next installment! Thanks, already working on the 2nd one, the idea is to progress it slowly to the more complex/production-level scripting, as there are enough one-time web scraping how-tos on the Net already. Awesome, can’t wait! Glad you like it, thx.
https://www.cybrary.it/0p3n/web-scraping-python-part-1-basics/
CC-MAIN-2018-43
refinedweb
1,563
61.06
Five cscope Tips By meem on Dec 27, 2009 At Sun, we primarily use a tweaked version of the venerable cscope utility which has origins going back to AT&T in the 1980s (now freely available from cscope.sourceforge.net). As with many UNIX utilities, despite its age it has remained popular because of its efficiency and flexibility, which are especially important when understanding (and optionally modifying) source trees with several million lines of code. Despite cscope's importance and popularity, I've been surprised to discover that few are familiar with anything beyond the basics. As such, in the interest of increasing cscope proficiency, here's my list of five features every cscope user should know: - Display more than 9 search results per page with -r. Back in the 1980s the default behavior may have made sense, but with modern xterms often configured to have 50-70 rows the default is simply inefficient and tedious. By passing the -r option to cscope at startup (or including -r in the CSCOPEOPTIONS environment variable), cscope will display as many search results as will fit. The only caveat is that selecting an entry from the results must include explicitly pressing return (e.g., "3 [return]" instead of "3") so that entries greater than 9 can be selected. I find this tradeoff more than acceptable. (Apparently, the current open-source version of cscope uses letters to represent search results beyond 9 and thus does not require -r.) - Display more pathname components in search results with -pN. By default, cscope only displays the basename of a given matching file. In large codebases, files in different parts of the source tree can often have the same name (consider main.c), which makes for confusing search results. By passing the -pN option to cscope at startup (or including -pN in the CSCOPEOPTIONS environment variable) -- where N is the number of pathname components to display -- this confusion can be eliminated. I've generally found -p4 to be a good middle-ground. Note that -p0 will cause pathnames to be omitted entirely from search results, which can also be useful for certain specialized queries. - Use regular expressions when searching. While it is clear that one can enter a regexp when using "Find this egrep pattern", it's less apparent that almost all search fields will accept regexps. For instance, to find all definitions starting with ipmp_ and ending with ill, just specify ipmp_.\*ill to "Find this definition". In addition to allowing groups of related functions to be quickly found, I find this feature is quite useful when I cannot remember the exact name of a given symbol but can recall specific parts of its name. Note that this feature is not limited to symbols -- e.g., passing .\*ipmp.\* to "Find files #including this file" returns all files in the cscope database that #include a file with ipmp somewhere in its name. - Use filtering to refine previous searches. cscope provides several mechanisms for refining searches. The most powerful is the ability to filter previous searches through an arbitrary shell command via \^. For instance, suppose you want to find all calls to GLDv3 functions (which all start with mac_) from the nge driver (which has a set of source files starting with nge). You might first specify a search pattern of mac_.\* to "Find functions calling this function". With ON's cscope database, this returns a daunting 2400 matches; filtering with "\^grep common/io/nge", quickly pares the results down to the 12 calls that exist within the nge driver. Note that this can be repeated any number of times -- e.g., "\^sort -k2" alphabetizes the remaining search results by calling function. - Use the built-in history mechanisms. You can quickly restore previous search queries by using \^b (control-b); \^f will move forward through the history. This feature is especially useful when performing depth-first exploration of a given function hierarchy. You can also use \^a to replay the most recent search pattern (e.g., in a different search field), and the > and < commands to save and restore the results of a given search. Thus, you could save search results prior to refining it using \^ (as per the previous tip) and restore them later, or restore results from a past cscope session. Of course, this is just my top-five list -- there are many other powerful features, such as the ability to make changes en masse, build custom cscope databases using the xref utility, embed command-line mode in scripts (mentioned in a previous blog entry), and employ numerous extensions that provide seamless interaction with popular editors such as XEmacs and vim. Along these lines, I'm eager to hear from others who have found ways to improve their productivity with this exceptional utility.
https://blogs.oracle.com/meem/tags/solaris
CC-MAIN-2014-10
refinedweb
796
60.85
Registered users can ask their own questions, contribute to discussions, and be part of the Community! Registered users can ask their own questions, contribute to discussions, and be part of the Community! Hi! I would like to create a connexion to my ES cluster which is exposed on port 80 behind a reverse proxy with "es" prefix. (So it can be accessed on). Below is the code that I would use in Python to create the connection. How can I configure that in the DSS GUI ? There doesn't seem to have any url_prefix field. Thank you very much for your help ! Christophe from elasticsearch import Elasticsearch, helpers # Connection to ElasticSearch es = Elasticsearch([{'host': 'my-domain.com', 'port': 80, 'url_prefix': 'es'}]) As mentioned in support ticket you also opened, this is not currently possible to configure such connection (with prefixes in front of the ES API) in DSS UI. We marked this for the R&D team review for future enhancement. As a possible workaround, you might want to configure your proxy to have an entrypoint like that redirects to. Then use es.my-domain.com in the elastic search config. Thank you for answer and advice. Best regards. Christophe
https://community.dataiku.com/t5/Setup-Configuration/Connecting-DSS-to-an-ElasticSearch-cluster-with-url-prefix/td-p/17397
CC-MAIN-2022-40
refinedweb
200
66.94
. 4 thoughts on “Python for 3ds max – Select objects of type” If you wanted to do it all in the pymxs api instead of using maxplus you could do it this way btw: import pymxs rt = pymxs.runtime # find exportable as the node has geom somewhere def get_all_children(parent, node_type=None): def list_children(node): children = [] for c in node.Children: children.append(c) children = children + list_children(c) return children child_list = list_children(parent) return ([x for x in child_list if rt.superClassOf(x) == node_type] if node_type else child_list) # getting only the first selected item sel = rt.getCurrentSelection()[0] kids = get_all_children(sel, rt.GeometryClass) # lights would be # kids = get_all_children(sel, rt.light) You could of course move the type filtering out like you have as well, but I thought this would be a handy thing 🙂 Thanks for the tip! 🙂
https://odederell3d.blog/2020/02/11/python-for-3ds-max-select-objects-of-type/
CC-MAIN-2022-40
refinedweb
137
62.58
I need to generate a table based on what r equals at different theta values. I am easily able to graph and show the equation with matplotlib, and was hoping that there was an easy way to: give numpy the theta variable, my curve equation, and viola, return the r value I tried to look at the documentation of numpy but am having a hard time finding what I need. import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np mpl.style.use('default') # Number of Points Ploted # Change this numer to affect accuracy of the graph n = 3000 theta = np.linspace(0, 2.0*np.pi, n) def show_grid(): plt.grid(True) plt.legend() plt.show() # Setting the range of theta to [0, 2π] for this specific equation theta4 = np.linspace(0, 2*np.pi, n) # Writing the equation curve4 = 5*np.cos(64*theta) ax1 = plt.subplot(111, polar=True) ax1.plot(theta4, curve4, color='xkcd:cyan', label='CURVE 4: r = 5cos(64θ), [0, 2π)') ax1.set_ylim(0,5) ax1.set_yticks(np.linspace(0,5,6)) show_grid() The above code produces a graph nicely, but: Can I use the same variables to return r at theta? It is in general not guaranteed that the array of theta values actually contains the value you want to query. As an example consider Now you want to know the value of r at theta0 = 2.5, but since that value is not part of thetait has no corresponding value in r. So you may decide to find the value of r at the theta that comes after theta0, in this case 3 is the next value in theta after 2.5, so you might be looking for r == 6, Or you may want to interpolate the r values on theta, in this case 2.5 is halfway between 2 and 3, so you are looking for 6.5 which is halfway between 7 and 6, Or more generally, you have an actual function, which defines r(theta). Here, The last case for your example would look like
https://techqa.club/v/q/returning-r-at-different-theta-values-with-numpy-c3RhY2tvdmVyZmxvd3w1NTc4Nzk4Mw==
CC-MAIN-2021-39
refinedweb
349
72.05
There are C++ behaviors that may leave you a bit astonished, staring at the lines on the monitor and wondering why the code isn’t compiling, or doesn’t work as expected. Just stumbled in one of these cases. I usually follow these steps to recover from the puzzled face. First I write a minimal example that reproduces the behavior. It should be a bunch of lines in a single file. Sometimes this could be a daunting task, but I have that it is always worth to grasp the problem. In fact, once you have the minimal code, you can easily experiment, changing and twiddling bits to see how the behavior changes. Then you have two options – you can ask your local C++ guru about the problem (if you have one), or you can google the Internet for a clever selection of keywords that describes your problem. So what happened today? I decide to move some code I developed into a namespace-constrained library. Everything compiled happily outside the namespace, but failed to do so in the namespace. After some headscraping, I started cutting and shaping a minimum file with the same odd behavior. Here you are: /** prova.cc * * @author Massimiliano Pagani * @version 1.0 * @date 24/04/2007 * * @notes * @history * */ #if defined( USE_NAMESPACE ) namespace NS { #endif class A { public: private: struct B { int x; }; friend bool fn( B const& b ); }; #if defined( USE_NAMESPACE ) } using namespace NS; #endif namespace NS { bool fn( A::B const& b ) { return b.x != 0; } } Now, if you compile it defining the symbol USE_NAMESPACE (e.g. via g++ -Wall -DUSE_NAMESPACE -c prova.cc), then you get the odd looking error: prova.cc: In function 'bool fn(const NS::A::B&)': prova.cc:21: error: 'struct NS::A::B' is private prova.cc:31: error: within this context While if you compile without the namespace everything works as expected. Since the error was quite meaningless to me, I started investigating on friend and namespace. After some mailing list browsing, I figure it out. And it was simpler than what appeared – just a case for a misleading error. In fact the friend statement declares a function fn somewhere in the NS namespace, while actually fn is defined in the global namespace. In fact there is just a using statement. To fix the problem, just move the fn function into the NS namespace. Well and I have figure it out alone, without the need of calling my uber-C++-guru friend Alberto. On a completely unrelated topic, today is the 25th anniversary of the marvelous ZX Spectrum. Happy Birthday Dear Speccy.
https://www.maxpagani.org/2007/04/24/friends-and-namespaces/
CC-MAIN-2019-09
refinedweb
433
66.03
Answered On : Jun 27th, 2005 Can i get the ans fr the question Question : How do you write a program which produces its own source code as its output? Answered On : Jul 16th, 2005 /* Program to printf itself on console */ #include int main(void) { FILE *in; clrscr(); if ((in = fopen("8.c", "r")) == NULL) { printf("Cannot open input file.n"); return 1; } while (!feof(in)) printf("%c", fgetc(in)); fclose(in); getche(); return 0; } Answer Answered On : Jul 27th, 2005 Howdoes return1 and return 0 differ? Answered On : Sep 3rd, 2005 'return 0' indicates program is ended with no error and 'return 1' indicates program is ended with error. Answered On : Sep 12th, 2005 #include<stdio.h> #include<string.h>#include<stdlib.h>int main(int args,char **argv) { char filename[20];int i=0,k=0;FILE *in; while(argv[0][i] != '\0')if(argv[0][i++] == '\\')k=i;printf("%d",k);for(i=0;argv[0][k] != '.';i++,k++){filename[i] = argv[0][k];}filename[i] = '\0';strcat(filename,".c");if ((in = fopen(filename, "r")) == NULL) { printf("Cannot open input file.n"); return 1; } while (!feof(in)) printf("%c", fgetc(in)); fclose(in); return 0; } Answered On : Oct 10th, 2005 Main() { char *a="main() { char *a=%c%s%c; char b='%c'; printf(a,b,a,b,b); }"; char b='"'; printf(a,b,a,b,b); } Answered On : Jul 21st, 2006 #includemain(){ FILE *p; p=fopen("filename","r"); if(p==null)exit(1); while(!eof(p)) { printf("%c",*p); p++; }getche();} Answered On : Aug 3rd, 2006 Hi, There are So many complex methods for that but i write the most effective and simple one just write this ..// program name avi.c#include<stdlib.h>void main(){ //// write ur program logic heregetch();system("type avi.c");}by the use of this system function from stdlib.h u can run any dos command from ur c program but please check the output for this only by running the exe of ur program ( in this case avi.exe)Regards ,Avinash Chaturvedi( Avi ) Answered On : Mar 14th, 2007 All the solutions above are reading the source code with the files concepts.find a solution where you do not have a source file to read the contents.There is a macro or an attiribute which tells the compiler the name of the program, function or the attribute. You can use that to get the source code. try out...!!! Answered On : Jun 28th, 2010 View all answers by praveensaini23 #include <stdio.h>int main(){char ch;FILE *file;file=fopen("printitself.c","r");while((ch=fgetc(file))!=EOF)printf("%c",ch);return 0;} If you think the above answer is not correct, Please select a reason and add your answer below. Data Modeling Data Structures OLAP OOPS UML What are the career opportunities available for MCA Graduates? How do you deal and overcome major challenges? Describe a time when you had to listen to someone. Do you seek advice from others when you have a question? What are my options when I do not get a job after graduation? How to handle academic gap while applying for a job? How productive are you? Do you have any questions that you want to ask? Describe a time when you had to convince a friend ?.
http://www.geekinterview.com/question_details/14384
CC-MAIN-2014-41
refinedweb
549
66.64
We all cringed, then laughed when Dr. Mark Serreze of NSIDC first said it, then marveled about it as it got a life of its own, being the buzzphrase for every alarmist who wanted to shriek about declining Arctic sea ice. In 2007 we heard him say: “The Arctic is screaming,” said Mark Serreze, senior scientist at the government’s snow and ice data center in Boulder, Colorado. So far, the “screaming” hasn’t kept anyone awake at night, and we have not returned to the low of 2007 in the last three melt seasons. In 2008 Serreze made the bold claim: The ice is in a “death spiral” and may disappear in the summers within a couple of decades, according to Mark Serreze, an Arctic climate expert at the National Snow and Ice Data Center in Boulder, Colorado. And in 2008 we had the forecast from NSIDC’s Dr. Mark Serreze of an “ice free north pole”. As we know, that didn’t even come close to being true. Summer 2008 had more arctic ice than summer 2007, and summer 2007 was not “ice free” by any measure. With those failed predictions behind him, in an interview in The Age just a few weeks ago, Serreze pulled a Harold Camping, and changed his prediction date. Now he’s saying the new date for an ice free summer is 2030. ”There will be ups and downs, but we are on track to see an ice-free summer by 2030. It is an overall downward spiral.” Now from a most surprising source, Andy Revkin at the NYT, a strong statement saying he’s not buying it anymore: On Arctic Ice and Warmth, Past and Future. ….) He’s referring of course to this paper we covered here on WUWT: New study suggests Arctic ‘tipping point’ may not be reached I wrote then: This is interesting. While there’s much noise from alarmists that we are on an “Arctic death spiral” the team for this paper’s press release today found evidence that ice levels were about 50% lower 5,000 years ago. The paper references changes to wind systems which can slow down the rate of melting (something we’ve seen on the short term, even NASA points this out for recent historic ice retreats). They also suggest that a tipping point under current scenarios is unlikely saying that even with a reduction to less than 50% of the current amount of sea ice the ice will not reach a point of no return (i.e. a tipping point). 115 thoughts on “Quote of the week – death of the Arctic “death spiral”?” But Revkin is a denier, and so is anyone who reads him. The truth only comes out of the mouths of Joe Romms. We all know that. (Oh wait wrong forum!) I am tired of all these so called scientists and so called journalists who write with such apparent certainty but with so little knowledge. So Revkin reads an article and suddeny he’s ‘not worried’. All he ever writes is knee jerk reaction ….. but without any basic knowledge. It annoys me that such basic concepts as geological scale climate variability seem to have eluded him till now. Anyone who had thought about the Holocene Optimum and what it might mean in todays context would have much greater informational base and analytical rationale on which to make commentary on todays observations. Maybe he should spend 3 years doing an undergraduate geology degree before he writes anything else. Wow, a seemingly rational about-face for Revkin. But “may disappear in the summers within a couple of decades” from 2008 to, “…new date for an ice free summer is 2030”, isn’t different at all. As per the ancient Chinese proverb …whenever a rabid warmist comes out with yet another dire prediction all one has to do is sit comfortably on the banks of that river called The Internet, and soon the corpse of that dire prediction will float by. Interestingly he mentions ‘alarmists’ in such a way that it clearly doesn’t include himself. Does that mean that Mr Revkin is now prepared to read science such as Spencer & Braswell 2011? Svensmark?? Friis-Christensen & Lassen??? If he accepts a low climate sensitivity (as the data strongly supports) then he maybe about to experience a Damascene climate event. Good luck Mr Revkin! If you are willing to look at the science objectively I hope it goes well for you and that your asbestos suit is in good repair. Ah, it was you Anthony who used ‘alarmists’, sorry I misunderstood. Still if Mr Revkin is edging himself away from the death spiral fraternity maybe there is still hope. He also said in 2008: “So even without special conditions like those seen in 2007, next summer could set a new record low, he added. ” Fail. An actual scientist should be VERY CAUTIOUS about proposing any sort of “tipping point” or “death spiral”. The fact that life continues to flourish on Earth after an uncountable number of shocks and perturbations is perfect evidence that the whole system has an uncountable number of negative feedback loops. There are small local positive loops (death spirals), but the remainder of the system always compensates. If it didn’t, we’d be just like the Moon by now. But the Arctic ice IS reducing. It will all be gone in 10 years, or 20 years, or …. Everybody knows that, and anybody who doubts it is an oil industry schill. This is like the ‘Hockey Stick’. It is divinely inspired truth that can never be refuted. Everybody knows that, and anybody who doubts it is an oil industry schill. [sarc off] Richard Two NASA scientists scare us that the arctic could be ice free by 2013, one is Serreze. I would be very careful and not laugh too much, Anthony. You have already been more wrong about the Arctic than Serreze will ever be. When can we expect your next SIN? 2011 is trailing 2007 big time and the Antarctic mega-anomaly has subsided. REPLY: “SIN” ? Oh that’s right, it is about religion now that Gore has been officially declared a prophet. Thanks for the confirmation. – Anthony Somehow this part of the opening was missed; ‘There are big changes afoot, with more to come should greenhouse gases continue to build unabated in the atmosphere. There will be impacts on human affairs in the Arctic, for worse and better, as we explored extensively in 2005 and I’ve followed here since.” And “The main source of my Arctic comfort level — besides what I learned while camped with scientists on the North Pole sea ice — is the growing body of work on past variations*” * So in other words the changes we’re seeing now are from a different source that past variability. Anthony – you are doing a great job, and if I was a US citizen you would get my vote for the next (since Eisenhower) “No B-S President” The money shot: “They also suggest that a tipping point under current scenarios is unlikely saying that even with a reduction to less than 50% of the current amount of sea ice the ice will not reach a point of no return (i.e. a tipping point).” How many blunders must an ‘expert’ make before he is declared inept? at best? It seems likely that there was a lot less ice in the arctic in ancient times. I think there is a lot of information in Dutch history that suggests that the sea farers in the 15th and 16th century knew or were led to believe from “their ancient history” that there was a northern passage (to the other side of the world) . Many, like Barents (the most famous) lost their lives trying to find that northern passage. Not to worry, all of you true believers: the ‘precautionary principle’ is already being deployed as your final refuge “on time scales relevant to today’s debate”. It is curious that Revkin never asks the obvious question as to what caused the much larger fluctuations in the past – surely it was not increased level of greenhouse gases given the literature. The fact of the greater historical fluctuations does more than cast doubt on any forward looking “death spiral”. It casts huge doubt on the theory that climate changes in the Arctic are related to greenhouse gas levels. Some far larger driver must exist, and it is incumbent on him to explain why the current cycle differs from former larger ones. Revkin’s comments to the effect that “even as I push for an energy quest that limits climate risk” and “adds credence to proposals for an Arctic focus for managing incoming sunlight as a way to limit greenhouse-driven impacts” appear almost as sops to avoid being ostracized as a heretic. It is this latter aspect of his comments that is most enlightening. When you look at the satellite images of Arctic Sea Ice; the “death spiral” and impending sea ice free arctic seems quite farfetched. There are still several million square kilometers of Arctic sea ice, and, per this Naval Research Laboratory model, which deserves a healthy degree of skepticism; significant portions of Arctic sea ice are still several meters thick. New report just out: ScienceDaily: Titled: Large Variations in Arctic Sea Ice: Polar Ice Much Less Stable Than Previously Thought, Study Finds.. source: So Serreze does have a chance of seeing an ice free arctic, if he rides a time machine and sets the time to minus 500,000 years. LOL Wow. Looks like some in the AGW camp are now looking at the facts. That’s the shocking part. The Arctic has had less ice. It’s had more ice. As I’ve asked several times, would it make it any difference at all if the whole Arctic ocean became ice free? The past tells me there was much less ice than today, perhaps ice free. For example during the Viking era. Yet all the ecosystems managed, and did so without any help from the EPA. The concept of a tipping point for arctic ice extent pre-supposes the existence of at least two stable configurations – our current one, with a lot of ice, and another one with no ice. The whole idea of a tipping point is that it’s a point where a system has been perturbed so far from one stable state that it proceeds into a different stable state. Does the peer-reviewed literature contain any evidence the such a ‘no-ice’ stable system is possible? If Andy Revkin can put his brain into gear and look more deeply at the science then I would call that an encouraging start. Welcome to Chez Sceptic, Andy. Come on in and make yourself at home. You might even find you like it. :D AW your always miles ahead of these AGWers no wonder you get so many hits LOL Warmists are coming to the harsh realizations one after another. Bill Maher even admitted on his show last week that it’s looking like Climate Change might actually be a hoax. MrC The first thing I look for in climate predictions are weasel-words like “might,”, “may,” “could,” etc. Serreze does more for the skeptical movement than most of us commentators here. He’s really a funny guy. The only thing I can say, is “Go Marky go! Amplify from the highest chunk of ice screaming about the death spiral! I’ve never understood this “death spiral” nonsense anyway. Are they saying that, if all the ice were to melt in the summer months, that the winter wouldn’t then go back below freezing and re-freeze the ice? Simplistic example, but if I empty my ice cube tray and refill it with water, it will still freeze. And that’s only at -5 degrees C. And, of course, we all know that the temperature is going to go way below freezing once the winter hits. So, what’s going to prevent it from re-freezing, even if the temperature/currents/whatever actually melt ALL of the ice in a given summer? Maybe one of our resident trolls can put away the snark and actually explain the logic on this, because it makes no sense to me at all. Sometimes I think way too many of the leading Warmista mouthpieces must have received their PhD’s by mistake or they got lucky with a box of Cracker Jacks. I mean really, they either think the rest of the world is stupid and will believe any silly story they make up or they actually believe the such crap and expect us to trust their word because they are know they are important people doing serious work. The general technique is usually to reschedule the date of impending doom, calim that there were a couple of “minor” errors in the sums that led to the wrong date being quoted, then sit back & wait, again, & again, & again, & again &……………………………………………………….! Good to see Andy moving a little closer to the sanity line. Wishing him well in his recovery. The great thing about making predictions for some future event nearly two decades away is there is no accountability for being wrong. That’s the brilliance of the climate models which make “projections” (notice projections, not predictions) for up to a century from now. Few will bother to verify the actual conditions and compare to the prediction or projections and if they do, various excuses will be made for the failure to match the real world. Mark Serreze’s prediction of an ice free arctic in 2008 is one of the earlier ones and reality has called time on that one. The earliest I have found is by Bernt Balchen who made a prediction in 1972 that the arctic would be ice free by the year 2000. Mr.Balchen was described as a leading specialist on the Arctic at that time. He also said that the Northern USA would be 20 to 25 degrees warmer than it is now. National geographic went for 2012, and so they are still in with a chance – but fast running out of time. ..and the good old BBC predicted an ice free arctic by 2013. In addition it said, I think the BBC may discover that predictions are rather tricky things, ‘especially those about the future’. But my favourite, although it doesn’t actually claim the arctic to be ice free, is the 1922 report from the US weather bureau that said “The arctic ocean is warming up, ice bergs are growing scarcer and the water is becoming too hot for the seals”. (Do these links work without me HREFing them?) Revkin was on record that human activity had produced never-before witnessed, disastrous, and accelerating melt in the Arctic, which he strove to bolster by alluding repeatedly (as he does again here) to his trip to the Arctic (with actual scientists!). This is a major climb-down, albeit without the man saying, “I was wrong.” But we know. Oh dear, the Promotion of Warmth will be jumping upon him something chronic. He’s verging upon being condemned as a heretic! Revkin no least!! perhaps the jumping of ships is about to start?? Credit Serreze with the ability to learn from his mistakes. If you’re pimping a bogus theory, don’t make predictions that can be falsified. 2030 is more like it. Sort of like commercially viable nuclear fusion, keep it about 20 years in the future. Once the ice in my glass of coke has melted it never comes back. There’s also CO2 in there. As far as history is concerned, a little knowledge is a dangerous thing. A complete lack, however, can be even worse. Glad he finally thought to ask the obvious question. OT. Only just found this. did David Archibald’s hard line public speech get wuwt coverage? At least 4 months old. [ ] REPLY: Yes VERY off-topic, please refrain. We covered his speech here: – Anthony Isn’t it time you started publishing the Arctic Ice Volume graphs on WUWT alongside all the other data? It’s a glaring omission in an otherwise excellent resource page. I don’t worry over when the sea ice will disappear, in fact, I’ll be happy when it is gone, then, in less then a couple of decades the same alarmists will worry over when the sea ice forms again, I’ll can LMAO for another decade or so. :p The Arctic sea ice is really the only change in the climate that we can definitely point to. Even accepting that, it is not that much of a change. The charts and graphs from the NSIDC are all exaggerated in that the Y-axis does not start at Zero (ie. no ice) it starts at 2 million or 7.5 million or what have you. Here is the NH daily sea ice going back to 1972. It is going to take a long time for the minimum each year to reach Zero on the graph. The September 10th anomaly has to go to -6.1 million while it is only at -1.1 million right now. That is a lot of change and only a small fraction of that has shown up to date. Bomber_the_Cat says: August 9, 2011 at 6:19 am Great post. Thanks. fantasy? “So in other words the changes we’re seeing now are from a different source that past variability.” Variability is variability. It doesn’t matter what the cause, what matters is the effect. Dead is dead, no matter what killed you. The cause of natural variability is ASSUMED to be different, largely because it was ASSUMED that past natural variability was low. As more and more studies show that natural variability is HIGH then that means there is less and less reason to worry about current variability. The polar bears didn’t die out in the past when it was warmer for a period of 3000 years, so it is illogical and thus unscientific to suggest that they will die out as a result of warming today. Those scientists that continues to suggest otherwise are not practicing science, they are engaged in fear mongering to try and drum up continued grants at the public expense. In other words, fraudulent utterances to obtain money. Found this page on the BBC yesterday that WUWT reported previously: The title is: “Arctic ‘tipping point’ may not be reached” Related Stories by the BBC are listed as: New warning on Arctic ice melt 08 APRIL 2011, SCIENCE & ENVIRONMENT Arctic sea ice melt ‘even faster’ 19 JUNE 2008, SCI/TECH Arctic losing long-term ice cover 18 MARCH 2008, SCI/TECH Amazing how quickly opinion can change from “the worlds about to end” to “oh…maybe not “ Climate science 101. The world is going to end in (present day + 20 years) due to (choose: human activity/carbon/co2/pollution) unless we get a grant to solve the problem. All signs point to things getting worse otherwise. Douglas Foss says; It casts huge doubt on the theory that climate changes in the Arctic are related to greenhouse gas levels. well,well, isn’t that what I said “even with a reduction to less than 50% of the current amount of sea ice the ice will not reach a point of no return (i.e. a tipping point).” Yep, there’s always that seed ice that forms every winter when there’s no energy input FOR 6 MONTHS! “Here is the NH daily sea ice going back to 1972. It is going to take a long time for the minimum each year to reach Zero on the graph. ” Assuming that the curve isn’t a cyclical signal. The curve also looks like a curve of the tides just past high tide and could be simply cycling towards low tide, before heading back up. Given that SH sea ice is increasing a the same time, what we could be seeing is simply a long term cycling of warmth back and forth between one hemisphere and the other. Any assumption that the heat between the hemispheres is always balanced is only an assumption. Ocean currents and wind could carry heat from one hemisphere to the other in a cyclical, oscillating fashion. The idea that the heat balance of the hemispheres is constant seems unlikely given that the earth and cosmos is in motion. He must have gotten the memo from big Al G to turn up the heat on the AGW hype machine. We are seeing the beginning of the end of the Warmista. It is coming in exactly the expected way. Climate scientists are reporting results of empirical research and it contradicts Warmista myth. I am so pleased to be able to think about and talk about some observations about driftwood collecting in the Arctic over the centuries. Warmista cared only for computer models and magical statistics. They were totally averse to facts of the environment, except for their outrageous lies in promotional photos of mythical polar bears and such. As someone else mentioned above, this change emphasizes that Anthony Watts has been the bedrock of rationality on the web throughout the debate over hysterical Warmista theses about climate change. Those students of climate science who have taken advantage of WUWT have received a genuine education in science, scientific method, professors, and how all three can become corrupted. The debates within climate science are just beginning because the genuine science of climate is just beginning. My hunch is that climate science will look very much like the work of Roger Pielke, Sr. People like Revkin are taking the opportunity to step down gracefully. Science provides that opportunity. New and original empirical research provides new topics and new takes on old topics. It moves the ball toward the goal. There will be endless opportunities to embrace it. Just about all the Warmista can be expected to take the opportunity to come in from the cold. Can anyone explain to me to me why on the Cryosphere images the purple colours (thicker ice) of 2007 disappears more quickly than the reds and greens (thinner ice) of 2011? I have been watching this with interest over the last couple of months and it is very definately the case the much thicker ice of 2007 melts more quickly than the much thinner ice of 2011. Or is this also to do with wind circulation or is the colour scheme just plain wrong? Hang on a minute. You note that Seereze said in 2008 that arctic ice may disappear in the summers within a couple of decades, and from the the link: With the climate feedbacks kicking in,” Serreze said by email, “we’ll lose the summer ice cover probably by the year 2030.” But then you write: “And in 2008 we had the forecast from NSIDC’s Dr. Mark Serreze of an “ice free north pole”. As we know, that didn’t even come close to being true. ” As we know, 2008 is not 2030. Meanwhile: August 3, 2011 Ar. Way to go Andy ! Bystander says: August 9, 2011 at 4:20 am So in other words the changes we’re seeing now are from a different source that past variability. Oh? And how do you get from here to there with that statement? And do not start off with evidence that CO2 is causing warming in the Arctic. I want you to come at it from the other end. First, you should show me the proof that ‘past variability’ (a strangely undefined term) is not the cause of current ice conditions. Philip Shehan said: “And in 2008 we had the forecast from NSIDC’s Dr. Mark Serreze of an “ice free north pole”. As we know, that didn’t even come close to being true. ” As we know, 2008 is not 2030. Philip, I’d click on the image at the top of this article to take you to the ABC news article and read it if I were you; you’ll find the original quote to which Anthony’s paragraph relates… Cheers Mark Philip Shehan says: August 9, 2011 at 8:32 am “As we know, 2008 is not 2030.” —————————————————————————- The quote that the Arctic might be ice-free in 2008 can be attributed to the ABC news article: “There is this thin first-year ice even at the North Pole at the moment,” says Serreze. “This raises the spectre – the possibility that you could become ice free at the North Pole this year.” After Spencer’s and Braswell’s paper it will be shown that probably ALL excess heat from whatever source is lost so that even DA is now wrong, This Earth is probably self regulating and that’s why we are still here. well, the world is getting warmer, and that heat transports to the arctic and so over the long run you can expect the average minimum ice to diminish. It’s a big old slush puppy now. will it ever be ice free? really not the right question. an ice free Npole some september? really not the right question. For the most part some climate scientists have been search for some iconic way of demonstrating the problem. Some simple statement or image that sells: like…. Ice all gone: polar bears dead. That’s a media agenda. On the science side we can confidently say that in a warming world the arctic ice will see lower minimums on average. We would not expect the ice to grow if arctic SST drop by 5C. If you stick to the core science, rather than the science that tries to find headlines, you’ll do much better. The right question will a long term retreat in minimums have measurable effects or feedbacks. There are not a lot of headlines and pictures for that The worlds getting warmer ( for a host of reasons) in a warmer world we fully expect more heat to be transported northward. More heat northward in general will result in lower minimums. It would be pretty silly to argue against that. Will that decrease happen year in and year out? no, nobody makes that argument. more is at play than simply the temperature, but temperature obviously matters. mycroft says: “Revkin no least!! perhaps the jumping of ships is about to start??” In the past, Revkin has, on rare occasions, rejected some Warmist notions, so this isn’t new behaviour. He’s been subsequently threatened with “the big cutoff,” otherwise he might be a little more of a sceptic. His sincerity is not in doubt. Regarding tipping points, the albedo of water overlaps that of ice at the zenith angles involved at the poles. The T^4 radiation law will ensure refreezing every winter as the Arctic Sea is exposed 24 hours a day to the 4°K blackbody temperature of the night sky. “ThinkingScientist says: August 9, 2011 at 7:48 am (Edit) fantasy? ##### Lets see how that approach to science plays out. If you look at a history of temperatures you will see plenty of ups and downs. for example you will see a dip in 1992. there is nothing out of the ordinary about that dip. Its well within the range of dips and peaks in the past. “natural variability!” But we generally are more curious than that. Looking at the data we see that there was a volcano. Does the volcano explain the dip? well yes, when we apply our understanding of how radiation propagates through the atmosphere we can predict that particles and gases from a volcano interfere with the transmission of shortwave radiation to the surface. We have tested physics models that tell us how EM interacts with particles of various sizes. We use these physics to build systems that defend our country ( for example the physics of radar chaff) . So what do we have here. we have two “explanations” for the dip 1. The “dip” is natural. The dip is not outside the range of past dips. There is nothing out of the ordinary that requires an explanation. TRUE. 2. The dip is explained by the volcano and radiation physics: TRUE. The problem with #1 is that it assumes that all science operates by noticing something ut of the ordinary as a prior condition of investigation. That is, if there is nothing out of the ordinary then there is no need for an explanation. The problem of course is that “ordinary” is not well defined. In the course of the history of earth the range of states for the arctic goes from ice free to full of ice. Nothing will ever be surprising or out of the ordinary. But that’s not how all science works. If you want to understand or explain the current decline, then appealing to “natural variation” is no explanation whatsoever. Its an explanation without any predictive power. Its an explanation that can’t be falsified. Its the absence of explanation, it’s anti science. Sagt Günther Kirschbaum an August 9, 2011 4:12 am Not aware of where Anthony Watts predicted “ice-free summers” by 2011^H3^H6. Citation(s) please? Steven Mosher says: August 9, 2011 at 9:25 am “The worlds getting warmer ( for a host of reasons) in a warmer world we fully expect more heat to be transported northward. More heat northward in general will result in lower minimums. It would be pretty silly to argue against that.” No mention of manmade CO2, computer models, magical statistics, or anything Warmista. Great! This issue has come up numerous times before and despite all efforts to clarify it, it still continues. Discussion in 2008 was that there may be open water at the North Pole in summer – i.e., the ice edge could potentially retreat past the North Pole.. In addition, the possibility of the event was discussed because for the first time during the satellite record, the North Pole was not covered by the thick, 3-4 meter multiyear ice, but rather by first-year ice that was 2 m or less thick. Such ice could have potentially melted, though it was unlikely given the high latitude and perhaps that unlikelihood should have been conveyed more forcefully. Walt Meier NSIDC Walt, I appreciate your attempt to clarify the issue. My best advice is for Dr. Serreze to go on record and say that his statements were more emotional soundbites than scientific, apologize for using them, then provide a quality essay using the best science available, minus such emotional talking points. I’ll give Dr. Serreze full unfettered access to WUWT should he wish to do so, with only one caveat: he can’t call people that frequent here “deniers” nor denigrate them as he has done in the past. Respectful discourse is welcomed. – Anthony waltmeier says: August 9, 2011 at 10:02 am .” With all due respect, Dr. Meier, what do you make of this NOAA press release? Ice-Free Arctic Summers Likely Sooner Than Expected April 2, 2009 Summers in the Arctic may be ice-free in as few as 30 years, not at the end of the century as previously expected. The updated forecast is the result of a new analysis of computer models coupled with the most recent summer ice measurements. — By “ice free” my assumption upon reading the title is that there is NO ICE! No qualifications were used like “mostly ice-free,” “ice edge has retreated beyond …” etc. And by “summer” I would think they are referring to the entire time between June to September. So – no ice in the arctic between June and September, correct? From your comments above, I would assume that you would strongly disapprove of this kind of misleading press release from NOAA – am I correct? Remember these press release are meant for public consumption – not for other scientists (who probably know better). (If you’re wondering why ordinary citizens are so distrusting of climate science, it only takes are few misleading, over-hyped press releases like this from government organizations like NOAA for people to start tuning you out…) In regards to Andy Revkin: I agree, his sincerity is not in doubt — and one should correctly remember that the ClimateGate Gang unsuccessfully attempted to bully him into toeing the line in 2009 –> . … I sense that you are about to experience the ‘Big Cutoff’ from those of us who believe we can no longer trust you, me included. … What are you doing and why?” — email from Michael Schlesinger, University of Illinois professor, to Revkin Andy Revkin, I feel, believes the world is warming, and that mankind’s CO2 emissions are responsible, but generally is one of the pragmatists, calling for mitigation and a huge push on new cleaner energy sources. Not always entirely/at-all impartial, but not a bad guy. I have him on my ‘read daily’ list, for good reason. Andy Revkin’s written work has incrementally moved away from enthusiasm for the concept of “one warm world” with “settled science”. The shift began shortly after the Climategate e-mails demonstrated how the “Team” members, especially Mike Mann considered him a puppet on a string. Even then, Mann was afraid Revkin might try to think for himself. Think, Andy. Think ! “If you lie, lie big. For a little of even the most outrageous lie will stick, if you press hard enough. Never hesitate, never qualify, never concede a shred of validity or even DECENCY to the other side. Attack, attack, attack! Hitler circa 1920 quoted page 38 in “The Third Reich At War” Steven Mosher, Well said. Walt Meier, Well Clarified. ____ I applaud Revkin’s well reasoned article. As discussed in the post about the latest Holocene Climate Optimum sea ice study, it is interesting to see that the sea ice was diminished in the past, and obviously made a “recovery”. But this is really not earth shattering news as other studies have indicated this as well. But to me, what is more interesting is noting the conditions under which this happened. The CO2 levels were about what we had previous to our modern run up, i.e. they were about 270-280 ppm, but we know that was not the cause of the low sea ice, but rather, it was a slightly greater NH summer insolation from the Milankovtich cycles. So our modern era low sea ice must have some similarly strong forcing, and of course, the greater CO2 levels versus then fits the bill quite nicely. But more interesting questions to ask would be: How quickly did sea ice decline during that Holocene Optimum as compared to how quickly it is declining now. This might give some indication of how quickly we might get to an ice free summer condition as well as being able to compare the forcing from anthropogenic GH emissions versus the Holocene Milankovitch summer insolation.. Alex the skeptic says: August 9, 2011 at 4:22 am “How many blunders must an ‘expert’ make before he is declared inept? at best?” Ask Hansen, he has racked up quite a few! Then again, as a blunder draws near they move the goal post…The gift that keeps on giving? Maurizio Morabito says: August 9, 2011 at 3:23 am As per the ancient Chinese proverb …whenever a rabid warmist comes out with yet another dire prediction all one has to do is sit comfortably on the banks of that river called The Internet, and soon the corpse of that dire prediction will float by. Beautiful, I love it! I think you’re missing the point. You are technically correct, however, in your assertion that a recurrance of past climate events does not necessarily mean they have the same cause. However, good scientific practice means we do need to understand what caused these past events and then determine if those same processes are at work now. Do you understand the null hypothesis? It appears that the US Navy takes the possibility of a largely ice-free arctic quite seriously: They’re the folks who will have to sail those waters eventually. No matter the cause, it appears that we are losing ice up there, and this is bound to lead to more shipping (Iceland is planning to become the new Hong Kong!), fishing and, eventually, clashes over resources. I seem to recall a Russian flag planted on the Arctic ocean floor close to the North Pole. Latest North Pole cam shot depicts an iced over lens and what looks to be a decent recent dump of snow. Overcast sky, Nuke says: August 9, 2011 at 12:44 pm R. Gates says: August 9, 2011 at 12:14 pm Do you understand the null hypothesis? ============================================ Yes he does, but like Trenberth, he has his own personal one. Meanwhile, on the other side of the world: Quite an interesting article if you can stomach Nature attempting to plumb new depths of idiocy: “Nature speculated whether “‘glacial tsunamis’ be added to the list of future global-warming hazards” Amazing what happens when you actually start reading scientific papers and putting things in historical perspective….not such a big deal after all. Took a look at Cryospheres Arctic Basin chart. Current ice area in the basin is almost at last years mid-September level. Nuke says: “…a recurrance of past climate events does not necessarily mean they have the same cause.” As Nuke points out, the null hypothesis assumes that a recurrence of the same events has the same cause, barring evidence to the contrary. Gates, on the other hand, assumes that the same repeating pattern has a new cause. And Trenberth knows the null hypothesis debunks his hidden heat in the pipeline conjecture, so he demands a new null hypothesis! If any of these guys followed the scientific method, they would have to produce solid evidence showing “this time it’s different.” Since there isn’t any evidence that this time it’s different, they want to turn the scientific method on its head, and change the null hypothesis. What they should be doing is to honestly admit that it is becoming clear that CO2 does not have the claimed AGW effect, and causes only minuscule warming at best – leaving natural variability as the best explanation for the very mild 0.7° rise over the past century and a half, as the planet continues its emergence from the LIA. But that would require them to admit that they were mistaken, and they will never do that. R. Gates says: August 9, 2011 at 12:14 pm .” Nice try, but it remains up to the Warmista to show that present conditions are not just more of the same. CRS, Dr.P.H. says: August 9, 2011 at 12:57 pm OMG, the military has contingency plans for everything. I am sure they have a recently updated plan for fighting their way out of Annapolis. “New report just out: ScienceDaily: Titled: Large Variations in Arctic Sea Ice: Polar Ice Much Less Stable Than Previously Thought, Study Finds.” Very interesting,,,but we know the warmists will rip the study to shreds, just as they did with Spencers latest study. All I see out of the Arctic Sea Ice Area and Extent data is that, since 2006, a step down to a new normal occured. How long will it stay there? How big is the next step? Which direction will it step next: Up or Down? Have fun watching and making bets/predictions, but don’t spend too long at the racetrack. RE: Steve Mosher at 9.44 am Thanks for your comments on my post. I accept your comments as being entirely valid, but that does not turn my statements into anti-science. As you say, as I scientist, if I see a dip in global temps coincident with a volcanic eruption I can postulate a mechanism, by science/physics as to how the temperature has been affected by the volcanic eruption. This is my natural curiosity as a scientist to explain the world around me and I entriely agree with your sentiments on this point. But if I observe changes in nature which are well within the bounds of other historical events then it surely behoves me to search for common, plausible physcial mechanisms of a general physical form before I create special pleading and special circumstances that the latter part of the 20th Century is somehow special and requires a special theory and set of physiscs whereby man (and AGW) becomes the root cause of the phenomenom. To formulate a physcial theory that the latter part of the 20th century requires the invoking of physics specifically involving mans actions when the changes observed appear to be no different in magnitude or form than previous, naturally associated events strikes me as possibly hubris and little different to the beliefs held by the population during less enlightened times. As an example, I believe Phil Jones is on record as pointing out that the putative global temperature rise of the late 20th century is statistically identical to the rise in the early part of the same century and as two previous periods within the temperature record for Central England. Why therefore does the latter half of the 2oth century require a special theory all of its own to explain it? A simple glance at the last 10,000 years of the GISP2 ice core temprature proxy should be enough to demonstrate that the recent warming is hardly unusual. The whole premise of tipping point warming upon which AGW was balanced got taken to political arena. There, while under watchful eyes, the economy turned far more sour than the planet warmed, so much so, that the real threat turned out economic, not climate warming. It was then that the GOP made hay of the point, and AGW was forthwith tossed under the Bus as a bargaining chit. An expensive chit what with all the years and treasury expended. Deals are deals. Nobody wanted a baked potato gone cold and moldy. Nobody in politics is about to dig it out of the trash can, let alone try to warm & serve it. It’s dead, Jim. ThinkingScientist, Exactly. The climate alarmist crowd is trying to make the current climate something sinister, when in fact it is a “Goldilocks” climate: not too hot, not too cold, but just right.. Re: Smokey at 3.47 pm “There has been about a 40% increase in CO2, and global temperature has only gone up a minuscule 0.7°C” Actually, if “corrected” GHCN is being used as the basis for the estimate of temperature rise in the 20th century you can probably subtract 0.25 degC from that temperature rise as this is the systematic “error” correction trend applied to that data since 1910. Not clear to me why the temperature correction across thousands of mercury thermometers over many decades of the 20 th century should be a systematic function of time. Within days arctic ice extent should reach the 5.5 million sq. kilometers predicted on this site last November. “The ice is coming back”. Yes, the USHCN adjusts everything. Look at this basket of snakes: click They adjust earlier readings lower so the resulting graph looks like temperatures are rapidly rising. And here we see how they got away from simply reporting raw mercury thermometer readings on their B-91’s: click Mark Fawcett, Thank you and Walt Meier for the clarification. It is clear that no one suggested that the arctic would be ice free in 2008. There is always discussion on the details of where when and how much with regard to the effects of AGW. Debate about precisely how many decades it may take for the arctic to become ice free misses the point. Cherry picking years like 2007 in noisy data and saying 2008 wasn’t so bad is cr**p science. The long term trends for ice cover is shown in fig 1 of this paper: .” The unfortunate thing is this smokey. Occams razor has nothing to do with this. There is known tested science that explains how C02 and other GHGs ( like water vapor) raise the effective radiating height of the atmosphere. That means that the earth will cool less rapidly. You have an effect, less rapid cooling that is predicted by science over 100 years old. Science so secure that we used it to design star wars and fighter aircraft. Science that has become engineering for people like me and jeffId and Ryan Odonnell. To be sure there are other factors that contribute both to warming and to cooling. But C02 or other GHGs added to the atmosphere will cause the temperature to be higher than it would be otherwise. No occams razor required. Steven Mosher, The evidence [or lack thereof] shows that the effect of CO2 is minuscule. Not non-existent. But minuscule. Joe Bastardi makes the case better than me: click Frank K., That press release says ice free in 30 years, not in 2008 or in 2013 or whatever else people here think Mark Serreze said. I have not followed everything that Serreze has claimed, but I have found his predictions to be consistent: the Arctic may be ice free in the summer by 2030. I even checked some articles from Anthony’s recent “short research project,” and I read the same prediction from him each time he was mentioned. Even in relation to his “death spiral” quote, he mentions the year 2030: . I’m sorry, but I find Serreze’s predictions to be much more consistent than people’s interpretations of what he said that are presented here. I don’t think it’s that hard to comprehend what Serreze has said.. I find it amazing that as the main predictions that convinced non-scientists and scientists alike of CAGW fail, they roll with the punches but remain steadfast. Would they remain so if all the predictions fail? Would R Gates still remain 75% convinced? Would Mosher just continue to grow more annoyed? Right now they are responding by stretching forecasts into the future, kicking up dust (aerosols?), changing the name of the perceived CO2 Armageddon to even remove the word warming….. As predictions fail. Having been given a 30-50 year respite and the halving or two thirds reduction in the expected temps, let’s at least take off the ‘C’ from CAGW (I don’t accept the desperate substitutes of c.c. Or c. Disruption). We live in interesting psychological times. On the good development side, the NSIDC has started reporting the daily sea ice extent numbers (as Jaxa does) and the individual regions are also reported. The data only starts on July 8th, but hopefully someone will go back and reconstruct the historical numbers (so there might be less arguing and more discussion about what caused Y and what caused X). if not, at least we can start using the data in the future. HomePage here. Data can be located on the right and through an FTP site in csv format. Steven Mosher says: August 9, 2011 at 9:44 am If you want to understand or explain the current decline, then appealing to “natural variation” is no explanation whatsoever. Its an explanation without any predictive power. Its an explanation that can’t be falsified. Its the absence of explanation, it’s anti science. Let me explain what is wrong with this train of thought. Terming unexplainable differences as ‘natural variation’ is the only way to describe them unless you prefer to ignore the fact that we don’t know everything. If a tree falls in the woods, you can see it on the ground. You may not be able to tell what fell that tree, but you don’t need to know what chopped it down to see it on the ground. What is anti-science is saying that just because none of the known factors can explain it, it must all be attributable to CO2. I have never seen a calculation that says, “If CO2 increases by [X], the effect on Arctic ice is [Y].” There are a lot of processes you’d have to follow to prove that out. Do you know of one? Otherwise, we are really just having a little argument about what the effect of CO2 on Arctic ice is. And that doesn’t really seem to be settled. In fact, to say that pointing out that it is not settled is ‘anti-science’ is disingenuous. “So far, the “screaming” hasn’t kept anyone awake at night, and we have not returned to the low of 2007 in the last three melt seasons.” Does that mean that 2007 ice which was “new ice” is now “old ice” or is it still classified “new ice”? LOL NJ says: August 9, 2011 at 5:19 pm OK. Do you believe that the arctic will be “ice free” – that is NO ICE IN THE ARCTIC?? For the entire summer?? My observation really wasn’t about Mark “The Arctic is Screaming” Serreze’s predictive powers (such as they are)…it was about the veracity of the NOAA press release headlines, and how they are designed for maximum alarmism. You can’t deny that. I was simply asking if Dr. Meier agreed with the headline, or if he (like me) thought it was way over-the-top. Again, the public is tuning out the climate scientists precisely because the people in charge of government press releases are, to put it charitably, out of control! If you have a cogent counterargument, please provide it. Thanks. Mosh, the ” media agenda ” you say is spread only by scientists and with deliberate intent. And it is done by scientists on the pro-AGW side of the camp and it is relayed in big words worldwide. The statements about artic ice have been done by scientists from NSIDC and NOAA. How about you ask them to shut up and follow the scientific method, study natural variations, past history and report facts truthfully? Don’t come here defending that crap. It is pro-AGW scientists who are spreading false statements and alarmism in the name of science. When their predictions or projections or whatever soothsaying crap they name it with don’t turn true they don’t even have the decency to put up their hands and say that they were wrong. Instead, they change the goalposts to some unverifiable future date and keep spouting the same bullshit. It is exactly the scenario that is being repeated again and again. That’s exactly what is being discussed here. So please get the gist of what the post says and what the comments are about. We know that the world is going through a warming phase after the little ice age. There’s nothing that has shown that this warming is anomalous to what has happened in the past and nothing that has shown that what is happening now is out of the ordinary. Natural variation is the null hypothesis that needs to be falsified if current situation is to be shown as anomalous. The artic has also shown to be ice free in the past. The GHG theory is well known and understood. One of the presumptions is that the earth acts like a perfect greenhouse and traps everything. Off late some work has been done which seems to show that this is not the case and a lot of heat seems to be radiated back into space. Dr.Spencer’s paper explores this theory. Dr.Salby’s forthcoming paper seems to say that CO2 lags warming and not the other way round. These papers my either prove true or may be debunked later. Time will tell. So best way is to keep an open mind and see all the evidence. That’s what science really is about. Steve Mosher says (condensed down): “There is known tested science that explains how C02 and other GHGs ( like water vapor) raise the effective radiating height of the atmosphere….Science so secure that we used it to design star wars and fighter aircraft….But C02 or other GHGs added to the atmosphere will cause the temperature to be higher than it would be otherwise.” You appear to be juxtaposing CO2/AGW theory with aeronautical engineering. I cannot accept that the theory of AGW via CO2 is “science so secure that we used it to design star wars and fighter aircraft”. As for the “effective radiating height”, well as I understand it physical models of the atmosphere have made predictions that the atmosphere should show a tropospheric “hot spot”. That prediction appears to have failed. In fact, I am not aware of any unique predictions made be AGW theory-driven GCM’s that have been clearly demonstrated against any data. And “hindcasting” doesn’t count, not when there are so many free parameters. Regarding the idea that CO2 causes some warming, I accept the views of any number of atmospheric physicists that this is true. Howeve, I notice that Spencer, Lindzen and (not forgetting he is a distinguished atmospheric physicist) Singer all agree CO2 will cause some warming but they all consider the effect to be much smaller than given by more alarmist scientists informing the IPCC reporting. As for water vapour, well its a strong GHG on paper, but it also forms clouds. As far as I can see the jury is still out on whether the feedback from water vapour is even positive or negative. Just from very simple “back of the envelope” common sense reasoning I find it very difficult to see how it could be anything other than negative – on the higher temperature bound the climate of the planet has been pretty stable for the last few million years, and has plataued consistently for the last 10,000 years post Younger Dryas. As I said above in an earlier post responding to your “anti-science” comments, a quick glance at the last 10,000 years of the GISP2 ice core data will show very clearly that MWP, LIA, Roman warming, Minoan warming, Bronze age warming etc are all comparable too or in some cases likely warmer than the latter half of the 20th century. Typhoon says: August 9, 2011 at 5:41 pm >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> The difference between yesteryears prophets of doom (names forgotten in the dustbin of history) and modern ones such as Erlich and Serreze is that those of yesteryears were taken down to the town square and pilloried with rotten cabbages, while the modern ones are taken to the townhouse, given a modern office full of expensive computers and awarded 5 to six figure salaries so that they would be able to continue feeding us eotw (end of the world) and other bs. Alex the skeptic says: August 10, 2011 at 2:16 am “In the imminent doomsday racket being consistently wrong is not a liability.” To add to this statement, doomsday headlines by NOAA, NASA/GISS, IPCC and their ilk serves primarily to increase and protect their government funding levels. Again, it’s all about money and fame with these people… Well, I’m late to the party again, and as usual no one’s taken a critical look at the source material. 2007 – The “ice screaming” quote from Serreze comes with no prediction at all. 2008 – The ‘death spiral quote’. Serreze suggests the ice could be gone “within a couple of decades”. A bit lower down the article he says, “we’ll lose the summer ice cover probably by the year 2030.” Yep, that’s roughly a couple of decades from 2008. At this point Anthony says: “And in 2008 we had the forecast from NSIDC’s Dr. Mark Serreze of an “ice free north pole”. Serreze wasn’t talking about total ice cover. He was talking about a hole possibly opening up at the North pole based on the conditions that were being observed. This is quite different from total ice cover, which extends far beyond the ‘North Pole’. The difference is even explained at NSIDC, where Serreze is director. You can verify that here. 2011 – Serreze says, “”There will be ups and downs, but we are on track to see an ice-free summer by 2030. It is an overall downward spiral.” …which Anthony describes as a “new date” from Serreze. But it’s the same projection he made in 2008 for total summer sea ice cover. He even gave the year (2030) as a rough estimate in the 2008 article – but Anthony appears to have missed that part. Serreze has been consistent. But in case I’m wrong, you have Serreze’s ear, Anthony. Perhaps you could ask him to clarify? Steve Mosher, I don’t think fighter aircraft are designed strictly inside of computer models. The designs are still tested in wind tunnels. The earths climate system is vastly more complicated than air resistance and turbulence that can’t even be computer modeled properly today. Your analogy fails. Chris Long says: August 9, 2011 at 5:05 am The concept of a tipping point for arctic ice extent pre-supposes the existence of at least two stable configurations – our current one, with a lot of ice, and another one with no ice. Does the peer-reviewed literature contain any evidence the such a ‘no-ice’ stable system is possible? Hi Chris. Between a lot of ice and none is the absence of ice in summer only. Tietsche, Notz, Jungclaus, Marotzke () have used model studies to suggest that if summer ice completely vanished today the resultant escape of warmth from the Arctic would lead to a return to much the same summer ice within two years or so. It must be noted that this “recovery” would be to a systemically falling level of summer ice coverage. Ice free Arctic summers are on the way. Another random observation. The NWS Anchrorage ice page depicts actual new ice formation in the Barents over the next week. Looks like temperatures are cooling earlier this year than they did last year. R Gates commented a week or two ago that the abrupt shallowing of the Arctic ice extent curve was merely “convergence” – the wind blowing the ice floes together, and predicted that this would be followed by a steep fall in extent as this convergence dissipated. This has not happened. The extent curve continues to follow a normal gradient and according to some metrics, such as the IMS (Interactive multisensor) this year’s extent has “joined the pack” of other recent years. Cryosphere Today’s colour map has shown for much of the summer alarmingly red and thin ice, predictive of rapid decline, but the rate of decline has been if anything below normal, and for July the decline rate was a record low. As others have commented there is something strange and different about the Cryophere images this year. Have the folks at Cryosphere Today received the knock on the door that has been long overdue? Hard to know how to interpret much official climate data when the instrumentation and databases are in the hands of warmista activists. Rather like interpreting official data on production of tractors in the Soviet Union during the 50’S and 60’s. Correction: Sorry – RGates described “divergence” – wind spreading out ice extent, not “convergence” as stated incorrectly in the previous post. My logic got inverted somehow. (Senior moment.) Ice area is now below last years Sept. 21st minimum. Summertime minimum ice extents in the Arctic are now ranging from 5.5 million to just over 4 million km2 of ice. And, over the last 30-odd years, have been measured by satellites as declining from their earliest values of about 6 – 6.5 million km2. The ice only can melt during the summer – the rest of the year averageg winter temperatures hover near -25 degrees. But during this same period of declining sea ice minimums, actual summertime temperatures at 80 north (the southern edge of the Arctic ice above Greenland, and an arc across the middle of the ice near longitude 180) have been measured since 1959 as declining. No measured temperatures – other than NASA-GISS’s 1200 km extrapolations across the tundra! – can show demonstrable Arctic temperatures increases. 1) My question to Hansen, Mosher, RGates, Mieirs, and others who have used these “tipping points” to destroy the world’s economies and force billions into early deaths mired in poverty and disease by their government-funded CAGW death-spiral threats, is to show by their calculations how an assumed 1/2 of one degree average world temperature increase (an increase only “measured” further south in temperate latitudes) can “melt” 1.5 million km2 of of Arctic ice, when the Arctic temperatures near the ice itself are declining during the only period of the year when the ice can be melting? 2) Hundreds of sources claim an Arctic albedo “positive feedback” but none can show how the sun can warm Arctic waters under the actual illumination angles present during the September minimums. 4 million km2 corresponds to an ice-covered “cap” covering the entire area between latitude 79.2 and 90 north. (Not a perfect match, but close enough. The real summertime minimum ice extent varies from year-to-year, but tends to be a near-circle centered about latitude 85, longitude 180.) Assume all of this ice melts for some reason one year: There is a completely ice-free Arctic in September. The result? My calc’s using the actual reflectivity of ice and water show that there will be no change in received energy to the earth regardless of how much ice has melted. That is, both ice and ocean water reflect the same percent of solar energy at the actual solar incident angles found above latitude 80 north. Albedo (color of the ice or of free ocean water) itself is irrelevant at these low angles. In fact, one can show that the insulating effect of ice-covered water prevents additional cooling due to evaporation, while both ice-covered surfaces and open water sources radiate the same amount of energy through the same skies and clouds to space. Received radiation from the sun during that very short period that the sun is visible stays the same, while losses (radiation and evaporation) increase over the entire 24 hours per day. Thus, an ice-free Arctic contributes to additional cooling, and the feedback of an ice-free Arctic is actually towards colder summers worldwide. where he said: Indeed, if the weather bureau says there is the possibility of rain tomorrow and it doesn’t rain then they should lose their jobs.
https://wattsupwiththat.com/2011/08/09/quote-of-the-week-death-of-the-arctic-death-spiral/
CC-MAIN-2017-09
refinedweb
10,478
70.33