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
Using Mule Agents An agent is a service that is associated with or used by Mule but is not a Mule-managed component. Agents have the same lifecycle as the Mule instance they are registered with, so you can initialize and destroy resources when the Mule instance starts or is disposed. Mule provides several agents for JMX support, including notifications and remote management. You can also create custom agents to plug any functionality into Mule, such as running functionality as a background process or embedding a server in Mule. Configuring an Agent Agents are defined in the Management module. To use an agent, specify the management namespace and schema, and then specify the properties for the agents you want to use. For example: For a list of agents provided with Mule and how to configure them, see JMX Management. You can also create a custom agent as described below. Creating Custom Agents To create your own agent, your agent class must implement org.mule.api.agent.Agent. You then configure your agent using the <custom-agent> element, which takes two attributes: name specifies a unique name for this agent, and class specifies the class where it’s defined. If your agent requires that you pass in properties, you can specify them as name/value pairs. Note that this element is now in the core Mule namespace. For example:
https://docs.mulesoft.com/mule-user-guide/v/3.8/mule-agents
CC-MAIN-2017-43
refinedweb
228
61.36
i basically have to write code which takes in 5 prices from insurance companies A-E from the user and outputs the average price, and cheapest price with the companies id which would be A,B,C,D,E here is my code so far, I got it to list the average but cant seem to figure out how to get the cheapest price, or how to make it have the companies id out-putted. public class InternetCompare { public static void main(String[] args) { int[] prices = new int[5]; // Read in ages int i = 0; String s = JOptionPane.showInputDialog( "enter a price, -1 to stop:"); int n = Integer.parseInt(s); while ((i <= prices.length - 1) && (n != -1)) { prices[i] = n; s = JOptionPane.showInputDialog( "enter a price, -1 to stop:"); n = Integer.parseInt(s); i++; } int nextFree = i; // nextFree is index of next free element in array // compute average age int total = 0; for (int j = 0; j < nextFree; j++) { total += prices[j]; } double ave = total / (double) nextFree; JOptionPane.showMessageDialog(null, "Average price is " + ave); } }
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/14016-arrays-beginer-printingthethread.html
CC-MAIN-2014-52
refinedweb
174
62.48
in reply to Module usage Including a module with "use" reads the module and makes it available to your program within its own namespace. By default, many modules will export symbols (variables, functions, methods, etc.) into the "main::" namespace. This allows you access to these symbols without prefixing them with their proper namespace. Specifying a list of symbols with the "use" statement overrides the choice of symbols to export. When this list is empty, no symbols are exported. The symbols are still accessible by prefixing them with the namespace of the module. That is incorrect, but it is often what happens because the use Module statement is in the package main. The symbols are exported to into the current namespace. Be well, rir My savings account My retirement account My investments Social Security Winning the lottery A Post-scarcity economy Retirement?! You'll have to pull the keyboard from my cold, dead hands I'm independently wealthy Other Results (73 votes), past polls
http://www.perlmonks.org/?node_id=746502
CC-MAIN-2014-42
refinedweb
163
65.22
In this article, I am going to give an explanation of the steps for getting started with MongoDB for express backend. For accessing MongoDB database from express, we use Mongoose which is an Object Data Modelling library providing all necessary functions to access and work with MongoDB. First, let’s make our work directory ready. $ mkdir express-mongodb $ cd express-mongodb Step 1: Initialise npm on the directory and install the necessary modules. Also, create the index file. … In this article, I’ll be explaining how you can get started with express to write server-side code. Node.js —A Javascript framework used for building backend for your applications. Express — Framework for node.js npm (node package manager) — package manager for installing necessary modules to work with your application. First things first, we should have node.js installed in our system. Click here to visit the node.js official site, select the platform that you are using and download. After installing node.js, create a new folder and open the folder in your favorite editor. $ mkdir express-demo$ cd express-demo$ code… In this article, I’ll be showing you how we could write python scripts to search and download images from google. Be it any machine learning project, the most boring part of it would be data collection. But what if we can automate the process? Let’s attempt to search for Persian cat images and save them to a directory. Firstly, Install the Google-Images-Search package using pip or conda from your command line. $ pip install Google-Images-Search In a new python file or jupyter notebook, import the module. from google_images_search import GoogleImagesSearch Step 1: Create a new project in Featurepreneur’s AWS scholarship to become an AWS certified cloud practitioner I didn’t even imagine that I would be getting a chance to take on the AWS cloud practitioner exam fully funded, in my pre-final year of study. AWS cloud practitioner certification tests you on the basics of cloud computing in AWS. Also, you will be acquiring knowledge of many AWS cloud services that are currently so popular among industries. I have been working as a research intern for Tactlabs since Nov 2020. Here in Tactlabs, DevOps and Machine Learning are the areas that are primarily focused. … For someone who’s looking to learn and grow, volunteering opportunity is a dream come true. And I’m gonna share my experience of receiving my new volunteer opportunity. I have been part of Tactlabs since Nov 2020. My experiences so far have been really fruitful. It tested me in a lot of ways and shaped me into the person that I am right now. I became much more confident than I used to be. Tactlabs has a very supportive workspace which encouraged me to grow by taking up challenges. “ If you want to learn, take up the challenge. “ In this article, I’ll be walking you through the basics of GraphQL in express. GraphQL is a query language for API’s and it’s more powerful. It allows the client to access only what they need, making the access rate faster. Create a new folder and cd to the folder. $ mkdir graphql-test $ cd graphql-test Initialize the npm package, using npm init $ npm init Install necessary modules $ npm i express express-graphql graphql Then, create index.js file and import the express module and make sure the app is listening to the port specified. const express = require('express');const app… Making long virtual sessions interesting is hard. But in @featurepreneur, we bring in interactive gaming sessions to make people more involved throughout the session. We have some really cool add-ons to any meeting. Let’s have a look! 1. ReadingBreak Here, an HBR article is shared and the candidates are given 5 minutes to read and understand. As time ends, they will be asked to discuss their opinions. Generally, it helps you to improve your communication skills. You will also learn to put forward your opinions to a group of people. 2. Error Scenarios Here, you are provided with errors and…
https://sharmilas22.medium.com/?source=post_internal_links---------3----------------------------
CC-MAIN-2021-21
refinedweb
687
66.44
XINS 2.1 alpha 1 has been released. The main new changes are: * Added new emma target for unit test coverage using EMMA (). * Return XML-RPC also in case of an error. * _context and _data parameters are only sent when needed. * If the XINS version changes the build.xml is recreated. This may requires you to remove it manually when coming from XINS 2.0 or 1.x. * New target javadoc-apis to generate the Javadoc for all APIs. * If no environment is specified for an API, the test form page is still generated and a text field is proposed to the user to fill the location of the API. The value is stored in a cookie. * Improved specdocs: added favicon, added meta information, fixed CSS, fixed some of the XHTML. * Many bug fixes and small RFEs implemented. Best regards, Anthony ______________________________________________________________________________ CHANGES INTRODUCED IN XINS 2.1 ALPHA 1: * XINS/Java Common Library: - Implemented RFE #1654262: Implement equals(Object) on PropertyReader classes. Contribution from Ernst de Haan. - Added a BufferedReader to read from the socket input stream. * XINS/Java Server Framework: - Implemented RFE #1631516: Log entry 3408 should specify value of fallback default. - Implemented RFE #1633455: Get all properties from the RuntimeProperties object. - Implemented RFE #1636219: Added file name to the logs when the thread stops. Contribution from Ernst de Haan. - Implemented RFE #1636219: Invalid XML-RPC request if namespace set. - Fixed bug #1371632: XML-RPC: 400 returned instead of XML-RPC fault. * XINS/Java Client Framework: - If no data section, the _data parameter is not sent. - If no context is available, the _context parameter is not sent. * Generation of server-side Java code: - Removed creation of _errorResult when the function has no input parameters and no input data section. - Removed creation of the parameter when the type is _text and is optional in checkOutputParameters() as not used. - Changed Request.equals() and Request.hashCode() to use in some cases equals() instead of ==. * Generation of client-side Java code: - Fixed bug #1703483: CAPI javadoc doesn't mention Error Result Code exceptions. * Generated build file: - The build directory is deleted if the version of XINS has changed between two build. - Added new target javadoc-apis to generate the Javadoc for all APIs. - Clean target should also delete the generated WSDL file. * Generation of specification documentation: - If no environment is specified for an API, the test form page is still generated and a text field is proposed to the user to fill the location of the API. The value is stored in a cookie. - Fixed incorrect CSS for specdocs. - Fixed some invalid XHTML. - Added a favicon.ico in the specdocs directories. - Fixed Bug #1576547: No warnings when resultcode is not referenced from api.xml. - Added meta description for the generated HTML pages. - Added link to the favicon in the generated HTML pages. * Tools: - Upgraded Maven pom to the new stable 2.0 release. - Added new target emma to execute the unit test coverage of an API using EMMA (). * Examples: - Fixed incorrect runtime property used to define the logdoc locale. * Documentation: - Added primer.html to redirect to primers/primer.html. * Build- and release-process: - Added NetBeans project files to CVS. - Added missing src/tools/dojo directory to the release. - Implemented RFE #1741660: building xins doesn't include Spring packages. * DTD: - Added 2.1 DTDs.
https://sourceforge.net/p/xins/discussion/669312/thread/d4401b28/
CC-MAIN-2017-34
refinedweb
551
61.12
- Comb list of items to appear in the ComboBox. Each item must appear on a separate line. Figure 3.9 The String Collection Editor. Items can be added to the ComboBox control at runtime, as well. This can be accomplished in two different ways. First, call the Add method on the Items collection property of the ComboBox control. Items can be removed through the Remove method on the Items collection, or all items can be removed by calling the Clear method. The following code snippet adds three strings to a ComboBox control named comboBox1: C# comboBox1.Items.Add("Hi"); comboBox1.Items.Add("Howdy"); comboBox1.Items.Add("Wuz Up"); VB comboBox1.Items.Add("Hi") comboBox1.Items.Add("Howdy") comboBox1.Items.Add("Wuz Up") You can also add items to a ComboBox at runtime by binding the control to a collection object. This is done by setting the DataSource to the collection object. When the ComboBox attempts to add items to the drop-down list, it will call the ToString method on each item in the DataSource and add that string to the drop-down list. The string can be customized by setting the ComboBox control's DisplayName property. The ComboBox will call the property specified in the DisplayName property and add the returned string to the drop-down list. Listing 3.1 demonstrates how to bind a ComboBox to a list of custom objects. The Customer class is a custom class that holds the name of a customer. The class has a property named FullName that properly formats the customer's full name. When the ComboBox is bound in the LoadCustomer method, the FullName property is set as the DisplayName. Listing 3.1 C# class Customer { string m_First; string m_Middle; string m_Last; public Customer(string first, string middle, string last) { m_First = (first == null) ? string.Empty : first; m_Middle = (middle == null) ? string.Empty : middle; m_Last = (last == null) ? string.Empty : last; } public string FirstName { get { return m_First; } } public string MiddleName { get { return m_Middle; } } public string LastName { get { return m_Last; } } static string FullNameWithInitial = "{0} {1}. {2}"; static string FullNameNoInitial = "{0} {1}"; public string FullName { get { return (m_Middle.Length > 0) ? string.Format(FullNameWithInitial, m_First, m_Middle[0], m_Last) : string.Format(FullNameNoInitial, m_First, m_Last); } } } private void LoadCustomers() { if(customers != null) return; customers = new Customer[6];"); this.comboBox1.DataSource = customers; this.comboBox1.DisplayMember = "FullName"; } VB Public Class Customer Dim m_First As String Dim m_Middle As String Dim m_Last As String Public Sub New(ByVal first As String, ByVal middle As String, ByVal last As String) If first <> Nothing Then m_First = first Else m_First = String.Empty End If If middle <> Nothing Then m_Middle = middle Else m_Middle = String.Empty End If If last <> Nothing Then m_Last = last Else m_Last = String.Empty End If End Sub Public ReadOnly Property FirstName() As String Get Return m_First End Get End Property Public ReadOnly Property MiddleName() As String Get Return m_Middle End Get End Property Public ReadOnly Property LastName() As String Get Return m_Last End Get End Property Private Shared FullNameWithInitial = "{0} {1}. {2}" Private Shared FullNameNoInitial = "{0} {1}" Public ReadOnly Property FullName() As String Get If m_Middle.Length > 0 Then String.Format(FullNameWithInitial, m_First, m_Middle.Chars(0), m_Last) Else String.Format(FullNameNoInitial, m_First, m_Last) End If End Get End Property End Class Private Sub LoadCustomers() Dim customers(6) As Customer") ComboBox1.DataSource = customers ComboBox1.DisplayMember = "FullName" End Sub There are two ways to obtain which item is currently selected in the ComboBox. First, the SelectedIndex item property returns the index of the currently selected item. This index can be used to access the selected item from the ComboBox control's Items property. The following code exemplifies the SelectIndex property: C# string selItem = comboBox1.Items[comboBox1.SelectedIndex].ToString(); VB Dim selItem as string selItem = comboBox1.Items(comboBox1.SelectedIndex).ToString() The ComboBox control also provides the SelectedItem property that returns a reference to the currently selected item. Once you have a reference to the currently selected item, you do not need an index into the Items property. The following code demonstrates how to use the SelectedItem property: C# string selItem = comboBox1.SelectedItem.ToString(); VB Dim selItem as string selItem = comboBox1.SelectedItem.ToString()
http://www.informit.com/articles/article.aspx?p=101720&seqNum=11
CC-MAIN-2019-04
refinedweb
686
57.87
how can i canfigur whelli collider? I honestly am having a hard time what your problem is, could you elaborate? when I play car down on the Trrein and jump , I dont indrestend why? I don't indrestend either. Try to use RigidBody.AddForce What are you trying to do, exactly and what is your problem? when i play car down in trrein and jump, This is not a question. Please provide more context, information, what you have tried already, etc. Not providing sufficient information makes it difficult for people to solve your problem and may lead to your question being closed for not following user guidelines. I have installed Rigidbody, WhelliColliders, and write script, but when i play my car is jump ...(using UnityEngine; using System.Collections; public class MoveScript : MonoBehaviour { public WheelCollider[] frontCols; public Transform[] dataFront; public WheelCollider[] backCol; public Transform[] dataBack; public float maxSpeed = 30f; private float sideSpeed = 30f; public float breakSpeed = 100f; void Start() { } void Update() { /** Get axis **/ float vAxis = Input.GetAxis("Vertical"); float hAxis = Input.GetAxis("Horizontal"); bool brakeButton = Input.GetButton("Jump"); /** End get axis **/ /** Motor **/ frontCols[0].motorTorque = vAxis * maxSpeed; frontCols[1].motorTorque = vAxis * maxSpeed; /** End motor **/ /** Brake **/ if (brakeButton) { frontCols[0].brakeTorque = Mathf.Abs(frontCols[0].motorTorque) * breakSpeed; frontCols[1].brakeTorque = Mathf.Abs(frontCols[1].motorTorque) * breakSpeed; } else { frontCols[0].brakeTorque = 0; frontCols[1].brakeTorque = 0; } /** End brake **/ /** Rotate **/ frontCols[0].steerAngle = hAxis * sideSpeed; frontCols[1].steerAngle = hAxis * sideSpeed; /** End rotate **/ /** Update graphics cols **/ dataFront[0].Rotate(0, 0, -frontCols[0].rpm * Time.deltaTime); dataFront[1].Rotate(0, 0, -frontCols[1].rpm * Time.deltaTime); dataBack[0].Rotate(0, 0, -backCol[0].rpm * Time.deltaTime); dataBack[1].Rotate(0, 0, -backCol[1].rpm * Time.deltaTime); dataFront[0].localEulerAngles = new Vector3(dataFront[0].localEulerAngles.x, hAxis * sideSpeed, dataFront[0].localEulerAngles.z); dataFront[1].localEulerAngles = new Vector3(dataFront[1].localEulerAngles.x, hAxis * sideSpeed, dataFront[1].localEulerAngles.z); } } / End update graphics cols */ ) Answer by ragnaros100 · Oct 26, 2016 at 09:24 AM I just matched your settings in a new project. Yes. The car jumps like crazy. You should change your rigidbody settings. The wheel collider looks for the rigidbody mass. I assume your rigidbody mass is at the standard 1. Try to set it to 2000 instead. A regular car usually weighs around 1-2 metric tons, not 1 kilo. Hope this helps :) I instead 2000 but , all the same my car is jump.((( Try to follow the steps Here and please improve your english skills. You are very difficult make it so the rigibody on the parent uses the mesh collider on the children ? 0 Answers Error NullReferenceExceptionwhot isk this?? 0 Answers How to trigger a BoxCollider with a RigidBody? 0 Answers What to do to prevent the camera from going through colliders with this script 1 Answer I fly when i pick up objects in VR 2 Answers
https://answers.unity.com/questions/1262170/why-my-car-is-jump.html?sort=oldest
CC-MAIN-2020-05
refinedweb
474
53.88
I am currently a student in C, and I'm trying to learn functions. However, the very first demo code the book gave just does not work (I keep getting undefined results). I've triple checked and I have code down exactly, so I'm wondering if they forgot to include a header or if I'm missing something. This keeps outputtingThis keeps outputtingCode:#include <stdio.h> #include <stdlib.h> #include <math.h> double average (double a, double b) { return (a + b) / 2; } int main() { double x, y, z; printf("Enter three numbers:"); scanf("%1g%1g%1g", &x, &y, &z); printf("Average of %g and %g: %g\n", x, y, average(x, y)); printf("Average of %g and %g: %g\n", y, z, average(y, z)); printf("Average of %g and %g: %g\n", x, z, average(x, z)); return (0); }Any ideas?Any ideas?Enter three numbers:234 Average of 1.8e-307 and 1.8e-307: 1.8e-307 Average of 1.79046e-307 and 7.96789e+268: 3.98394e+268 Average of 1.79064e-307 and 7.96789e+268: 3.98394e+268 Process returned 0 (0x0) execution time : 1.391 s Press any key to continue.
http://cboard.cprogramming.com/c-programming/152288-function-not-working-properly-what-am-i-missing.html
CC-MAIN-2016-30
refinedweb
199
77.84
Helping Hands Introduction: Helping Hands For those that can use an extra hand around the house! I like to ask my students to think of some small thing in their life that could use a little extra assistance around the house. It can be small, from a toothpaste holder to a coat rack or an extra fist bump them when they finish their work. Then we make that idea more concrete! - What: Helping (Concrete) Hands - Why: Fist bumps forever - Concepts: Casting and Molding, Woodwork, Chemistry - Price Per Hand: ~ $2.50 - Materials: - For casting: - Concrete (quick drying Rockite works great) - Alginate for the mold (I used this brand) - 2-liter bottle (or other large container for casting) - Mixing stick - A small piece of cardboard - Bolt - Threaded insert (that fits bolt) - Washer (that fits bolt) - Nut (that fits bolt, just for setting) - Wood - Screws - Drill - Scissors (optional) - Utility knife (optional) - Saw - Sandpaper of Sander Ready, Get Set, Concrete! Step 1: Prepare Your Bottle Whether you just chugged 2 liters of Hawaiian Punch or scrounged from the company picnic, you've got to prep that bottle. Cut off the top with a utility knife or scissors, and then dry out the inside. Put your hand in in the position you want your cast to make sure there's enough room so it doesn't hit any of the sides. If it does hit a side, you're going to need a bigger container. Time to chug 3 more liters of Hawaiian Punch! Or just use a box. :) Step 2: Alginate: the Miracle Maker If your mouth has been filled up at the orthodontist, or if you've ever dreamed of a purple heaven, then you know alginate well. Alginate is just amazing stuff to cast from living things. It's also neat that it's actually from the cell walls of algae. Scoop some into your bottle that you think can surround your hand (a little less than half by volume), add water and mix. I used a brand called "Dermagel" from Douglas and Sturgess, and they recommend adding 1 part alginate for 1.5 parts water by volume, but I find that I can get good results by just eye-balling it aiming for a semi-goopy milkshake mix. Get your hand in there! Once you've started mixing, your alginate is setting. For me, my hand got tired after a bit, so I used the side of the bottle to prop it up. To see if the alginate is set, wait 5-10 minutes and poke it to see if it feels like spongy but solid. If it is, you can start wriggling your fingers free and take it out. You can make it go faster by using warm water and keeping a higher powder to water ratio. Step 3: Hand Out and Bolt In! Wriggle that hand out of there. If your alginate moves a bit when you take it out, that's okay! It's part of the magic. It'll return (ish) to its mold state. It's bolt time! We're going to set a bolt into the back of the cast hand, but you're going to need a little support to do so. Make a hole in a piece of cardboard with some scissors (2). Then slide a wide washer on your bolt and poke it through the cardboard. Hold it in place with a nut (3), and make sure that the bolt will hand low enough into your mold to be deep in the concrete (4). Remember, the head of the bolt will be inside the concrete. You got it! Step 4: Pouring Concrete Scoop up some concrete powder (I like Rockite because it's quick), and add water. Again you're going for a milkshake-like consistency. Pour it into your mold, making sure to move your mold around, angling it to make sure any air can escape from overhangs (like where my pointer finger curled in this mold). Pour it to the top, and then place the bolt in the top. If you find the bolt is too far out, cut down the sides of your bottle until it's just right. Step 5: Excavate! This is truly the most fun part of any casting process. Is it a hand? Did it work? Will the fingers break off? Is there a live animal in there? It's just so much fun to go on the archeological dig of the most recent fossil on the planet. After your concrete has set, remove the bolt and uncover your piece. (Look! The bolt is in there!) You can slide alginate out of most things, and then begin to peel it away with hands and scissors if you like. And inside is.......YOUR HAND! AS A ROCK! IT'S A MIRACLE! (I really do feel this way) Step 6: Wash Your Hand(s) After you have a "HOLY MOLY, THAT'S MY HAND" moment or hour or so, you can start to clean up your cast. There will probably be little flakes of alginate, a few drips of concrete you don't like, and maybe some rough edges around the base. I started with a a little water and a brush to take off some of the concrete dust and alginate, and finished up with sanding the corners around the wrist to make them nice and smooth. If there are holes from air bubbles, you can always mix a little more cement and dab them in there. Concrete hand surgery is pretty forgiving that way. :) Step 7: Make a Mount Your mount can be any shape you'd like, but I chose a circle. I used a roll of tape to trace around, and then cut it out on a bandsaw. I sanded down the edges, and then found the center of the circle for drilling. My favorite method for finding the center of a circle is this one! Step 8: The Threading Insert This is a great little piece of hardware called a "threaded insert." It's adorable. It looks like a stumpy brass worm. It also is going into our mount. Check the size of your threaded insert, and drill a hole slightly smaller than it in the center of your wood (1). Screw the insert onto another bolt of the same size (2), add some glue (3), and then use a drill to drive it down into the wood (4). Now you have a great threaded piece of metal that you can easily screw your hand on to (5)! And you can trade out hands whenever you want. If you want a more permanent hold, you can always do a more standard nut and washer method to hold the bolt in. If you do, just make sure to countersink them so they're flush with the wood. Step 9: Saw Off Extra Bolt When you screw the hand all the way in, you may have some bolt sticking out the back. Saw it down so that you can mount it flat on the wall. To remove the extra bolt, screw your hand all the way in and mark which thread you'd like to cut it off at. Put it in a vice, and hacksaw the bolt off, making sure to support the hand when it breaks free. Then you can either sand, grind, or file it down to flush, and soon you'll have a helping hand you can mount on the wall! Huzzah! Step 10: Putting Hands on Walls If you want to put your helping hand up, it's easy to do! Screw the hand all the way in, and mark where "up" should be on the wood. Take the hand off, and then pre-drill two holes and insert screws. Drill them into the wall, making sure your "up" mark is facing upward. Then screw back on the hand! Step 11: You're Did It! Shake Hands With Yourself! You did it! Your helpful concrete hand can be used for all sorts of purposes. Whether it's used as a coat rack or a high-five or a toilet paper holder or a guiding pointer, it's there! I am excited to see what you all come up with, so do share below if you make one! Have fun and keep exploring. Could you please share how long you let the cement set up before removing the Alginate from around the hand? Hey, good question! It can vary a bit depending on type, the mix ratio, and temperature of water, but usually 3-5 minutes should do the trick. It's quick! I do it by feel which is to try tapping the surface and waiting for a jello-like density. At that point you can slowly wriggle free and escape your mold! Sorry, maybe I didn't make my question clear enough. :) I'm actually asking how long you let the CEMENT set up before starting to remove the mold from around the cement. I've tried this twice, left the cement to harden for 30 and then on a next try 40 minutes, and the fingers break off easily in the process. However, I should note that I was using a different brand of cement - DAP quick plug anchoring cement - I couldn't find the Rockite that was recommended. Could the brand of cement be the difference or should I be letting the cement set up longer? I did this with my children's hands when they were little. The grandparents loved it. I'd like to try this, though with a bit more forearm. I have somewhat hairy arms though... How does the algenate release from hair? (sorry for the weird question) Coat your arms with vaseline first. Hello nice instructable i made it in Colombia, i still have issues with the concrete but it went pretly well at first try thank you Very creative and well written!!! F**k, this is brilliant! Need to make this for all of my family members. Will keep you posted... They did this in the 60's & 70's. I think Cynthia started the ball rolling (so to speak): I'm so going to do this! Awesome! I'm getting rid of my Paris plaster "hands" I use for my jewelry displays!. I've never liked the look of them. Now I just need to find a narrow container long enough so I can incorporate the wrist and forearm too. Great work! I think you can probably fit several bottles together to make it longer or deeper, if you will. If they seem to be leaking, use duct tape or something similar to seal the edges. Good luck! You can use the core tubes used to ship carpet. Carpet tubes? I'll look for those. I guess carpet stores might have some left over from jobs? Thanks for the idea. Oh awesome! I'm excited to see it! You can build containers out of cardboard boxes fairly easily if you need! Just make sure to duct tape the edges up well! I'll post ASAP! I may have missed it but I would suggest can a metal coat hanger cutting it up inserting into the fingers just to add some strength to it. if you have a heavy set of keys it would break if you didn't help give it some strength. Goid reasoning.. If you're worried about strength I would suggest using Fibermesh polypropylene fibers. We use it by the pound, per yard in concrete in residential and the steel fibers in commercial concrete floors. I have seen small packs of it for sale in Lowe's and Home Depot. Hey manic matt! That's a wonderful idea for added strength. This one was able to hold a pair of boots on it, which is about as heavy as I need, but I'll bet it could be EVEN BETTER with some metal. Thanks for the comment! I'll try it out! I think I'll make one of my foot to use as a door stop! Hey TomC57! I made an Instructable on your wonderful riff of Helping Hands! Now called "A Foot In the Door." I linked a thank you to your profile, but I'd also love to give you a pro membership. Would that be useful? Now thats a cool idea...do u use it for a door stop? cool idea! I love it! cool idea! I love it! That is just a phenomenal idea. This is very cool wish I had the materials to do this. Just go n buy it..they said it cost $2.50..and all the rest im sure u ciuld find around ur house.. A Pro Membership would be great, thanks! Why would anyone need something like that in their house. Its so creepy lol I dint think it's creepy at all.......but I love art! Perhaps this type of art just isn't your thing? Exactly! my son has had the same idea last year, he wants to do a handle for the gate of room his, but being a volcanic type with too much ideas for the head has confined to the plaster cast, never realized in resins Love it! It reminds me of the hand hat holders in the Willy Wonka factory. Tres cool! If you have an open hand position, could you make more than 1 hand per alginate mold? This looks really good! Definitely going to try it some time! Fist bump! who doesn't need this type of encouragement everyday? Thank you for responding so quickly and the info provided :) Used to do something similar back in the 70s with wax to make crazy, fist-shaped candles. This reminds me of the scene in Willy Wonka & the Chocolate Factory (1971 version) where they go to hang up their coats and the hands on the walls move to grasp the coats and hats. You usually have a cost per student listed with your materials list. Do you have a rough estimate for this project? Oh great question Jobar. I find that if you go with the larger tub, it comes out to about $2.50 per hand. Not too shabby! This is going to be AMAZING for our Halloween party! Thank you SO much! Oh yay! That would be WONDERful. And handy! :) Hi, What a GREAT project and you made the tutorial simple and easy to follow :) I have one question about the alginate please. Since our hands do not have saliva to help make them slippery (eg. the dentist mouth casts) can a very thin coating of petroleum jelly or similar lubricant such as mineral oil be applied to the hand before inserting into the alginate to make the removal easier? Or would that affect the cast in some way ?Thanks :) Hi LeslieGeee! Oh thank you for the comment, and this is a great question. Alginate does a pretty awesome job of being slippery enough that you don't need any extra layer on your hand. It'll slip right out from the spongy nature of the alginate. For casting, some people add soapy water to a mold before they pour into it (the concrete step), but these two materials are so different that it works out great without any additives. Have fun! please tell me in which substance you had dipped your hand Hi VanshM1! I used alginate, and specifically this brand:... It's amazing stuff! Whoa, that stuff is pretty expensive. For $35, how many hands could you make from one container of alginate? Hey wenestvedt. Thank you for the comment! And yes, it might be good to start with the smaller container (1lb) that sells for about $9. I found that it takes a little less than a 1/3 of a pound of alginate to make a hand. Have fun! (P.S. Also, this is a really fun Instructable -- thanks for posting it!)
http://www.instructables.com/id/Helping-Hands-2/
CC-MAIN-2017-34
refinedweb
2,668
82.85
Join devRant Search - "concept" -22 - - Who needs rubber duck debugging when you can do paper duck debugging? Or is that concept too... Farfetch’d? 😎13 - Asus introduces dual screen laptop with touchscreen instead of keyboard. Just imaging programming with that DISCLAIMER: it’s just a concept40 - - I don't judge other developers for not knowing or understanding a particular concept, I judge them for pretending like they do...2 - I’m making a puzzle game! Cool! Concept - done Mechanics - done Art - done Ui - done Puzzles - uhhh... this is harder than expected.32 - When you're trying to explain a concept as simple as it can be to your non-dev family and friends, but they're just quietly staring at you.8 - Finally got around to installing Arch on an actual machine 😀 I went for deepin since i wanted to try something new. I didn't go for any WMs since the whole concept seems complicated to me but i wanna look into it someday. Anyways, super happy so far. I boot in < 5s from hitting the power button which is super dope ♥️ ♥️. I did have some weirdness with nvidia drivers (as usual on linux lol) but reinstalling it fixed it.40 -?6 - Here I am, 'Junior' in my title and on my paycheck, training my 'Senior' colleague on the concept of variable types.7 - IF THERE ARE NO CARS IN THE SQUARES THEN YOU DONT SELECT ANYTHING ITS NOT A SUPER HARD CONCEPT TO GRASP.5 - MOTHER FUCKER IDIOTS!!! SO I HAVE TO ROLLBACK OUR PROD DEPLOYMENT BECAUSE IM THE ONLY FUCKER WHO UNDERSTANDS THE SIMPLE CONCEPT OF "DONT PUSH UNFINISHED CHANGES"?!? DAMN!!!! FUCK YOU ALL...10 - - - Witchcraft: Code that has been optimized to a point at which even its author has no concept of exactly how it works, only what it is used - So back in January 2015 I bought my first Mac and wanted to learn Swift. Coming from .Net C# IBOutlet was anew concept for me, had to search for how to make a button event and Google gave that 😐 **I just googled it for the sake of this rant but ya it happened 😅5 - You can’t become fit physically by reading a lot about fitness. You actually need to go to the gym and put the hours and sweat in! Same concept applies for coding as well.5 - Wi-Fi WPA2 has supposedly been successfully hacked and a proof of concept is supposed to be released later today. Thoughts? Link below. - - STOP LIMITING THE LENGTH OF THE PASSWORD I CAN CREATE YOU STUPID DICKBAGIAN MOTHERFUCKERS. YOU MOTHERFUCKING ASS BLEEDING WANKOSAURS REX FACED TITHEADS HAVE NO CONCEPT OF SECURITY. Anyone who does this should build a giant trebuche and launch themselves to FUCKING URANUS. Ps. FUCK YOU7 - Mind blown! Microsoft invented the concept of touch bar way before apple. oO Surprises me how everybody is saying apple invented it.13 - - Oh the ups and down of learning code. One day you feel like a programming prodigy, the next you hit a concept that makes you feel like you'll never become a professional programmer. So much to learn!!!! 😭😭7 - - - Product team having a proof of concept demo with client: Sales to client: "Just for the record, we are not selling this to a rival company. Because we really want this technology exclusive to you" Me (thinking to myself): "Oh really? We just had a demo with them last 2 weeks" One of the core values of our company is Integrity, and I am not just seeing it. - Client: "We want you to build us a quick prototype / proof of concept. Don't make it too neat, we'll rebuild it before we go live." Also client: "We already have a working version, why would we rebuild it?" - Realizing no programming language or concept or theory is too hard to learn. My retinas may burn out staring at my screens but I will get there eventually.3 - - - When your company hires a third party to develop 2.0 version of your product after doing a proof of concept... Fml - - - When I was in college I used to think deadlock is just a theory concept. First c++ project on my job and I already have one now. 🙃 - - Client has a hand drawn logo. Which is really bad. We build a website with the same concept. Client keeps telling us the website doesn't look sophisticated enough. How do I tell them it's the childish logo?8 - - You guys ever thought about the concept that our universe might be a simulation written by some alien kid for a school project and got a C- for it? Yeah...perhaps I should go to sleep18 - The endorphins released when you suddenly get your head around a difficult programming subject, I just had mine with a cryptography concept. - - When they don't know about the concept of MVP (minimum viable product), expects everything to be perfect at v1.0 and wants it to be done ASAP #FML2 - - Every 2 or 3 weeks, a tech guy accidentally invents the concept of the city bus. Credits: @boring_as_heck1 - Designers that continually use non-webfonts, KNOWINGLY, and then get pissy when the site doesn't look EXACTLY like the concept.11 - if ur gonna explain a brand new goddamn concept and make a goddamn course or a goddamn series out of it then dont fcking goddamn copy and paste the godfuckingdamn code and just explain it WRITE THE CODE AND EXPLAIN IT1 - When you realize all personal projecrs end up being proof of concept prototypes working just for you and youd be ashamed if someone looked at the code behind it - Tried to simulate spreading of viruses in quarantined vs non-quarantined environment. Non-quarantined people are not understanding the concept of boundaries.6 - A friend of mine got into pentesting and his first idea was to try hack his own wifi, proof of concept. He got the cap file all professional and started crunching. He walks away and it two minutes starts screaming at me for the wifi being "too fookin slow" My friend is terminally stupid - Anyone else suffer from this. Have a brilliant idea, start computer, open you IDE, write a few lines of code as proof of concept and then just loose interests coz it's no longer a challenge - - - //No rant Guys today I released Shooter Retro my first Project for public but it's in total alpha and only basic game concept is working so if anyone test it go to my github account and download shooter.c from shooter-retro repository6 - - - Hey guys, I hope you don't mind me sharing here.. I just wanted to share some progress iv made on my game. It is officially out of concept phase now and I have upgraded to 3D. Check out my gameplay here:... If you want to follow development please come and read my blog. Thanks if you do :)29 - Give everyone the ability to intuitively grasp the concept of unix timestamps. No more timezones or DST, no more confusion about formats - The concept of manhours in our company. A project that is estimated to take 400 manhours can not be finished by 50 people on 4 hours.4 - . " - Mitch Hedberg - Have a somewhat good game idea/concept... Have no experience with game engines... This could take a while10 - Linkedin hunter per excellence. They are looking for “an experienced Expert for a position as Junior IT Consultant“. Well, I have some experience, but someone should really explain them the concept of being a Junior Expert...5 - Can anyone tell me the difference between VPN and this proposed concept of Mr. Wang? “Your Private Browsing Isn’t as Incognito as You Want It to Be” - Deleted accounts could have a skeleton/corpse as the picture. Adding "no offense" in the tags just to be a bit polite.8 - Has anyone installed Elasticsearch on Linux - centos to be specific. Trying to workout why the fucker won't install. Setting up a proof of concept so don't want to use it currently as SaaS. From why I can tell, it only needs Java, (check) and to be ran as a user other then root (check) but running ./bin/Elasticsearch hangs after a while and starts powering up 100 odd threads with no progress.6 - When sales starts selling a "concept" feature to a client because someone showed them a mockup of it in Photoshop. They say "don't worry they know it's going to take a month or two". A week later .. When are we getting that feature? 😑2 - I really don't know how LinkedIn works. The whole concept of connecting with random people is very weird. Pls explain.11 - !rant for any rock/metal fans, Avenged Sevenfold just released a new concept album (the stage) about artificial intelligence. It includes a spoken word section in the last song by Neil deGrasse Tyson!1 - In my short career, I've seen projects become legacy before their first release. Hell, I've seen proof-of-concept apps turn into technical debt because to management as long as it works we won't rewrite it. - - My internship company does not believe in the concept of 'commenting'. They just tell me: "Ahh just write readable code! Yeah that's cool until I need to read out thousands of lines of javascript without a single comment!5 - - Enlightened my colleague on the concept of JS promises, chaining of events, multiple deferrals... Ah, his code is looking much readable already! - - - Soon I will be talking about a new communication protocol between Raspberry Pi and Arduino ... At the meeting ... IoT enthusiasts. I am excited and slightly upset.7 - - Freshman out of the university started working for me as a php developer. Software Engineer from a major Australian university. First project, a WordPress plugin... Two weeks down the track I had to explain to him the concept of sessions and multiple visitors. WTF are they thought at universities these days?41 - - Last year I planned to start a startup. I've started many good things but not the startup yet. * A new data format * A new data type * A new web framework * A new concept for logging * And many other opensource tools and libraries2 - The first message sent over the early internet across the university, where the concept was developed, was supposed to be the word "login" The students sent "l" "o" and the system crashed. The students restarted and sent "l" "o" "g" "i" "n" successfully. This makes the first three characters sent over the Internet in history: lol8 - Why can't people be more objective on demands? These people can't fucking grasp the concept of "ask for something" NOOO they have to fucking make an endless black hole stupid speech to tell you to "do x"!!!! FUCK YOU WHO DO THAT!! YOU HAVE AN ASSHOLE WHERE SHOULD BE YOUR MOUTH! - - Made this app just for the fun of it. Let me know what you guys think about it. And do suggest places for improvement. 😃 Here's the link: - One of my fellow mate wants to run a python script on a click of button doesn’t understand the concept of web frameworks and it can’t be just with HTML6 - I built a basic MVP for a client as a proof of concept for his startup. It was a quick thing just to prove a point do I rattled it out in procedural php. Sadly it was successful and has somewhat taken off. It’s also grown arms and legs. It works. The user will never know, but the code is SHIT. I never thought it would still be here. I’m want to re-write it now in laravel. But...... ugh1 - Now the real question is are you even allowed to put React in your cv if you've never worked with redux, don't know the concept of HOC and still make pull requests with componentWillReceiveProps ?12 - Seriously, fuck sports fans. Imagine having to relate every conceivable concept through a scenario in sport to understand it. "How does that work?" "Okay, so imagine you've got this team, right..."2 - !rant && 'suggestion' What if we write cook book in pseudo code (or official development languages) instead of plain english so dumb fuck that can't follow a simple instruction like me could actually make something nice? def mayonnaise: mayonnaise = random.shuffle(['yolk', 'salt', 'pepper', 'mustard', 'vinegar']) while(mayonnaise not "thick"): mayonnaise.whip() mayonnaise.append('olive oil') mayonnaise.append('seasoning' || 'lemon juice' - - After I read clean code I talked to a fellow developer about some concepts. Later I reviewed some code of him and he clearly got the concept (not) Java ... If (isTrue(someValue))... public boolean isTrue(boolean value){ if(value == true) return true; else return false; }9 - Lets discuss Git Clients. Now I love electron, in concept. And I love what you can do with it, on paper. And I understand Github's need to jack itself off by developing its own framework just to make its own software in being what Github is, and then everyone else following suite because Github must know best. And that's my rant, I don't think it had a point. So, favorite git client and why?21 -.14 - - "The space between an idea and a concept is your lips. If you can’t say it out loud you can’t do it. " - Nick Longo - I got travel advertisments on my Windows 10 lock screen. I didn't remember how to get rid of them, so I had to search for it again. I was lead to this piece of fine irony on my screen. Staring at it felt like staring at the concept of art while it's staring back. This experience left me emotional. Thank you Microsoft and Windows Central. Thank you art, life, and love. Thank you ads.5 - > :) - In my life I have never had trouble researching a concept... Until now.. Never had so many fruitless endeavours, its getting frustrating.7 - - I just learned the concept of this thing called REST API and now here's GraphQL showing up on me face. Mother fucking web development hell. BRB. KMS4 - Adding a proof of concept directly to production and handing it over without a single test is God's blessing.1 - Architect: I know we said we would never do The Thing because doing The Thing is really bad, but can we do The Thing for a proof of concept? Me: How about Fuck No! Unless you are proposing a solution to fix The Thing, we are NOT doing The Thing just to satisfy some perverse curiosity you may be harboring.4 - working with UX/UI designers who don't understand the concept of style guides or reusable UI components is torturous, why don't they understand things work a bit different in real life than in Photoshop, Illustrator or Sketch - It's annoying when you're approaching the deadline on two separate projects and the AMs for both think their project is the most important. Leave me alone and let me do my job and both projects will get done, pester me and they won't. Pretty simple concept.3 - "If it were easy to nut out tricky design problems, I might be out of a job. But it’s also true that the cleverness in most lateral design doesn’t come from blindly grinding away at the same concept. When you’re dealing with ideas, it’s rarely a matter of simply putting in more time working. Five minutes can be much more fruitful than five hours." - Rob Morris1 - - This quote made my day. "Dependency Injection" is a 25-dollar term for a 5-cent concept. [...] Dependency injection means giving an object its instance variables. [...]."2 - When somebody demos a new app to the CIO as a functional product but turns out to be a concept prototype made with Origami without any proper code... literally a glorified PowerPoint with animations....3 - - Cengage's shit wanted me to rewrite Bubble Sort in Python. The test also said bubble sort was "the most efficient sorting method." How does one slap someone in the face with a concept? Someone's getting their shit pushed in with timsort.11 - Yay! Another meeting to go over a design concept for the next version of our website, awesome this makes meeting 163 - Freshly failed gloriously my degree in interaction design. Now I stumbled into a new job, doing a fullscale company advertisment campaign on cybersecurity for 6500 employees. Alone. Writing concept, gathering stakeholder, requirements and shit. I'm scared.4 - I have tried to combine the concept of Instagram and Reddit in this app. Now you can browse Reddit just like Instagram. Please install and tell me if you like the concept and what more modifications can be added Thank you. - Anyone have experience with Qt? I have been struggling with the whole Model/View concept for a QTableView all day, and I am at that panicking stage :..8 - - When you’re struggling, learning some new framework or concept and your friends still think the entire internet is made solely with html and css because they took desktop publishing in 9th grade. - - - - - I don't understand the concept of drinking tea or coffee. More over why is everyone is so surprised when I say "I don't drink tea or coffee." ??6 -...... - So I have been using REST APIs since last 4 years and used this term in lot of technical discussions with backend teams. Learnt that it's full form is 'REpresentational State Transfer' just a few minutes ago 🙈6 - Am on my way to a Meetup, giving a talk on a database class I've designed - bit different to the norm - hope they like the concept I came up with! - All u need is C folks seriously fuck the OOP concept you waste more time in a paradigm dilemmas than writing functional code. And that’s a damn fact. I feel sorry for the mobile developers that are stuck using the OOP methodology6 - Spent the day working on a concept for a Survival, Twin Stick Shooter, Tower Defence game. not sure if it will work yet, but everyone I have ran my Concept by really likes it. - - Working in a shared office space, everytime I hear somebody brag about the "AI" they have on their stack, I ask "Really? Can you show me where it sits??" just to see how confused they get thinking it might be a new tech concept.2 -) -?20 - What technology/concept/programming language did you learn that made you feel way way more brilliant? Me: Shell scripting, feel like god 😌21 -'ve come to accept the fact that when I first learn a new concept I'm not gonna know what the heck I'm doing with it until I code it for myself and break it and then fix it. Bugs help you learn. - - - As silly as it sounds, but migrating our company's web application from Ember/JSON API --> React/GraphQL would be a pretty solid achievement. We're almost to read-only feature parity at the moment with a single developers side time as a proof of concept. - Well, i when I was 13 I thought that a bit extra knowledge before programming in school would be nice, so I bought a book about the basics of java. The books never mentioned the concept of an IDE, so I just used the windows editor and command lines. And yes, you guessed right, the battles with the compiler were furious. - Turn my partner's idea into fruition. I'm trying GameMaker since the concept is a text based 2d game.2 -... - - - (As of Tuesday at 10:00 PM) We have a project with a hard due date Sunday. We have yet to get a proof of concept finished. My team has no grasp on reality or how long this project is going to take. I'm screwed. - - !rant Yes!!!! My AI has been born tonight...He may not "compete" yet but the foundation and concept is written and sound...now to just fill in the conditions and variables and he's going to be kicking player's butts in no time!2 - - I'm absolutely fuming why on earth would someone try to apply exactly all rules of a theoretical concept. I hate those so called "scrum masters". We can't apply all rules of agile we're not machines. There's real life and theory - I recently started a new job, where they introduced me to the concept of being handed a low-level technical design. They've hired me to be a keyboard monkey. -] - !rant Y'all ever heard of the Clingo language for Answer Set Programming? Fucking concept is blowing my mind. Taking a class on KRR(my graduate degree is all about A.I) and this shit is beyond interesting man.3 - Respect to all women in CS. They are in fact better when it comes to clean code and concept. Prof. Kamala Krithivasan, is teaching some hardest shit in CS. Turning Machine; - - I already built a compiler and an interpreter. ONLY ON THE THIRD TRY I realize that the hard part is the language design. lets hope Gerlang3.0 will turn out usable lol specs:... PS: I hate apes2 - I just came up with an idea while writing and I can't share it because I really need to trademark it first 😛😂 - I have a question for you guys and gals. Why did you start coding? For me, it was because I find the thought of making something that has never existed amazing. Truly amazing. Possibly changing the world from behind one screen is an exciting concept for me7 - Spiders; the only web developers that love finding bugs. Thinking of creating something using the "spider" concept, for developers and software engineers. Maybe it'll replace GitHub in our lives, maybe. And yes, I'm a bit drunk.1 - Our OS instructor gave us a written assignment about concept of Bootstrap, some of my course mates copy about BOOTSTRAP CSS(Front-end) at least 3 pages and the deadline is now - Quick question, because I have no idea how to Google it. The "block coding" concept that scratch is built upon, does anyone know if it's copyrighted in any way? Working on a project, where I'm thinking of implementing something like it - Does anyone else here think the regulating and centralising of crypto currencies and tokens worrying? It is slowly being bent to the will of the higher ups just like traditional fiat and they’re burying its fundamental altruistic design concept without providing and means for it to be assimilated into benefiting the daily lives of the masses an especially the unbanked.5 - Friendly reminder for hackathons, a great idea is better than a great app. I saw amazing creations, from a virtual reality rowing machine to a camera that read a Connect 4 game into a AWS server live. Yet, the hack that won the popular vote was an app that would tell your friend, through texts, where you were when you're heading over to pick them up. A simple concept to implement, but a great idea.1 - The concept of designing and building a testable application is apparently a very alien one to my colleagues. 1. The application cannot be used without gigabytes of data. 2. The application must be fully connected to all external systems at all times. 3. Convention over configuration is unheard of, so if you manage to achieve the above, it still takes hours to set up the damn thing. Apes. -. - - Just completed a 24 hour hackathon at my school in which the 'best software' winner purely had mock ups of yet another mobile app and had no proof of concept. Meanwhile my team developed a scaling platform online that adapts to groups of user's trends to create optimal results. I guess I keep misreading the definition of 'software' in the dictionary each morning. (RULE #8.2 - Software Engineers shall read the definition of the following phrases each morning excluding Saturday: software, heap, ego, scrum, algorithm, the documentation of C.". - First go through any getting started guides or introductory tutorials. Then depending on comfort level and available time, either start exploring further on your own or search for more advanced tutorials. Try to make use of what you learned, either at work or in hobby projects or small proof of concept programs, as the case may - Another dev concept butchered by business people: BDD, but does not integrate into any tests, uses arbitrary language and format, covers only happy path... Kill me now, please1 - Update Your Servers! Critical vulnerabilities found on Win Servers via RD gateways. Here is a source for the proof of concept: - - I hate all of the OS/langs circlejerks. I think anyone participating in them (in a serious manner) needs to fucking grow up and learn the concept of tools. TL;DR for any OS/lang discussion: Use the right tools for the right job.4 - AccuRev. Imagine version control software written by someone who read about the concept in a book once and who also never heard of UX. - Throw out the baseline, then inherit the new baseline we paid contractors to develop as a proof of concept using tech you don't know and maintain that. - Thanks to my parents to create an Application Context and autowire all my Dependencies required to live a happy life.. !!! The best framework that provides IOC -- Parents. Note: Finally understood spring framework IOC and DI concept.. many more to understand.. - !rant Do you think it is worth learning functional programming and specifically haskell. It seems like a really good concept, but a lot of people claim that it's not applicable in real scenarios.12 - I'm ok with almost every language. But this "everything is a function" concept of JavaScript always give me that "kill me painless and quick" itch !!!#":":/#*%¢|°° const fuuuuuuuuuck = require('fuckoff.js')1 - Dear facebook/instagram When in sandbox mode, please dont require https redirects, my localhost server has no concept of what an SSL cert is, its sandbox for a reason.5 - I am not even identifying with a specific language or stack any longer. I am an agnostic web developer that loves learning new things too much to hover over a mean or lamp stack forever. After a certain amount of experience, everything just seems to look the same anyways. PHP laravel, the same concept as C#'s .NET. Blade templating is the same concept as razor templating. React is the same damn concept as Vue and angular isn't too far from either of them. Everything starts to just lose individual importance and starts to morph into web development as a whole. All of a sudden I see why language and framework are not of that high importance. Knowing how to template, how to define routes, how to implement MVC, how to create a generic REST API. The principles start taking importance and the technology of choice becomes less of importance - - I would hack the heck out of Roslyn Analyzers! Everything that could be f*ckin detected at compile-time _would_ be f*cking detected at compile-time. All those freaking config files usages, or attributes/reflection. Analyzers for everything, with sensible error messages! (Although I realize I that's overstretching the concept of unlimited - Anybody here that uses ratpoison wm?? Can you recommend me configurations to make it look cool? There aren't much documentation. P.S. Please don't recommend another wm, I loved ratpoison's concept so I want to give it a try.4 - The concept of personal assistant programs is really starting to take off, and I'm super excited to see what is going to happen in the future3 - "For me, discomfort is a signal of an exceptional concept. When I’m totally comfortable with a concept, I’ve probably used it fore or seen it somewhere else. Discomfort is almost a prerequisite for a great idea." - Craig Frazier - When a client keeps asking about how a new feature works... Have you even bothered to read the fucking concept? IT'S ALL - self refrencing tables awesome concept but it pisses me off that mysql doesnt support "select with" query i had to think about writing recusive functions that builds a tree of n level i must say im kinda proud :p2 - Trying to implement DDD into this current project of mine but the whole concept of converting Eloquent objects into plain entities seems to be more work than it is worth. But the whole methodology of DDD also seems rather complicated.2 -. - Who the heck made this concept of exams. Don't wanna study for my sessional which will be in next 10 hrs. I am screwed😭😫2 -: - Today I have practically learned the concept of geometric progression. A db table of 5 Gb now it's 500 Mb.3 - I'm working on a concept for an efficiency/speed focused networking project. Any recommendations for low-level languages that support networking that can be run on both windows and Linux with relative easy? Thanks in advance. - So, my simulations started to take about a week to complete. Productively invested the time in getting into Python! I'm really liking its syntax and relative simplicity (coming from c++) and I'm kinda digging it at a sort of proof-of-concept producer: instead of talking in pseudocode I can just put down a python script to show what I mean. - Question about GPG: So I understood the concept and successfully applied it to my Gitlab, but how helpful is it? From what I understood it helps detecting which commits are from verified authors and which are from just someone who has access? I'd appreciate if someone explains more on how helpful it is :)5 - Css positioning is harder to understand than the full OOP concept. So i wanted to create a very simple page with a single css file. I spent 2 hours to position the buttons in the fixed header and center some things. I got the whole OOP concept with abstraction, polymorphism and inheritance in an hour and could use it right after without problems. Holy shtcake i never want to do frontend.8 - i was wondering Is it true when people do drugs they code alot better? All where I see this concept.6 - - . - These days I now spend more time each week fucking about with Docker and VMs than I ever did when we were setting up the local environments ourselves. I love the concept of Docker, but it seems to create more problems than it solves.2 - Preparing for an interview tomorrow, am a nervous wreck. It's worse when you actually want the job and not just browsing through. The concept of your peers poking holes in your reasoning and deciding you're inadequate is far from appealing.3 -) - So I did this little experiment PWA caching and service worker which caches entire website (js/css/html) [It's a small website]. Now I do not understand the concept of PWA caching entirely because when I 'Add it to Home screen' it becomes an app as expected but when I turn off the internet and then open the app it requires the internet. What in fucking ass, why won't you just render those html pages which are cached ?16 -. - Well my PO introduced the concept of owning stories (which we naturally used to do) in our pairing environment. After we gave names, we started seeing each other like seven different kingdoms. Suddenly my PO looks like Cersei. And I am looking like Theon Greyjoy, hardly worried about other stories and stuck with no pair to complete my stories. That's how pair programming died a casual death. P.S : Tomorrow is my (our) demo !! 😭😭 - - Does anyone know whats the concept for creating an ios app that fire notification everyday at 5am with different message set for each day. #xcode #swift16 -: - I start website with Databases, it work well but I want to upgrade with new feature. Some features could be better in an other site. So I build another website with many features and think about new widget and concept. I start another one again and again and again... Does I am the only one to do that? - what I am doing is reading mathematics as people say developer needs good concept of mathematics poor me 😂😂😂😂3 - Guys and gals, what's tour opinion on static website generators? Have you ever used one? The concept kind of intrigues me and I was considering a Hugo + Travis CI stack.7 -. - We need to test the last step in our proof-of-concept chain before putting our project proposal... but just before testing what we believe will be (finally) a functioning scenario, the key service we need and have no influence over stopped working. I am pretty sure, it will start working like 5 minutes before I usually leave.. one has to love this waitNRush development. - What if we have a AI that will build code what ever we say? Is it be a new concept or new programming , it would so easy to build any software. Maybe in a future some one will do this I hope.3 - Status meetings. Jesus, some people don’t understand the concept of “take your discussion offline” Yeah, we get it. You have questions... we are not all wasting our time to fix your issues in one meeting. “Take it the fuck offline” - I really don't like the approach that the elementary OS developers took to their system. A closed system like that is antithetical to the whole concept of building on an established base... Which is what they're bloody well doing in the first place!4 - TLDR; Please give me some feedback on the design (again) So guys, a while back I posted a post (link in comments) with a design for a concept app for poules. Now I've processed some feedback from you guys and from some friends. Meaning I added some gradients and made the design way easier. Here is the newer version!3 - Angular and is best friend RxJs are too over engineering and far from the concept of 'keep it simple, stupid' But just a moment they're both use typescript to design there interfaces ... maybe that is the fucking reason for that !2 - What happened to Project Looking Glass? I still wonder, it seemed like a revolutionary concept but we have come to flatness from glassy skeumorphism. - - Which skills and platform do I need to focus as a ASP.NET back end developer? The .NET development environment is so massive, I really don't know from where do I need to start. I do know basic C# syntax and was studying C# 7.0 in a Nutshell and stopped temporarily because it introduced too much concept that I don't need for now. Any advice will be appreciated. Thank you!4 - So... An MVP is nothing that a prof of concept that you have to develop for yesterday but then it should evolve and be maintained and upgraded forever (keeping the profit and ahead of competition) . No wonder developers quit!3 - What tool/process/concept saves you the most time in your day-to-day work? I'm looking for things I could integrate into my own work that would make me or my team more efficient1 - - - In react.js?... with react visual-DOM concept, does it fully support and work well with third party libraries ??6 - HI I started to learn Angular I have created some small projects but sometimes I think I shall not be good at programming. I always think about how will I improve it. I am doing lots of practics but the thing is that I forget concept after some time I am not feeling well and always think that I will never be a good programmer.1 - I'm creating a game for my final major project a college. Doing some primary research would be greatly appreciated if you can fill this survey out. Share around if possible. Thanks - - Web, particularly the mobile web. Why? I just found the concept of platform silos to be dumb. I want my creations to be experienced by as many people as possible. - New device: "iPhone air" There is nothing other than air. Yeah, you just assume that there is an iPhone. Or you don't, it's completely up to you. we are ~Apple~ - Ehm, ok, i'll code this new event calendar concept, but do you realy think it's cool as you think? . . . At least i can take it as a practice and than throw it to the trash as always.7 - I'm SO FUCKING PROUD of whoever put this here. It's besn forever since anyone's even mentioned memes as a concept in my high school, much less done/written something for the meme.1 - Ok! My new project still haven't started and I'm so bored , running out things to look into!!! So far I have looked into Firebase Ethical Hacking Some web developing concept... Any suggestions??? Related to web developing, laravel , vuejs ???1 - The mind of The Flash. You know, able to think quickly and fast. Then I can solve a lot problems in a nick of time, or learn a new concept or language quickly. Yeah, that'll help me a lot.1 - - - Do you know where to get Windows App Signing Keys for a reasonable price? The cheapest ones I've found were still ~€150 per year, too much for a proof-of-concept :( Not signing the app is not an option...13 -?5 - - "I think advertising is a brilliant concept that has been pooped upon by selfish marketers, resulting in corrupted motives and flawed execution." - Michael Mistretta3 - I was very interested with the concept of programming and so I downloaded varies IDE's one of which was Android studio, I didn't have interest in it at first but one day I was bored and decided to open Android studio and play around placing varies components making a very uninteractive app and the feeling I got was unexplainable and I knew that this was going to be my passion.1 - - - - - "When Einstein realized, 'Dear me, this universe with its wonders all adds up to E=mc2?,' he did not stop to think whether this concept would sell better set in Futura or Antikva." - Kari Piippo9 - !rant Does anyone here know CodinGame.com? I just discovered it and wondered weather some of you know it and "play" it. I think it's a very intersting concept, good for training and a good opportunity to challenge yourself. -' - - - First time pithing about startup concept in startup bootcamp, 2 fucking dead air (fuck....) but I'm able to finish my pitch in time. (Feeling relief now) - ❓Question: I've recently been introduced to reactive programming, and I'm wondering some things about it - How new of a concept is it? - Can it be declared as a third type of programming compared to OOP & FOP? - How common is it? - -? - While conceptualizing, coming up with the best idea is like meeting your soul-mate. It just feels right. - Samadara Ginige -
https://devrant.com/search?term=concept
CC-MAIN-2020-34
refinedweb
6,606
72.56
what I'm trying to do is create a class and demo class that receives length and width of two land tracts, displays the area and makes use of an equals method to compare the areas... and throw in a toString just for kicks. here is my first class: public class LandTract { private double length; private double width; double areaA; double areaB; public LandTract() { } public LandTract(double len, double wid) { length = len; width = wid; } public double getLength() { return length; } public void setLength(double length) { this.length = length; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getArea() { return length * width; } public String toString() { String string = "The area of the land is: " + getArea(); return string; } } here is the demo: import java.util.Scanner; // needed for user input from keyboard public class LandTractDemo { public static void main(String[] args) { double length; double width; double areaA; double areaB; LandTract landA = new LandTract(0.0, 0.0); // two instances LandTract landB = new LandTract(0.0, 0.0); Scanner keyboard = new Scanner(System.in); // keyboard input System.out.print("What is the lenth of the 1rst tract of land? "); // get and set data for landA length = keyboard.nextDouble(); landA.setLength(length); System.out.print("What is the width of the 1st tract of land? "); width = keyboard.nextDouble(); landA.setWidth(width); landA.areaA = length * width; System.out.println(landA.toString()); // output the 1st area System.out.print("\nWhat is the lenth of the 2nd tract of land? "); // get and set data for landB length = keyboard.nextDouble(); landB.setLength(length); System.out.print("What is the width of the 2nd tract of land? "); width = keyboard.nextDouble(); landB.setWidth(width); landB.areaB = length * width; System.out.println(landB.toString()); // output 2nd area if (landA.equals(landB)) System.out.println("\nThe two landtracts are of equal area."); else System.out.println("\nThe two landtracts are not of equal area."); } } I cannot seem to get the equals method to work correctly.
http://www.dreamincode.net/forums/topic/179198-help-with-equals-method/
CC-MAIN-2016-44
refinedweb
327
67.55
Introduction Seaborn is one of the most widely used data visualization libraries in Python, as an extension to Matplotlib. It offers a simple, intuitive, yet highly customizable API for data visualization. In this tutorial, we'll take a look at how to plot a Line Plot in Seaborn - one of the most basic types of plots. Line Plots display numerical values on one axis, and categorical values on the other. They can typically be used in much the same way Bar Plots can be used, though, they're more commonly used to keep track of changes over time. Plot a Line Plot with Seaborn Let's start out with the most basic form of populating data for a Line Plot, by providing a couple of lists for the X-axis and Y-axis to the lineplot() function: import matplotlib.pyplot as plt import seaborn as sns sns.set_theme(style="darkgrid") x = [1, 2, 3, 4, 5] y = [1, 5, 4, 7, 4] sns.lineplot(x, y) plt.show() Here, we have two lists of values, x and y. The x list acts as our categorical variable list, while the y list acts as the numerical variable list. This code results in: To that end, we can use other data types, such as strings for the categorical axis: import matplotlib.pyplot as plt import seaborn as sns sns.set_theme(style="darkgrid") x = ['day 1', 'day 2', 'day 3'] y = [1, 5, 4] sns.lineplot(x, y) plt.show() And this would result in: Note: If you're using integers as your categorical list, such as [1, 2, 3, 4, 5], but then proceed to go to 100, all values between 5..100 will be null: import seaborn as sns sns.set_theme(style="darkgrid") x = [1, 2, 3, 4, 5, 10, 100] y = [1, 5, 4, 7, 4, 5, 6] sns.lineplot(x, y) plt.show() This is because a dataset might simply be missing numerical values on the X-axis. In that case, Seaborn simply lets us assume that those values are missing and plots away. However, when you work with strings, this won't be the case: import matplotlib.pyplot as plt import seaborn as sns sns.set_theme(style="darkgrid") x = ['day 1', 'day 2', 'day 3', 'day 100'] y = [1, 5, 4, 5] sns.lineplot(x, y) plt.show() However, more typically, we don't work with simple, hand-made lists like this. We work with data imported from larger datasets or pulled directly from databases. Let's import a dataset and work with it instead. Import Data Let's use the Hotel Bookings dataset and use the data from there: import pandas as pd df = pd.read_csv('hotel_bookings.csv') print(df.head()) Let's take a look at the columns of this dataset: hotel is_canceled reservation_status ... arrival_date_month stays_in_week_nights 0 Resort Hotel 0 Check-Out ... July 0 1 Resort Hotel 0 Check-Out ... July 0 2 Resort Hotel 0 Check-Out ... July 1 3 Resort Hotel 0 Check-Out ... July 1 4 Resort Hotel 0 Check-Out ... July 2 This is a truncated view, since there are a lot of columns in this dataset. For example, let's explore this dataset, by using the arrival_date_month as our categorical X-axis, while we use the stays_in_week_nights as our numerical Y-axis: import matplotlib.pyplot as plt import seaborn as sns import pandas as pd sns.set_theme(style="darkgrid") df = pd.read_csv('hotel_bookings.csv') sns.lineplot(x = "arrival_date_month", y = "stays_in_week_nights", data = df) plt.show() We've used Pandas to read in the CSV data and pack it into a DataFrame. Then, we can assign the x and y arguments of the lineplot() function as the names of the columns in that dataframe. Of course, we'll have to specify which dataset we're working with by assigning the dataframe to the data argument. Now, this results in: We can clearly see that weeknight stays tend to be longer during the months of June, July and August (summer vacation), while they're the lowest in January and February, right after the chain of holidays leading up to New Year. Additionally, you can see the confidence interval as the area around the line itself, which is the estimated central tendency of our data. Since we have multiple y values for each x value (many people stayed in each month), Seaborn calculates the central tendency of these records and plots that line, as well as a confidence interval for that tendency. In general, people stay ~2.8 days on weeknights, in July, but the confidence interval spans from 2.78-2.84. Plotting Wide-Form Data Now, let's take a look at how we can plot wide-form data, rather than tidy-form as we've been doing so far. We'll want to visualize the stays_in_week_nights variable over the months, but we'll also want to take the year of that arrival into consideration. This will result in a Line Plot for each year, over the months, on a single figure. Since the dataset isn't well-suited for this by default, we'll have to do some data pre-processing on it. import matplotlib.pyplot as plt import seaborn as sns import pandas as pd df = pd.read_csv('hotel_bookings.csv') # Truncate df = df[['arrival_date_year', 'arrival_date_month', 'stays_in_week_nights']] # Save the order of the arrival months order = df['arrival_date_month'] # Pivot the table to turn it into wide-form df_wide = df.pivot_table(index='arrival_date_month', columns='arrival_date_year', values='stays_in_week_nights') # Reindex the DataFrame with the `order` variable to keep the same order of months as before df_wide = df_wide.reindex(order, axis=0) print(df_wide) Here, we've firstly truncated the dataset to a few relevant columns. Then, we've saved the order of arrival date months so we can preserve it for later. You can put in any order here, though. Then, to turn the narrow-form data into a wide-form, we've pivoted the table around the arrival_date_month feature, turning arrival_date_year into columns, and stays_in_week_nights into values. Finally, we've used reindex() to enforce the same order of arrival months as we had before. Let's take a look at how our dataset looks like now: arrival_date_year 2015 2016 2017 arrival_date_month Great! Our dataset is now correctly formatted for wide-form visualization, with the central tendency of the stays_in_week_nights calculated. Now that we're working with a wide-form dataset, all we have to do to plot it is: sns.lineplot(data=df_wide) plt.show() The lineplot() function can natively recognize wide-form datasets and plots them accordingly. This results in: Customizing Line Plots with Seaborn Now that we've explored how to plot manually inserted data, how to plot simple dataset features, as well as manipulated a dataset to conform to a different type of visualization - let's take a look at how we can customize our line plots to provide more easy-to-digest information. Plotting Line Plot with Hues Hues can be used to segregate a dataset into multiple individual line plots, based on a feature you'd like them to be grouped (hued) by. For example, we can visualize the central tendency of the stays_in_week_nights feature, over the months, but take the arrival_date_year into consideration as well and group individual line plots based on that feature. This is exactly what we've done in the previous example - manually. We've converted the dataset into a wide-form dataframe and plotted it. However, we could've grouped the years into hues as well, which would net us the exact same result: import matplotlib.pyplot as plt import seaborn as sns import pandas as pd df = pd.read_csv('hotel_bookings.csv') sns.lineplot(x = "arrival_date_month", y = "stays_in_week_nights", hue='arrival_date_year', data = df) plt.show() By setting the arrival_date_year feature as the hue argument, we've told Seaborn to segregate each X-Y mapping by the arrival_date_year feature, so we'll end up with three different line plots: This time around, we've also got confidence intervals marked around our central tendencies. Customize Line Plot Confidence Interval with Seaborn You can fiddle around, enable/disable and change the type of confidence intervals easily using a couple of arguments. The ci argument can be used to specify the size of the interval, and can be set to an integer, 'sd' (standard deviation) or None if you want to turn it off. The err_style can be used to specify the style of the confidence intervals - band or bars. We've seen how bands work so far, so let's try out a confidence interval that uses bars', data = df) plt.show() This results in: And let's change the confidence interval, which is by default set to 95, to display standard deviation', ci='sd', data = df) plt.show() Conclusion In this tutorial, we've gone over several ways to plot a Line Plot in Seaborn. We've taken a look at how to plot simple plots, with numerical and categorical X-axes, after which we've imported a dataset and visualized it. We've explored how to manipulate datasets and change their form to visualize multiple features, as well as how to customize Line Plots. If you're interested in Data Visualization and don't know where to start, make sure to check out our bundle of books on Data Visualization in Python: Data Visualization in Python .
https://stackabuse.com/seaborn-line-plot-tutorial-and-examples/
CC-MAIN-2021-17
refinedweb
1,559
62.48
Q&A on MicroPython Multi-threading and Garbage Collector - Bettina administrators last edited by As we completed the MicroPython Multi-Threading and Garbage collector features with Damien George we sat down with our CTO Daniel to take a look at what that means for the use of the scripting language. Here’s the resulting Q&A. Q: Why did you decide to fund Multi-Threading and a re-entrant Garbage Collector? A: MicroPython is already feature packed and 99% equivalent to the CPython implementation of Python 3 in most of its aspects. Apart from giving you the expected built-in functionality features like tuples, list, dictionaries, strings, byte objects, floating point and complex math, a file system, BSD sockets and an interactive prompt, it also provides a simple, yet powerful hardware API that let’s you access all the peripherals of a microcontroller in a very elegant way. Handling analog to digital converters, serial interfaces like SPI and I2C, or even GPIO pins are not common things that you’ll do on a PC, but those are one of the main tasks performed by an embedded system, and there’s therefore a need to provide a flexible API for those features in MicroPython. The peripherals in a microcontroller involve mostly input/output operations, which take time to execute, and more often than not, block until they are complete. When operations block, then the need for multiple “threads” of execution arises to allow for other tasks to run while others are blocked and waiting for an I/O transaction to finish. There are other ways to work around the blocking I/O problem, like using an event loop with cooperative tasks, but such mechanisms are not very natural for most software developers, and doesn’t really fit well into the Python programming model. Q: What are those features useful for? A: A typical IoT application goes like this: - A device connects to the Internet via WiFi, - it collects data from sensors and sends it to a server in the cloud. Most likely, - it’ll also receive data and control commands from the server to adjust it’s behavior based on certain parameters. In some cases, it could also have a user interface (switches, LEDs, a display, etc.) Things will seem to work until something happens, for instance the WiFi connection is lost and the device needs to re-connect. During the seconds the WiFi connection is being re-established, nothing else happens, no more data comes from the sensors, and the user interface doesn’t respond, and that’s no good. Maybe some of the sensors are slow, which means that when reading data, the communication with the server may stall. Remember those times when your PC application crashes and your mouse stops moving for several seconds? That’s what happens here too. The solution is to have for instance 3 threads. One thread that handles the WiFi and the Internet connection. Another thread takes data from the sensors, and the third one controls the application logic and the user interface. The threads communicate via queues and semaphores which let them share data and stay in sync. That way no thread waits for the other and the application can work more seamlessly without interruption. Q: What can you do on the WiPy/LoPy that you couldn’t do before? A: You can use blocking sockets, for instance. You can divide the tasks of your application into several threads of execution with different priorities. To do this you use the _thread module which over the most low-level features, or the threading one. Here’s some example code: import urllib2 from threading import Thread def url_test(): for i in range (10): page = urllib2.urlopen(“”) for i in range(10): t = Thread(target = url_test) t.start() Q: Will Pycom fund other features of MicroPython? A: Yes, that’s very likely. We have great ambitions for our products and MicroPython is one of the enablers for fast IoT applications which is one of our core promises. Plus we like giving stuff back to our growing community of developers and funding future features is a way of achieving that. Q: In your opinion what should be the next thing MicroPython should have developed as features? A: The next feature should be the ability to run compiled byte code directly from the flash memory of the microcontroller. This will have the advantage of being able to run literally infinite Python code while leaving the entire RAM space for the data of the application thus speeding things up. I am just started to dig into to threading, but my understanding is that pycom only support _thread, which has limited functionality compared to threading. Like lack of .start or .stop. Is my understanding false? Cause the sample code is not working on my wipy. Does that mean standard MicroPython will also have multithreading? It already does. The feature is part of the core. The unix and the cc3200 ports have it implemented as well. Interesting. Looks like PyCom managed to influence MicroPython more than some discussions on their Forum and Github. Does that mean standard MicroPython will also have multithreading? Is there a list of features you intend to fund? Can you add tail-call optimisation to that list? ;-)
https://forum.pycom.io/topic/3/q-a-on-micropython-multi-threading-and-garbage-collector
CC-MAIN-2022-33
refinedweb
881
61.97
The Inevitability of Russiagate Jim Comey’s dramatic testimony last week significantly ratcheted up the intensity of the greasefire engulfing Donald J. Trump, whom it still pains me to describe as the President of the United States. Yesterday’s tap dance recital by Confederate General Jefferson Beauregard Sessions III, and the astonishing rumors that Trump is contemplating firing special counsel Robert Mueller have only added fuel to those noxious flames. For those who dislike Trump but have been skeptical of any skullduggery with Russia, the shift to obstruction of justice as the likely grounds on which Trump will find the locks changed on the Lincoln Bedroom is very welcome. “The coverup is always worse than the crime” as the cliché goes, although in this case the potential crime — conspiring with a foreign power to throw a presidential election — is actually a fuckload worse than any coverup. Regardless, Trump is tailor-made to create more problems for himself with his predilection for Mob-like tactics to intimidate investigators and squash an honest inquiry. Even if there ultimately proves to be no there there on Russia (and that’s a big “if”), Trump is creating reasons to justify his removal with an almost kamikaze-like determination. So for that very reason we have to ask: WHY IS HE DOING THAT? Why take such extreme measures to block an investigation at every turn — and at such risk to his presidency — if the allegations regarding Russia are false? It certainly does not convince anyone that he has nothing to hide, not even those predisposed to give him the benefit of the doubt (a group largely limited to Klan rallies and sexual predator chat rooms). Some on the left — notably Glenn Greenwald — have scorned the progressive fixation on possible Trump collusion with Russia as wishful thinking, a left wing indulgence in tinfoil-hat conspiracy theory more characteristic of the right wing lunatic fringe, and a waste of valuable energy better spent fighting the loathsome Trump agenda. In its most critical version, Russiagate is a liberal analogue to birtherism, a handhold for an enraged opposition party desperate for a reason to declare a hated presidency illegitimate. (The analogy is imperfect at best, of course. Birtherism was a racist fantasy without the slightest basis in reality. Russiagate is at least plausible — highly plausible, in fact — even if it is eventually disproven. We shall see. But the right’s unconvincing attempt to depict it as a “fairytale” smacks of a carefully coordinated media strategy, to include a directive to use that term, judging by the suspicious frequency with which it pops out of the mouths of Trump apologists.) But I do understand the criticism. It’s almost too much to hope that this horrific administration did something so criminal, so self-destructive, so blatantly treasonous that it would bring about its own downfall. But the other equally believable way of looking it this phenomenon is that the two threads are inherently connected.? So in that sense Russiagate is not an aberration or the fulfillment of liberal magical thinking at all, but the logical conclusion of a leader and an administration this abominable. Admittedly, the scope and scale of the crimes of which Team Trump is accused are so outlandish that they would embarrass the worst airport spy novelist. But there you have it. RUSSIAN ROULETTE WITH SIX CHAMBERS FILLED So let’s stop for a moment to take a quick survey of what we know about Russiagate thus far. Obviously, our information is very very incomplete. I remain confident that the truth will come out as result of Bob Mueller’s inquiry — unless Trump fires him — along with the efforts of the Senate Intelligence Committee, and to a lesser extent its counterpart in the House (compromised by its chairman, the oleaginous Trump toady Devin Nunes), and we may yet see an independent commission as well. What Congress does about the conclusions those entities come to is another matter. But even the incomplete, raw facts we already know are rather damning when viewed by anyone with a shred of objectivity. The Russians interfered with the 2016 presidential election with the express purpose of helping Donald Trump win. That is not in dispute by any serious observer. Trump himself actively encouraged Russia to hack into the computers of his Democratic rival, which it did. Unwittingly or not, Trump also personally helped spread disinformation — “fake news” — that had been generated by Russia to hurt Hillary Clinton. And both during the campaign and in the transition period, Trump associates had improper contacts with Russian officials, including intelligence officers. All seventeen US intelligence agencies concurred on the issue of Russian interference, which was corroborated by independent reporting by the most respected journalistic organizations in the country, as well as allied intelligence agencies who were the first to warn the US government of what was going on. Only Trump’s most fanatic followers believe otherwise, and of course Trump himself, who evidently is so insecure about the legitimacy of his presidency that he lives in dread fear of anything that suggests he did not win with a North Korean-like 100% of the vote. None of that looks good for Trump. And that stuff doesn’t even rise to the level of active collusion, which would be an actual act of treason. So at a bare minimum one might be justifiably outraged at Trump’s relationship with Russia even without believing he or his people are outright traitors. But do we think Trump and his people actually even further? Again, let’s look at the record. Cui bono, as they say. Who benefits? The Trump administration’s eagerness to do favors for Russia while getting nothing in return (that we know of) is eyebrow-raising to say the least. Among the gifts: lifting sanctions imposed by the Obama administration, prevailing on the GOP to change its platform on Ukraine and Crimea, and returning to the Kremlin a pair of mansions in Long Island — openly known to be spy facilities — that Obama took away in retaliation for Russian misbehavior. The capper — thus far — has been Trump’s jawdropping decision to hand over to Moscow top secret compartmentalized information passed to the US by Israel, without Tel Aviv’s consent or foreknowledge, not to mention that of anyone in the US intelligence community. That unfathomable action may well have been a function of Trump’s well-known eagerness to brag and impress, rather than of any duties as a Russian stooge. But it speaks to his level of comfort with the Kremlin and his ignorance both of diplomacy and the basics of handling classified material, to say nothing of general idiocy and unfitness for office. Trump’s behavior during the recent NATO summit, in which he excoriated our oldest and staunchest allies while refusing to reaffirm Article 5 mandating collective defense was a wet dream for Putin. As many noted, Trump may or may not be a Russian asset, but in Brussels he behaved exactly as the Kremlin would have wanted a Russian asset to behave. In shaking confidence in a mutual defense pact that has kept Europe secure for more than seventy years, Trump’s performance could not have better served Russian interests if the Kremlin itself had scripted it. Hmmmm. Of course, an affinity for Russia is pervasive in Trumpworld. Trump’s former campaign manager Paul Manafort was a paid flack for Russian political interests, which was why he was forced to resign. Steve Bannon and the so-called “alt-right” (let’s just call them what they are: neo-Nazi white supremacists) are deeply enamored of Russia for their own twisted quasi-eugenic reasons. And Trump himself famously has never had a bad word to say about Vladimir Putin: this from a man who has picked fights with the Pope, a Gold Star familiy, beauty queens, Meryl Streep, the cast of Hamilton, and the prime minister of Australia, just to name a few. Yes, it could be that Trump merely admires a preening bully like Putin, which would be of a piece with Trump’s own self-image and man-crushes on various other so-called strongmen, from Duterte to Kim Jong-un to the Saudi royal family. But the weirdness, consistency, and intensity of his Russophilia is highly suspect. It’s hard to believe that there aren’t more concrete motives in play. WHAT’S MY MOTIVATION? So what can we conclude from all this? Again, lawyers, investigators, and Congressmen will deliver the evidence, but as private citizens we are within our rights to speculate. The most extreme and baroque scenario, of course, is that Trump is being blackmailed by the Kremlin and as a result is their clandestine agent. (Not very clandestine, actually, but that’s the idea.) The possibility that the Kremlin has compromising salacious information on Trump as alleged in the Steele Dossier (one of my favorite Ludlum novels) seems farfetched, although Trump’s adolescent fixation on his sexual escapades does not help his argument. Apparently in his many meetings and conversations with Comey, Trump was far more agitated about the alleged “golden shower” tape than anything else. What is not farfetched at all is the possibility that Trump’s business interests are heavily entangled with the octopus of Russian organized crime, government, and security services (which for all practical purposes are merely separate tentacles of the same rapacious beast), incentivizing him to act favorably toward Moscow without being an actual controlled “asset” in the strict sense of the word. Of course, since Trump won’t release his taxes — and the Republican Party and rank-and-file are acting like that’s acceptable — we don’t know. Perhaps the emoluments suit recently filed by the Attorneys General of Maryland and the District of Columbia will force his taxes to light. Trump has claimed he has no business ties to Russia, which we know to be patently false. His own sons have bragged about all the money the Trump family businesses get from Russia. Again, tax returns would be helpful in sorting out truth from Pinocchio-isms, which is precisely why Trump won’t release them. Rachel Maddow has extensively documented Trump’s involvement in real estate sales tied to his massive debt to Deutsche Bank, which extends to laundering illicit Russian money through a sketchy Caymans Island bank — is there another kind? — run by associates of Putin (which is to say, by Putin). One of the chief officers of that bank — and this is almost beyond belief — is the man who is now the United States Secretary of Treasury under Trump, Wilbur Ross. In normal times that would be a front page international scandal, but in the current climate it’s just Tuesday. So short of water sports with Russian hookers and/or a Manchurian candidate brainwashing, the most plausible scenario seems to be that Trump simply does not want to piss off people who have great financial leverage over him, or through whom he makes a lot of money , or both. Not very titillating, but very very believable. And that is the most charitable interpretation that the facts allow. For Trump, it only gets worse from there. WHAT ARE THEY TRYING TO HIDE? Perhaps the most damning and suspicious point of all is this simple question: If all of the Trump team’s contacts with the Russians were innocent, why do the White House and members of Trump’s inner circle keep lying about those contacts? That dog quite plainly does not hunt. Which brings us back to the original question. Why so desperately try to dodge and undermine the Russiagate investigation unless there is something incriminating to hide? Jeff Sessions lied under oath, claiming he had never had any contacts with the Russians as a Trump surrogate, then was exposed as having had at least two clandestine meetings with Russian ambassador Sergei Kislyak, the Kremlin’s top spy in the US. Mike Flynn and Jared Kushner similarly failed to disclose such contacts with Russian officials. Flynn also failed to mention that he was a paid agent of a foreign power — Turkey — and had even intervened on Ankara’s behalf to halt long-planned US military operations against ISIS that the Turks opposed. (This from a retired three-star general and career intelligence officer who during the campaign self-righteously railed over Hillary Clinton’s possible carelessness with classified material, memorably leading bloodthirsty chants of “Lock her up.”) Kushner floated a proposal to the Russians so startling that even they were caught off guard: that the Trump team use Russia’s own secure secret communications network for a backchannel to the Kremlin to prevent US intelligence from listening in. Kislyak, Lavrov, & Co. didn’t realize that they would soon be getting top secret compartmentalized information handed to them on a silver platter from the President himself during a face to face meeting in the Oval Office. It is hard to believe that Sessions, Flynn, and especially a callow neophyte like Kushner undertook those actions on their own initiative and without Trump’s knowledge. It’s far more likely that they did so at his direction. Obviously, that is an explosive conclusion and one that Mueller and the other prosecutors will have to prove, if they can. But purely as a matter of common sense, it is difficult to believe that Trump was not involved. Why has Trump been so desperate to stop the investigation into Michael Flynn’s actions, to the point of sacking the director of the FBI over it? Is it just because he is so loyal to Flynn, a man he also summarily fired? Uh, maybe. But far more likely is the simplest and most obvious explanation of all: Because he ordered Flynn to take those actions. “I’M AS SORRY AS YOU ARE, DMITRI” Needless to say, there is some irony in Americans expressing shock and outrage at Russian meddling in our election, given the long history of American meddling in foreign elections (and by “meddling” I’m including covert CIA attempts to overthrow foreign governments by force). Governments try to influence foreign elections all the time, sometimes in benign ways and sometimes more maliciously. We don’t have to like it or tolerate it, but it’s naïve to be shocked by it. What is genuinely outrageous, however, is the idea that American citizens would collaborate with such efforts, or condone others doing so, which is what the overwhelming majority of Republicans are brazenly doing. Polls show that tribalism in America is so extreme at the moment — at least on the right — that few Republican voters say they would be bothered even if hard evidence emerged that Trump did in fact conspire with the Kremlin. Let’s stop and take that in a moment. Wow. The reasons given are usually on the order of “Ah, all politicians do that sort of thing,” or “Hillary’s done/would do worse,” or “Whatever it took to keep Hillary out of office, I’m fine with it.” Such thinking does not deserve to be dignified with a response, but you can imagine for yourself what those same voters would likely have said if the roles were reversed and Barack Obama or Hillary Clinton were suspected of conspiring with Vladimir Putin to throw the election. Hell, the Tea Party wanted to lynch Barack just for putting his feet up on his desk. (OK, to be fair, they wanted to lynch him because he’s black. But they got pretty upset about the desk thing.) In his testimony, Jim Comey made plain that Russia executed a shocking, extensive, and well-planned act of war against the United States and other Western democracies and will continue to do so. To much less public fanfare, former Director of National Intelligence James Clapper recently testified that the possibility of Trump/Russia collusion dwarfs Watergate, making it arguably the worst scandal in American history. The Russian effort represents a far more serious threat to American sovereignty and democracy than ISIS. But we have been conditioned to freak out over “terrorism,” especially when carried out by brown people of a different religion, to the point where it even beats out decades of ingrained Russophobia. (A Russophobia that, historically, was led by the Republican Party.) Trump himself has shown zero interest in investigating Russian interference in the election — not even lip service. On the contrary, in fact: Trump bragged of shutting down the investigation, both to NBC’s Lester Holt on national television, and more shockingly, to the Russian ambassador and foreign minister face to face in the Oval Office. (Come on, guy, at least try to act innocent.) After Comey’s testimony, MSNBC anchor and former Bush White House communications chief Nicole Wallace sagely pointed out that Donald Trump spoke with Jim Comey in person or by phone NINE times in the four months. Obama spoke with Comey only twice in three YEARS. Not ONCE in any of those nine conversations did the President of the United States Donald Trump appear concerned about such Russian action, or even inquire about the progress of the investigation into it. Does that sound like the behavior of a man who really wants to get to the bottom of any such interference….or for that matter, the behavior of a man who is supposed to be in charge of the security and defense of the United States of America? So yes, the perfect, almost mathematical symmetry of Russiagate is almost too good to be true. But it only makes sense.. Inshallah. Nixon/Trump mashup illustration; artist unknown
https://edwardsrobt.medium.com/the-inevitability-of-russiagate-b8edd892c1f
CC-MAIN-2021-04
refinedweb
2,940
56.29
[…] This post was mentioned on Twitter by Aleksandr Matrosov, Jochem and alex knorr, xanda. xanda said: .LNK Tools by @DidierStevens […] Pingback by Tweets that mention Quickpost: 2 .LNK Tools « Didier Stevens -- Topsy.com — Sunday 8 August 2010 @ 11:30 Hi Didier, regarding the .LNK vulnerability, I used this tool to parse link files and I want to share it with you: (see lnk-parse-1.0.pl) P.S. your 010Editor template does a great job Comment by shinnai — Monday 9 August 2010 @ 9:31 […] la plantilla LNK de 010 Editor publicada recientemente por Didier Steven’s, obviamente para el programa 010 Editor, que si no conocéis os recomiendo que le hagáis una […] Pingback by Parsing de LNK: “You’re doing it wrong” — Tuesday 10 August 2010 @ 11:19 […] use Didier Steven’s recently released 010 Editor LNK Template for the 010 Editor […] Pingback by LNK Parsing: You’re doing it wrong (I) — Tuesday 10 August 2010 @ 11:20 Your clamav signature does not “find all .LNK shortcuts that load a DLL.” You may wish to revise your wording. A more accurate description would be that it “finds a specific .LNK shortcut that operates in the Control Panel.” Comment by Forrest Gump — Tuesday 10 August 2010 @ 14:24 @Forrest Gump You’re right, I actually wanted to write “find all .LNK shortcuts that load a DLL without opening.” Comment by Didier Stevens — Tuesday 10 August 2010 @ 14:34 Well actually, I think you may have missed the point. The clamav signature you provided is *very* specific. Given that you’ve written an 101 template for the LNK file, you should be aware that the file format has many flags, variable-length, and variable-count entries. Your signature appears to only be for one specificially-formatted LNK file. Change e.g. just a single bit flag, and the signature won’t trigger. Beyond that, the signature doesn’t have anything to do with DLL files. It stops at the point of knowing that the shortcut operates within the context of the control panel. It ignores the target. Comment by Forrest Gump — Tuesday 10 August 2010 @ 15:35 @Forrest Gump “Your signature appears to only be for one specificially-formatted LNK file.” Yes, I mainly check for the 2 IDLISTs used to write exploits for MS010-2568. Do you have .LNK examples without these 2 IDLISTs that exploit MS010-2568? Comment by Didier Stevens — Tuesday 10 August 2010 @ 16:16 The first IDLIST can contain a different byte sequence and still be functional. I have confirmed this part. I have a hunch that the second IDLIST, which is the one of interest, may also not always be 58 bytes away from the header, but have not confirmed that aspect. Comment by Forrest Gump — Tuesday 10 August 2010 @ 17:54 @Forrest Gump That’s really interesting. I had changed some random bytes in the first and second IDLIST, and the result was that the DLL didn’t load anymore. Could you provide more details? Comment by Didier Stevens — Tuesday 10 August 2010 @ 18:03 Well, a GUID is 16 bytes. And the data sections for the two IDLISTS you’re likely dealing with are 18 bytes. If you change the GUID, then you break the functionality. While I don’t know the function of the two bytes that preceed the GUIDs, I do know that they can be changed (at least with certain patterns) without breaking the exploit. Comment by Forrest Gump — Tuesday 10 August 2010 @ 19:09 The (MS) IDList format seems to start with a single byte that specifies the IDList type. So the format of the registry IDListItem we are dealing with here is { WORD Size; BYTE Type; BYTE Unknown;//This could probably be changed and still work? GUID guid;//guid of COM interface that implements shell namespace/shellview host? } Comment by WndSks — Tuesday 10 August 2010 @ 22:47 @WndSks Sounds about right. Comment by Forrest Gump — Wednesday 11 August 2010 @ 12:33 @WndSks I can confirm that the last 16 bytes of the 2 first IDFLists are GUIDs. I updated my template to parse and identify the GUIDs, and they are well-known shell GUIDs: My Computer and Control Panel. @Forrest Gump I assume you change the byte for the Type and/or the Unknown byte, but not the GUIDs? Comment by Didier Stevens — Wednesday 11 August 2010 @ 16:08 @Didier: I think the type byte may be a bit field, so perhaps some of the bits can be changed, but not all (Looking at a shortcut to the control panel, the two shiid’s start with 14 00 1F and 14 00 2E) Comment by WndSks — Wednesday 11 August 2010 @ 18:50 @Didier: Correct. Comment by Forrest Gump — Wednesday 11 August 2010 @ 21:06 Sup guys, I just published the 2nd article of the LNK Parsing series. I hope you’ll find useful information there regarding this matter. Comment by Jordi / prk — Friday 13 August 2010 @ 1:28 […] — Didier Stevens @ 10:43 I updated my .LNK template with info I got from comments from WndSks and Forrest Gump. This new version identifies well-known Shell […] Pingback by Quickpost: « Didier Stevens — Wednesday 18 August 2010 @ 10:43
http://blog.didierstevens.com/2010/08/08/quickpost-2-lnk-tools/
CC-MAIN-2014-52
refinedweb
868
70.73
8.3. Automatic Parallelism¶ MXNet automatically constructs computational graphs at the back end. Using a computational graph, the system is aware of all the computational dependencies, and can selectively execute multiple non-interdependent tasks in parallel to improve computing performance. For instance, the first example in the “Asynchronous Computing” section executes a = nd.ones((1, 2)) and b = nd.ones((1, 2)) in turn. There is no dependency between these two steps, so the system can choose to execute them in parallel. Typically, a single operator will use all the computational resources on all CPUs or a single GPU. For example, the dot operator will use all threads on all CPUs (even if there are multiple CPU processors on a single machine) or a single GPU. If computational load of each operator is large enough and multiple operators are run in parallel on only on the CPU or a single GPU, then the operations of each operator can only receive a portion of computational resources of CPU or single GPU. Even if these computations can be parallelized, the ultimate increase in computing performance may not be significant. In this section, our discussion of automatic parallel computation mainly focuses on parallel computation using both CPUs and GPUs, as well as the parallelization of computation and communication. First, import the required packages or modules for experiment in this section. Note that we need at least one GPU to run the experiment in this section. In [1]: import gluonbook as gb import mxnet as mx from mxnet import nd 8.3.1. Parallel Computation using CPUs and GPUs¶ First, we will discuss parallel computation using CPUs and GPUs, for example, when computation in a program occurs both on the CPU and a GPU. First, define the run function so that it performs 10 matrix multiplications. In [2]: def run(x): return [nd.dot(x, x) for _ in range(10)] Next, create an NDArray on both the CPU and GPU. In [3]: x_cpu = nd.random.uniform(shape=(2000, 2000)) x_gpu = nd.random.uniform(shape=(6000, 6000), ctx=mx.gpu(0)) Then, use the two NDArrays to run the run function on both the CPU and GPU and print the time required. In [4]: run(x_cpu) # Warm-up begins. run(x_gpu) nd.waitall() # Warm-up ends. with gb.Benchmark('Run on CPU.'): run(x_cpu) nd.waitall() with gb.Benchmark('Then run on GPU.'): run(x_gpu) nd.waitall() Run on CPU. time: 1.1914 sec Then run on GPU. time: 1.2230 sec We remove nd.waitall() between the two computing tasks run(x_cpu) and run(x_gpu) and hope the system can automatically parallel these two tasks. In [5]: with gb.Benchmark('Run on both CPU and GPU in parallel.'): run(x_cpu) run(x_gpu) nd.waitall() Run on both CPU and GPU in parallel. time: 1.2277 sec As we can see, when two computing tasks are executed together, the total execution time is less than the sum of their separate execution times. This means that MXNet can effectively automate parallel computation on CPUs and GPUs. 8.3.2. Parallel Computation of Computing and Communication¶ In computations that use both the CPU and GPU, we often need to copy data between the CPU and GPU, resulting in data communication. In the example below, we compute on the GPU and then copy the results back to the CPU. We print the GPU computation time and the communication time from the GPU to CPU. In [6]: def copy_to_cpu(x): return [y.copyto(mx.cpu()) for y in x] with gb.Benchmark('Run on GPU.'): y = run(x_gpu) nd.waitall() with gb.Benchmark('Then copy to CPU.'): copy_to_cpu(y) nd.waitall() Run on GPU. time: 1.2262 sec Then copy to CPU. time: 0.5235 sec We remove the waitall function between computation and communication and print the total time need to complete both tasks. In [7]: with gb.Benchmark('Run and copy in parallel.'): y = run(x_gpu) copy_to_cpu(y) nd.waitall() Run and copy in parallel. time: 1.2828 sec As we can see, the total time required to perform computation and communication is less than the sum of their separate execution times. It should be noted that this computation and communication task is different from the parallel computation task that simultaneously used the CPU and GPU described earlier in this section. Here, there is a dependency between execution and communication: y[i] must be computed before it can be copied to the CPU. Fortunately, the system can copy y[i-1] when computing y[i] to reduce the total running time of computation and communication. 8.3.3. Summary¶ - MXNet can improve computing performance through automatic parallel computation, such as parallel computation using the CPU and GPU and the parallelization of computation and communication. 8.3.4. Problems¶ - 10 operations were performed in the runfunction defined in this section. There are no dependencies between them. Design an experiment to see if MXNet will automatically execute them in parallel. - Designing computation tasks that include more complex data dependencies, and run experiments to see if MXNet can obtain the correct results and improve computing performance. - When the computational load of an operator is small enough, parallel computation on only the CPU or a single GPU may also improve the computing performance. Design an experiment to verify this.
http://gluon.ai/chapter_computational-performance/auto-parallelism.html
CC-MAIN-2019-04
refinedweb
889
50.12
Details - Type: New Feature - Status: Closed - Priority: Major - Resolution: Fixed - Affects Version/s: None - Fix Version/s: 1.8.1, 1.9-beta-1 - Component/s: groovy-jdk - Labels:None - Flags:Patch Description As described in a thread in the groovy user list here: An implementation of groupBy that receives a list or an array of closures as criteria for grouping would be useful for making nested groupings. def grouped = [ [aa: 11, bb: 22, cc: 33], [aa: 22, bb: 22, cc: 44], [aa: 11, bb: 22, cc: 55], [aa: 22, bb: 33, cc: 66], [aa: 33, bb: 44, cc: 77] ].groupBy({ it.aa }, { it.bb }) def expected = [ 11:[22:[[aa:11, bb:22, cc:33], [aa:11, bb:22, cc:55]]], 22:[22:[[aa:22, bb:22, cc:44]], 33:[[aa:22, bb:33, cc:66]]], 33:[44:[[aa:33, bb:44, cc:77]]] ] assert grouped[11][22] == [[aa:11, bb:22, cc:33], [aa:11, bb:22, cc:55]] assert grouped[22][33] == [[aa:22, bb:33, cc:66]] assert grouped[11][99] == null groupBy with one closure criterion would behave like the current implementation of groupBy.
https://issues.apache.org/jira/browse/GROOVY-4885
CC-MAIN-2018-51
refinedweb
188
53.38
So i keep having an issue with dfs permissions. Here is a outline of the current DFS setup. There are 3 servers 1 is a 2003 the other 2 are 2008 storage server. Intermitently i have a user that losses permissions to the namespace share. it will kinda go off and on for him with no forseable pattern. The share he is accessing orginally existed on the 2003 server only. I bought the two 2008 servers because the 2003 was running out of space and we wanted to use dfs and namespaces for redundancy. So to make the transfer of data go smoother i added the 2003 server into the dfs to replicate its data to the new servers. So the directory he is accessing was setup with the 2003 server as the primary server, and had the permissions copied from that server. It is my understanding that after the initial replication there is no longer a primary server. I have also read that there is some weird permission issues with the root folder of shares with server 2003. He can see the folder when this happens just can no longer save to it. Anyone have any suggestions of things to try. I have tried to research this issue without much luck 1 Reply Aug 18, 2011 at 3:54 UTC I have quite a mixed DFS environment too. It is possible that the share permissions(not NTFS permissions) are incorrect on one of the other servers. It is happening intermittently because sometimes he connects to the 2003 server and other times he connects to the 2008 servers. When it happens to him right click on the mapped drive and choose properties. then check the DFS tab and see which server he is using. then you know which server to check the permissions on.
https://community.spiceworks.com/topic/152359-dfs-permission-issues
CC-MAIN-2017-13
refinedweb
304
72.26
Board index » VC All times are UTC Hi ! I using VC++ 4.2 under Win 95 In my application I using the ShellExecute function to start an "external" application. How can I decide, when finished the started application? The application runing without any window. Is very important for me to know, because in the next step I have to use the result of the started application. But if the application still runing I havn't the result. So can anyone help me? Thanks in advance Ilyes Albert you could try #include <process.h> .... status = _spawnl( _P_WAIT, "sample.exe","sample.exe", "parm1 parm2 parm3", NULL); this will wait until the process finishes under WIN95. but it may not work under nt4. 1. Knowing when a thread finished working 2. Knowing when threads have finished without locking the main thread 3. Knowing when a process has finished 4. How to know when IE is finished printing 5. How to know that WebBrowser has finished printing? 6. How to know when a print job finish? 7. Memory problem finishing my Application... 8. How to tell if an application is finished 9. how can I decide when finish an application started with ShellExecute 10. Memory problem when I finish my Application... 11. How can i know when Dos application finish to Run ??? 12. General:How can I know what the additional DLLs should I destribute with my ATL application
http://computer-programming-forum.com/81-vc/ebf8980e3b47ea9b.htm
CC-MAIN-2022-33
refinedweb
235
70.29
Important: Please read the Qt Code of Conduct - QML ToolBarStyle hides Android Menu (Qt 5.5.1) Here is basically some cut and paste QML from the documentation... an Application window with a MenuBar and a ToolBar. Run it for Desktop, it works fine. Run it on android it works fine (the menu bar is integrated on the right of the toolbar.) However, when I add the ToolBarStyle to change the background of the toolbar, the menu is gone under android. This has got to be something simple, I've tried a gazillion googles and different permutations, but no joy. Has anyone got a clue on this one? import QtQuick 2.3 import QtQuick.Controls 1.2 import QtQuick.Layouts 1.1 import QtQuick.Controls.Styles 1.4(); } } } toolBar: ToolBar { // THIS STYLE CAUSES ANDROID MENU TO DISAPPEAR style: ToolBarStyle { background: Rectangle { color: "green" } } RowLayout { anchors.fill: parent ToolButton { text: "foo" } } } Label { text: qsTr("Hello World") anchors.centerIn: parent } } ok this appears to be the same problem as this: not really "solved", but at least some pointers in that previous post.
https://forum.qt.io/topic/65963/qml-toolbarstyle-hides-android-menu-qt-5-5-1
CC-MAIN-2021-31
refinedweb
180
68.67
RSA_generate_key − generate RSA key pair #include <openssl/rsa.h> RSA *RSA_generate_key(int num, unsigned long e, void (*callback)(int,int,void *), void *cb_arg); or 65535. A callback function may be used to provide feedback about the progress of the key generation. If callback is not NULL, it will be called as follows: •). If key generation fails, RSA_generate_key() returns NULL; the error codes can be obtained by ERR_get_error(3). callback(2, x, cb_arg) is used with two different meanings. RSA_generate_key() goes into an infinite loop for illegal input values. err(3), rand(3), rsa(3), RSA_free(3) The cb_arg argument was added in SSLeay 0.9.0.
https://alvinalexander.com/unix/man/man3/RSA_generate_key.3.shtml
CC-MAIN-2019-09
refinedweb
106
68.26
Massachusetts Finalizes OpenDocument Standard Plan 210 wellington map writes "The state of Massachusetts has finalized a proposed move to an open, nonproprietary format for office documents, a plan that involves phasing out versions of Microsoft's Office productivity suite deployed in the state's executive branch agencies. Massachusetts expects its agencies to develop phased migration plans away from productivity suites that do not support OpenDocument, with a target implementation date of January 1, 2007. Looks like it's finally cemented after some heated discussions." lately... (Score:5, Funny) Good on 'Em, mate! :-) (Score:3, Interesting) I am happy to hear the Chew'setts have the brass tacks to pull something like this off and I can't wait to see Microsoft shoot themselves in the foot on this one. Re:Good on 'Em, mate! :-) (Score:3, Funny) Here's to the Boston Office party! I'll believe it when I see it. (Score:3, Interesting) Hate to be a downer, but I am sure if you a Re:I'll believe it when I see it. (Score:2) i'm willing to bet CIO's will be looking to limit their personal risk when this directive becomes state law. Re:Good on 'Em, mate! :-) (Score:5, Insightful) Of all the company representatives present during that meeting, I did not hear one objecting to the goals MA has in mind, except one. And some of those companies present are not from the backwoods. If anyone is phasing anyone one out, it is Microsoft doing it to themselves. Re:Good on 'Em, mate! :-) (Score:4, Interesting) Re:Good on 'Em, mate! :-) (Score:2) So why does MA want an open standard format????? Re:lately... (Score:2, Insightful) Re:lately... (Score:5, Insightful) I also have seen the quality of tech support in several local gov't situation. Usually below industry pay rate (but nice benefits). And the hiring process favors women, minorities, those with prior civil service experience and military background. Some of the dumbest folks you ever want to meet are working for your local gov't. I had one "sys admin" forward me an e-mail about a dangerous file on my system that I had to delete... turned out to be a critical windows file. So point is, this decision wasn't made based upon tech savvy. It was made based upon cost. Re:lately... (Score:3, Informative) You can listen to a recent meeting of the Mass Technology Leadership Council here: i It's long, but they say time and time again they're only concerned with the document format and it's "openness." And they do a *great* job Re:lately... (Score:2, Interesting) Re:lately... (Score:5, Insightful) They were very smart IMHO. It's not trend-following. In fact they sort of appologize for not getting to this earlier (talking about how government tends to actually trail behind the private sector). Their reasoning is that they never want to need to worry in the future about being able to read old documents (MS can't make this guarantee - remember that state documents live for hundreds of years!). This was the big sticking point mostly. They also don't like one vendor controlling what they can do with their documents and didn't want to require the public to purchase expensive software to view these documents. This is one of the few times I'm glad to be from Massachusetts. They had very well thought-out reasons behind this. The Microsoft representative couldn't even argue with them (though it sounds like he'd just gotten off a flight so he was probably pretty tired). They stated that they don't require Open Office, just software that implements the OASIS spec. Microsoft is free to do so and then they will consider Office. It was the most complete spec that they found that offers all of the above points. I highly suggest listening to that recording. It's long, but not terribly boring (mostly techies in the room - few lawyers). Re:lately... (Score:3, Interesting) I have a database in Access 1.0 format. It is entirely unreadable/convertable by current versions of Access, and there is no free software available that will convert it. Essentially the data is lost forever, unless I seach for a garage sale copy of Access 1.0 or 2.0 - and there is no guarantee that such software would work on Windows XP anyway. Now as it happens I don't need that data. But local governments should not be put in a position where their achi Re:lately... (Score:4, Insightful) I suspect the problem you describe is primarily due to the age of the data file and not some much with the data file being in a proprietary format. As the open file format evolves it's likely you will encounter the same issue. No, not the same issue. If Access 1.0 had used an open format, even if I couldn't acquire a copy of a sufficiently old version of Access, I could always read the specification and implement a translator that converts to a newer format which modern software can read. Now, whether or not that's worth the effort depends on the circumstances, but it would be orders of magnitude easier than reverse-engineering the format, or finding some way to acquire the ancient software and the infrastructure needed to run it. And, odds are, given an open format someone else will have already written the translator and published it as open source. Especially if the format in question was widely used. Re:lately... (Score:3, Interesting) "Microsoft will publish the new Office Open XML Format specifications with the Open and Royalty-free license that we first made available for the Office 2003 XML file formats. But Microsoft's license is not available to Free Software projects. Such a license fulfills most of the Massachussets goals, but unnecessarily limits what programs can implement support for the formats. You mean something along the lines of what a myraid of programs, such as Open Office, already do for MS Office file formats? So Re:lately... (Score:3, Insightful) It meets their goals. Whether it's available to free software projects is irrelavent. It meets *most* of their goals. One of their goals is that the format must be implementable by anyone. Free Software projects cannot use Microsoft's format, ergo it does not meet all of the requirements. A non-issue as the format is being published by Microsoft. Perhaps. Their Office 2003 XML formats include significant features that, while documented, are inextricably tied to other Windows components which are not Re:lately... (Score:2, Interesting) Not so. If the Access 1.0 format were open, BasilBrush could have written a converter himself, regardless of how old the format was. But the format is closed, so he is f*cked. Massachusetts does not want to be stranded like Basil. Will Microsoft still be Re:lately... (Score:3, Insightful) Re:lately... (Score:2) Re:lately... (Score:2) As one gentleman in the meeting put it. The law books from the early 1800s in the Harvard library are still readable. So should any documents stored elecronically in 200 yea Re:lately... (Score:2) Re:lately... (Score:2, Insightful) Re:lately... (Score:2) Yes, and why is that? It is because paper books are a common, reliable (albeit comparatively low density) non-volatile data storage medium which has changed very little in all that time. And even though the medium has remained stable, the truth is that the nature of the languages used (i.e., the file format) most certainly has changed, often to the point where the inform Re:lately... (Score:2) Fact is, file formats can always be reverse engineered Ahhh, but will it be *legal* to do so? That is part of the dilemma being faced lately, and part of the reason Massachusetts doesn't want file formats encumbered by patents and such. Re:lately... (Score:2) I call Bullshit. Supporting different versions of MS products is indeed more technically challenging and daunting - worse, in many cases it's near impossible - you actually refer to the stupid advice to delete a patch! Considering non-MS agencies know and care more about MS formats and support them in their packages, this is both a cost-effective AND wise decision. Re:lately... (Score:2) Re:lately... (Score:2) It was only after a rather lot of pressure from the public (mostly geeks, I assume) that they released the updated version. Public outcry made them realize that encumbered file formats were not a good idea for government files. So, whilst your reasoning is sound, it is factually incorrect. Re:lately... (Score:2) And yes, there are qualified black and female IT professionals. But they are a small percentage of the entire IT workforce. When you limit youself to a small percentage of the workforce, you will get a smaller percentage of qualified personnel. The fact is the civil service is sexist and racist. If I reversed the scoring procedures (add points for mal Since you asked... (Score:3, Insightful) Re:Since you asked... (Score:3, Insightful) The problem I have with this logic is this: Not all white folks are necessarilly the beneficiaries of past racist policies. I live in a semi-ghetto area. About half white, half-black. Very high unemployment. I won't go into my reasons for living here. About half of the folks are unemployed. Most come from families where education is not stressed and drug use is high. Affirmative action might help a young black person who wants Re:Since you asked... (Score:3, Insightful) It irks me every time I fill out some kind of government form and have to skip over the "visible minority" checkbox.. For the record, I happen to know it also equally irks my girlfriend who happens to be a Re:Since you asked... (Score:2) This might be something that came into use through some kind of PC push but it's very puzzling... Re:Since you asked... (Score:2) Re:Since you asked... (Score:2) Re:lately... (Score:3, Interesting) MS Will Come Around Eventually (Score:5, Interesting) Anyway, in the end, the customer is always right. So Microsoft will come around if OpenDocument gets any kind of real traction. Re:MS Will Come Around Eventually (Score:3, Funny) Re:MS Will Come Around Eventually (Score:3, Funny) Re:MS Will Come Around Eventually (Score:5, Interesting) Re:MS Will Come Around Eventually (Score:2) Actually, the plan does not necessarily involve phasing out anything. As the parent post suggests, Microsoft can continue to be a contender by modifying Office to support open document formats. Once large companies and governments realize that they can get along just fine without Microsoft products, it will be even harder to get them back on the crack, so to speak. Th Re:MS Will Come Around Eventually (Score:2) Re:MS Will Come Around Eventually (Score:2) Re:MS Will Come Around Eventually (Score:2) Sad (Score:2, Funny) In Related News... (Score:5, Interesting) great reply! (Score:2) Great way to fight the FUD!!! Re:In Related News... (Score:2) ." Re:In Related News... (Score:2) Re:In Related News... (Score:2) I whish the format would be more ea Re:In Related News... (Score:2) Why? (Score:2, Insightful) The slashdot articles are also fairly free of any Re:Why? (Score:5, Insightful) There is a recording of the Mass Technology Leadership Council discussing their reasons here: Basically they're very afraid of proprietary document formats (and rightly so). Especially when they consider archival purposes. 20 years from now do you want to find a copy of Word '98 to be able to read old state documents? Right now I can go to the basement of Harvard and read law books from the 1800's! They're also concerned about requiring the public to purchase expensive software from a single vendor in order to view "public" documents. They state time and time again what their requirements for a doc format are, and that if Microsoft were to offer one they would consider it. MS, unsurprisingly, does not offer one... Quite concrete problem (Score:2) On the other hand, when I wrote papers in WordPerfect 4.2 or so, not much later, those formats are still Re:Quite concrete problem (Score:2) A)It'll be supported for a *long, long* time, and B)100 years from now writing a parser to extract all that old data will be trivial. It's not that the data is easier to understand (though it is). It's that everyone has equal access to the instructions to build such a parser. Also, I suspect that if it does become an ISO standard, OASIS OpenDocument will remain as a subset of any future docume Re:Quite concrete problem (Score:2) Re:Why? (Score:2) Re:Why? (Score:3, Interesting) Re:Why? (Score:3, Insightful) Re:Why? (Score:5, Insightful) Massachussets stated reason for switching to the OpenDocument format is that it allows them to guarantee access to important state documents. However, my guess is that this is just a fancy sugar coating over the real reason for switching, and that reason is the cost of migrating to Office 12. There is a very interesting exchange in the MP3 of the recent meeting that the state officers had with various software companies in which, after nearly an hour of saying that the state didn't want to talk about procurement, one of the Mass. officers let the Microsoft team have it right between the eyes. Basically he laid out the costs that Massachussetts would incur in a switch to MS Office 12, and it was clear that the costs were much higher than a switch to OO.org. Massachussets is going to have to switch document formats no matter what they do. The new version of MS Office 12 is going to have a completely new set of document formats that won't be backwards compatible. Yes, Microsoft has promised plugins for some of the older versions of MS Office that will read and write these new formats, and yes Microsoft has tools that allow for batch conversion of documents, but OpenOffice.org has this as well. The state of Massachussetts has an estimated 50,000 desktops, primarily running Windows 2000. In order to use MS Office 12 Massachussetts would have to upgrade the operating system on all of these boxes, and in many cases it would need to purchase new hardware to boot. Not only that, but Office 12 also has an entirely redesigned user interface which would require additional user training. Do you see where this is going? Massachussetts estimates (using past knowlegde of similar Microsoft updates) that a move to Office 12 would cost $50 million dollars. A move to OpenOffice.org is estimated to cost an order of magnitude less ($5 million dollars). Heck, if Microsoft is going to force their customers to a new set of file formats, with a new UI, and a new operating system then its almost certain that OO.org on their existing operating system and using existing hardware will be less expensive. OO.org also forces you to use a new file format and it will require training, but Massachussetts won't have to throw an OS upgrade into the mix. The reason that Massachussetts can get away with the switch is that they are big enough that they can simply mandate a file format and expect people that deal with them to make the switch. You don't argue with the bureaucrats. If they want their documents in OpenDocument formats then you simply find a way to send them OpenDocument formats. The fact that the software necessary to deal with the state government is going to be a free download is just a bonus. If Massachussetts required MS Office 12, or WordPerfect, or even LaTeX that's what people would send them. One thing is certain, a lot of businesses and individuals in Massachussetts are going to find it necessary to download and install OpenOffice.org, and many of them are going to like what they find. It's almost certainly going to become much more difficult to sell new versions of MS Office in Massachussetts. After all, unless you are some sort of MS Office power user you are not even likely to be able to tell the difference between the two programs, and OO.org is going to be required for dealing with the government. Re:Why? (Score:2) Re:Why? (Score:2) Of all of the OpenOffice.org family Writer is far and away the best piece of software. In fact, due to the fact that it makes it much easier to use styles in your document than MS Word I actually like Writer better than Word. The real problem with OO.org has always been file format compatibility with MS Office. I know that I have kept around a copy of MS Office for years now simply to test documents before sending them to MS Office users. For the most part OO.org has worked well, but sometimes there hav Re:Why? (Score:3, Informative) I, and anyone else who have creating word documents for the past decade or so, know how fustrating it is to go back and try to edit old work. Now, if one is using word as a toy, i.e. school papers or memos that no one really reads, then it doesn't matter how the work is saved, because the computer is just a fnacy typewriter, and no one will care about the do Microsoft just trying to stop Massachusetts... (Score:4, Funny) Re:Microsoft just trying to stop Massachusetts... (Score:4, Informative) Note: while MS Office documents can be open in abiword and openoffice, it's kind of a closed format that can never be 100 percent documented, so compability can't be perfect. Only MS Office use fully the format so there's a dependency on Microsoft by using its format. This will be M$'s strategy... (Score:5, Interesting) By the way, what will happen when the Federal government sends documents to Massachusetts in word format? Would the state send them back? Suppose M$ suddenly decides to support OpenDocument, gets the state's business and then issues a "security patch", that introduces proprietary extensions as has been in the past? Re:This will be M$'s strategy... (Score:2) Open Office or all packages that support OpenDoc can read the MS word format without any problem. Likewise, the reply docs can be saved in word doc versions and still be read by the Fed systems running MS Office. I don't see any problems here.... except for locked down formats like Microsoft's. Re:This will be M$'s strategy... (Score:5, Informative) > a state's authority. You do not understand correctly. > By the way, what will happen when the Federal government sends > documents to Massachusetts in word format? Would the state send > them back? The state will read them with OpenOffice, of course. What do you think? > Suppose M$ suddenly decides to support OpenDocument, gets the > state's business and then issues a "security patch", that > introduces proprietary extensions as has been in the past? Either the "extensions" will be turned off or Microsoft will lose the state's business again, and perhaps find itself in court for breach of contract. Re:This will be M$'s strategy... (Score:2) > > a state's authority. > You do not understand correctly. If only that were true... The feds have multiple ways of overriding a state's authority. Foremost, the vague clause in the constitution that gives the feds the power over anything (article I, section 8, clause 18) tends to be abused quite a bit. This used to be a major difference in the parties - traditionally, one party supported use of clause 18 while the other opp Re:This will be M$'s strategy... (Score:3, Informative) Only in cases that deal wih the Constitution, laws or treaties of the United States. As of yet, there is no federal law that says that the all documents within the United States must be in Word format. Even if Congress tried to pass one (which would be silly), the current Supreme Court would probably strike it down for lack of Subject Matter Jurisdiction (the Rhenquist Court was pretty good about telling Congress to st Re:This will be M$'s strategy... (Score:3, Interesting) My guess? Massachusetts will open it in OpenOffice.org (or IBM's upcoming thin-client ODP solution), and file a complaint with the federal government "We've received XXX.doc, please be aware that it is against the policy of the State of Massachusetts to work with documents not in the ODP ISO-standard format. Your document has been converted to an ODP format document-- the S Mod Parent UP Please (Score:2) My guess? Use OpenOffice.org as a conversion filter. Then, various fed employees (IT people) will start wondering _why_ they should be paying for MS Office when they *already* use a similar office suite as a _conversion_ filter." You took the words right out of my mouth. Why aren't big companies doing this? (Score:5, Insightful) Whenever I bring it up to any of my clients, government or private side, they give me that deer in the headlights look. Even if you can dig out an old backup tape and demonstrate the files aren't conveniently recoverable it still doesn't seem to sink in. The same with database storage. I'm amazed how many companies don't even have a freakin data dictionary. If you have to ask why you need one of those, then you need one. Maybe you just really like transposing fields and data types on the fly between every application you build. People must find that pleasurable because there's sure enough of them doing it. Just the beginning (Score:3, Insightful) (1) For some odd reason, nobody had every really put forth a major, viable, industry-backed and powerful open specification for Office formats (2) Compatibility with existing documents. Most large corps have many Re:Why aren't big companies doing this? (Score:3, Interesting) Re:Why aren't big companies doing this? (Score:2) MS could embrace this and stop the bleeding (Score:4, Insightful) In this way, they could show governments that they *can* move to open standards, while still maintaining their (for MS) lucrative relationship. Instead, as per usual, we get stonewalling out of Redmond. Re:MS could embrace this and stop the bleeding (Score:2) The only thing that MS can use to differentiate their software is its native Re:MS could embrace this and stop the bleeding (Score:2) However, it's also clear that by refusing to support an open system such as OASIS, they're entirely losing their user base in the MA government. If this continues and becomes a trend, by not supporting the OASIS formats, Microsoft is actually locking themselves out of the market, instead of locking themselves in, as Re:MS could embrace this and stop the bleeding (Score:2) Re:MS could embrace this and stop the bleeding (Score:2) The MS XML Office doc format is still proprietary in nature. As one article or another noted, it's not just the XML-ness of the OASIS formats that's important, it's the fact that there is a shared, open, and agreed-upon parser for these documents. The semantics of the XML have to be identical in order for everything to work properly. Microsoft is not, to the best of my knowledge, releasing all associ Re:MS could embrace this and stop the bleeding (Score:2) You *really* don't know what you are talking about. Repeat after me, "XML is not a document format" "XML is not a document format" XML is a general purpose markup language you can use to define document formats. Grandparent is correct. MS Office 12 will NOT save in the soon to be ISO approved, OASIS OpenDocument format. Period. Office Open XML != OpenDocument XML Just because they both have XML in the name doesn't mean that they are the same thing. There might be a possib Oh no! (Score:2, Funny) Re:Oh no! (Score:2) They'll be restricted to cross-platform embedded Java VOIP apps in their wordprocessors, instead of using Windows-only ActiveX VOP apps in their wordprocessors. Oh Noes! Strangely, though, my VOIP java-app doesn't work properly. No matter what printer I print my document out on, and no matter how hard I ink out the 'Send' button, I don't hear any voice from my letter. Maybe the ActiveX version would work? *shrug* 8*) Why so many replies with M$ FUD? (Score:2, Insightful) Re:Why so many replies with M$ FUD? (Score:2) Yup, the scientists have had it all wrong for years. Newton should have charged a license fee for access to his research, E=mc^2 should be a secret unless you're a paid up member of the Einstein corporation. Free software is far closer to the concepts of freely shared scientific information than any concept of getting crappy freebies. It's that free sharing of Software As A Commodity (Score:5, Insightful) Once this happens (and it already is, slowly), the software companies will have to make their money by creating "ten-percenter" software: highly specialized software contracted and built specifically for another company, or a niche market. To use an analogy, the "ninety-percenter" software market right now is like tract housing. Companies build products that they think people will like, and then sell them when the product is finished. The future of software design is much more like contract housing; people contact a company, tell them what they want in their product, and the company builds it for a contract fee, specifically for that customer. Both types of software development co-exist now, but soon the tract style will not be maintainable as a business model since groups of people are giving away tract houses for free. Microsoft is struggling right now with the future of their products. Microsoft Office will soon be obsolete if MS continues their current business model, since there will be nothing to justify its high price. Right now, Microsoft maintains their pricepoint with vendor lock-in; but as soon as every major company and government is using open standards, MS Office will be just one choice out of several. I can see Microsoft Office being quite profitable in a commodity market, but Microsoft will have to add more than just office-suite productivity to their software. They have to offer more value than the next guy: in the form of tech support, or service contracts, or collaboration/version tracking software, or any of a number of things that would add value to the commodity. The commodity alone will not be enough. This is a very good move by Massachusetts; in the long run, it will protect valuable data from vendor lock-in, and eventually foster competition in the office suite marketplace. Competition is always a Good Thing(tm). MA document sovernty (Score:2) listen to the MA open format meeting. This is about nothing more than storage of a document is a fashion that allows everyone equal access. MS can choose to implement the standard or they can choose not to. It is about preserving the sovernty of data owned and created by the MA govt. I highly doubt MS is going to support this document format as it will no TeX anyone? (Score:3, Funny) Re:And the results of this: (Score:3, Insightful) On top of that, I'm also sure they'd identify weaknesses in the specification and ensure that their .odt files are laced with extra namespaces & markup Re:And the results of this: (Score:2, Insightful) If there is a *policy* in place that tells folks that they must save in the ODF, then those folks will naturally ask their IT staff to make it easier to do, whether it's with a MS product add-on or OpenOffice or KOffice, or whatever. Well done, Massachusetts. Re:And the results of this: (Score:5, Informative) This sounds very similar to what Microsoft is doing with HTML/CSS/JS. Before they release a new browser, they state how CSS2 is "flawed," and therefore we wont support it (And I'm betting that they will add propritary functions that do a similar thing). The same thing happened with the half-assed support of pretty much any standards in HTML/JS...yes, they might have one or two parts that follow standards, but the rest is either proprietary, or a horrible "improved" take on the standards. I'm sure MS will attempt to do the same thing to ODT files. They will make some fairly basic functions in Office stored in a "enhanced" form, which, ofcourse, only works in MS Office. Judging from past experiance, the "standard" files genorated by Office would be a horrible mash of invalid markup, useless elements, and namespaces that server no purpose; except to break compatibility with any other program. In their usual style, they will probally hide a series of options hidden under 12 dialog windows which are the only way to genorate an actual standard document. Not only this, those options would probally pop up a "scary sounding" warning when disabled, to stop the non-techies among us from changing them. Just to back this up, look at the XML Word genorates for a document that only contains "Hello world!" (No, I'm not joking, check for yourself). Re:And the results of this: (Score:3, Funny) Jeff Re:And the results of this: (Score:3, Interesting) When properly indented, it seems quite reasonable. What really scaries me is the <w:validateAgainstSchema/> <w:saveInvalidXML w: bits... Re:And the results of this: (Score:2, Insightful) Re:And the results of this: (Score:2) That's the meat of the new policy. The documents *must* be kept in an Open format. Right now, that means OASIS OpenDocument. Period. Re:long overdue (Score:3, Insightful) Is this true? Are most users running Open Office? Is it 5%?, 10%?, 50%??? It is A standard, but is it THE standard? Re:MS Office already uses open formats (Score:5, Insightful) Wikipedia defines. Languages based on XML (for example, RDF, RSS, MathML, XHTML, SVG, and cXML) are defined in a formal way, allowing programs to modify and validate documents in these languages without prior knowledge of their form. One uses XML to 'define' a document format. The problem is that one could easily define a format (schema), permit royalty free-licensing, but 'patent' the schema/format. Remember GIF? MS XML formats have this problem. One, there are a couple licensing requirements. Two, the royalty-free license does *not* grant the licensee rights to use any MS patents that the document format may utilize. Even if one interprets some as the text as granting a right to the patents for certain implementations of MS XML, there's no reason to believe you have a perpetual right to those patents. MS has some control over who can implement these formats, and for instruments of public policy, that is simply not acceptable. MS is free to implement OASIS formats, because everyone is free to implement them. Governments are having to upgrade anyways--> DOC is being phased out. It's either switch to OASIS (ISO-approved), with multi-vendor support, and shipping software that supports it; or switch to MS Office Open XML, which hasn't been released yet, which *no* software on the market currently supports, which is not vendor neutral in implementation, and is not any kind of 'official' standard. People use DOC over all the other formats because it has marketshare. MS Office Open XML has 0 marketshare right now. It has to compete on its merits alone, and a such, is failing. Read here for more information: Re:MS Office already uses open formats (Score:3, Interesting) 1. OpenOffice.org (read, Sun's Proxy) is one of the forces behind OASIS, but by no means the main force. There are quite a few heavyweights, both vendors and customers. Here's a list: Vendors: Adobe (Framemaker, Distiller) Arbortext (Arbortext Enterprise Publishing System) Corel (Word Perfect) IBM (Lotus 1-2-3, Workplace) KDE (Koffice) SpeedLegal (SmartPrecedent enterprise document assembly system); both product and company later changed names to Exari. Sun Microsystems / OpenOf Re:This does NOT exclude MS Office (Score:3, Interesting) The amount of work would be quite a lot, especially if they wished to make said plug-in proprietary. Also, I imagine that MS would try to break this plug-in quite a bit. It's much more likely that someone would make a separate go-in between filter program. If you are going to use a separate program, however, you might as well run OpenOffice.org to do you conversion. You could have an OpenOffice.org java/macro program that did exactly that. Drop the file on your openoffice.org con
https://slashdot.org/story/05/09/24/1317234/massachusetts-finalizes-opendocument-standard-plan
CC-MAIN-2017-26
refinedweb
5,574
63.39
Hi Steve, > The timing with reference to Geronimo certainly perks an eyebrow. Geronimo is certainly interesting to me too. But came as a complete suprise to me, and the Apache XMLBeans work is completely unrelated to it. Maybe I'm not plugged in enough. On your real questions: XMLBeans currently is not designed as a Castor replacement. Castor's sweet spot is the "start from Java" use case, and XMLBeans current sweet spot is the "start from XML Schema" use case. Filling Castor's role is an interesting problem, but it's not something that the dev team has committed to investing in yet. Your questions are the kinds of things we'd have to understand if we wanted to do this, so it's a good discussion to understand. With that in mind, my comments below: > 1) data architects want to be able to specify an XML Schema void of any implementation specific namespaces (basically only the W3C XML Schema namespace) > 2) object modellers want simple JavaBeans that implement java.io.Serializable, have a public default constructor, and do not import anything outside the scope of the JDK. > 3) programmers want a single ubiquitous (un)marshalling framework that they can use across the whole J2EE enterprise, web services, and client testcases. Agreed, those are good goals. In the XMLBeans world, we are very data-oriented, and we add a few others: 4) Data architects want to be able to rely on using all of the XML Schema spec, instead of probing around for a "safe" subset. 5) When instances of XML go through the system, the whole infoset should be available. For example, XML is specifically designed to permit extensibility attributes and elements; if you lose these, you lose much of the robustness of XML to evolution and change. 6) Loading and saving XML with only minor mods should result in the identical document with minor mods. Although throwing away things like XML comments may seem OK, in doing this sort of thing you lose a core reason to use XML, which is its human-readability. > I personally feel that these should be the three core requirements of an (un)marshalling framework and should be met at all cost. I've currently only found this capability by using Castor and writing a set of JAX-RPC Castor Serializers for Apache Axis. However, Castor is not completely an ideal implementation at this point, and the development effort on it appears to have weened a bit. "At all cost" is a stronger statement than we make. The constructor requirement you propose in particular is attractive, yet fairly constraining, because of the penalties you need to accept. By tying yourself to a single public implementation class, you rule out (1) allowing a framework to provide multiple different implementations (e.g., fast versus high-fidelity versus change-tracking); you rule out (2) allowing sophisticated users to wrap your classes with their own implementations; and you rule out (3) use of other powerful techniques like dynamic proxies as interceptors. I agree it would be desirable to say "new Foo()", but "Foo.Factory.newInstance()" is not too bad, and the difference in convenience needs to be weighed against the other penalties. > 1) the binding and mapping specification should be one and the same; i.e. I should be able to source generate my JavaBeans from an XSD with the default mapping and subsequently (un)marshal without specifying a mapping; I should also be able to create custom bindings/mappings in a single file that can be used to source generate and (un)marshal (Castor requires a seperate file for binding and mapping, but they almost look identical) Yes. > 2) the (un)marshalling framework should use an XML pull model for performance It should use whatever model is fastest. Agreed, pull can be very very fast, but the main advantage of pull is architectural modularity. It can't hurt for unmarshalling to support both pull and push, and internally default to whatever is fastest. > 3) the framework should have it's own type mapping registry that is initialized by either the default mapping or a custom binding/mapping file; this should significantly increase performance (this is why Castor is slower than some of the other frameworks) Yes, initialization must be fast. Throughput is even more important. > 4) do not require the addition of any non W3C namespaces in the XML Schemas of the user data types XMLBeans certainly is free of any nonbuiltin namespaces, since it's "start from schema". We use just the schema you give us. However, I'm curious what your proposed approach should be for java.util collection classes and so on when you're doing "start from java"? What should you do with java.util.HashMap? > 5) do not source code generate or do byte code modifications to the user JavaBeans in such a way as to couple them to the (un)marshalling framework by requiring the import of (un)marshalling framework specific classes If you "start from Java" the binding compiler should keep its "hands off the Java". If you "start from schema" you need to keep your "hands off the schema". The two scenarios are fairly different, and currently if you start from Java, most binding frameworks require generation of schema, and also vice-versa. > 6) the source code generated JavaBeans should be REAL JavaBeans with public default constructors, and not some elaborate abstraction framework with factories for instantiation (JAXB has issues here). They are stupid structs for Pete's sake! Again, this is an important goal for "start from java". In "start from xml schema", you want your generated objects to correspond to elements in the XML tree - they're just stupid xml elements for pete's sake... why would you ever want to drop element ordering information when you load XML? XML trees are simple, but they are element-ordered and mixed with and comments and text, and so slightly different from the Java data model. > 7) the source code of the (un)marshalling framework should come with a JAX-RPC XMLBeansSerializer, XMLBeansDeserialzier, XMLBeansSerializerFactory, and XMLBeansDeserializerFactory that either directly implements the JAX-RPC serialziation framework interfaces of implements those of individual JAX-RPC implementations that offer significant value-add (Apache Axis for example); these should be configurable to use user specified custom mapping file Agreed. JAXRPC doesn't do a great job at standardizing serializers and deserializers. Developers around here are interested in making sure we plug into a few of the proprietary ones, including Axis and others. > 8) really good user documentation Of course. Want to help? > I'd love to see this effort implement the JAXB specification, but only in so far that doing so does not deviate from the three golden requirements that I noted in my OBSERVATIONS. The JAXB spec currently has some problems and needs a bit of massaging to allow for seemless integration into the JAX-RPC spec. All points taken seriously. > I look forward to seeing the source code! You can get it already under an open source license, although it's only currently posted on bea.com [] Stay tuned for source code here on cvs shortly. Looking forward to working with you and others here, David Bau - --------------------------------------------------------------------- To unsubscribe, e-mail: xmlbeans-dev-unsubscribe@xml.apache.org For additional commands, e-mail: xmlbeans-dev-help@xml.apache.org Apache XMLBeans Project -- URL:
http://mail-archives.apache.org/mod_mbox/xml-xmlbeans-dev/200308.mbox/%3C00ea01c35d46$6afaefb0$65a8a8c0@lightbox%3E
CC-MAIN-2016-18
refinedweb
1,233
51.99
Wikibooks:Reading room/Administrative Assistance From Wikibooks, the open-content textbooks collection [edit] Change Username To Raiku I would like my name changed to Raiku, i am a wikipedia rollback. Raiku Lucifer Samiyaza (talk) 04:42, 29 May 2009 (UTC) - Could you please make an edit on jawiki to show that you own the account w:ja:User:Raiku? — Mike.lifeguard | talk 19:37, 29 May 2009 (UTC) [edit] Recusal and Block Request Kittins_floating_in_the_sky_yay (contribs) started out making some defensible contributions to Wikibooks, but then quickly descended into attacking Adventist Youth Honors Answer Book. He has twice replaced the content of the front page with text asserting "brainwashing cult" spaced over a period of four weeks or so. I believe these actions merit a lengthy (perhaps indefinite) block. I could block this user myself, but I would like to recuse myself on the grounds that I am highly biased. Adventist Youth Honors Answer Book is a project on which I have spent literally thousands of hours developing. I elect to not determine the block period, as I don't think I can do so fairly. Thanks for input. --Jomegat (talk) 12:43, 8 June 2009 (UTC) - Having reverted two of their edits on the 18 of May myself, the fact that they have returned exactly three weeks later ought to show that these actions have been sustained and that a short block period will not outlast their patience. -- Adrignola talk contribs 12:56, 8 June 2009 (UTC) - I have blocked them for 2 months to give them time to calm down. They seem to contribute only in monthly intervals. I think its likely they won't even notice the block until next month. Based on the intervals in which they contribute I'm not ready to say yet they came here specifically to attack Adventist Youth Honors Answer Book, but that might be the case if they continue despite having been warned and continue to do so when they can contribute again. --darklama 13:07, 8 June 2009 (UTC) [edit] Small correction Hi admins! Please correct interwiki ru:Форум → ru:Викиучебник:Форум in Wikibooks:Reading room/Navigation (protected). Tnank you. Best regards, Innv (talk) 00:58, 13 June 2009 (UTC) [edit] 212.219.90.97 If you look at the recent contributions of 212.219.90.97, you'll see they are causing widespread vandalism. I'd like to bring this to the attention of an administrator. I've rolled back their recent edits. -- Adrignola talk contribs 12:51, 15 June 2009 (UTC) - I blocked the IP for three days. Thanks for the heads-up. --Jomegat (talk) 15:55, 15 June 2009 (UTC) [edit] Request for test I am seeking some help testing a helper script I have written that supports a template I have also written. Some background - I am currently planning a book that I intend to write for Wikibooks. During this planning process, I decided that the existing tools for referencing and citing textual sources in a wikibook do not meet my needs. Specifically, the <ref> and <references /> tags provided by the cite extension require a reference and citation to exist on the same wiki markup page. This condition rarely obtains for books. Books are long, comprise many pages and the rendering of citation and footnote text generally occurs on a wiki page other than where the citation or footnote reference occurs. So, I decided to create a template, called Bref, that uses the cite extension in a way that allows the separation of text source and footnote references from citation and footnote data. However, the cite extension <reference /> tag creates back links to references. In order to separate references and reference data so they may exist on different pages, Bref renders these back links meaningless (more details about this is found on the Bref documentation page). Consequently, I created a helper script that effectively deletes these back links. I have tested the helper script myself, but would like at least one other user to test it to ensure I have not hardwired something into the script that means it works for me, but not for anyone else. Instructions for using the helper script are found at helper script instructions. For the cautious, the script is located at User:Dnessett/Template/Bref/Clean Back Links.js. It is pretty simple and a moderately experienced javascript programmer should see it is not harmful. The easiest way to determine that the helper script is working is to go to the Bref examples page and render one of the footnote or reference pages. Good candidates are the references pages for Example 1 and Example 4. If the helper script is working properly, no back links should appear at the beginning of each entry. Dnessett (talk) 18:43, 15 June 2009 (UTC) [edit] Request to Nuke duplicate pages I created a duplicate subtree of some pages in my namespace and would like an admin to nuke the old version. The reason I didn't move the subtree is I needed to edit most of the pages to conform to their new location. So, I copied them from my personal wiki after the modifications. I know I can put a quick delete template on all of the old pages, but there are approximately 30 and that would take a lot of time. The subtree that should be deleted is the one based at Dnessett/Template/Bref/Examples. Thanks. Dnessett (talk) 21:20, 26 June 2009 (UTC) Thanks. You missed two (Dnessett/Template/Bref/Examples/Example3/Chapter1/Markup Page 2 and Dnessett/Template/Bref/Examples/Example3/Chapter1/Markup Page 3). However, you saved me a great deal of time in deleting the others for which I am grateful. I have placed speedy delete templates on the two remaining pages. Dnessett (talk) 17:40, 27 June 2009 (UTC) [edit] Bfbggon An account created apparently for the sole purpose of being obnoxious. --Pi zero (talk) 18:05, 8 July 2009 (UTC) - Blocked, indefinitely, for putting explicit pictures on multiple users' pages. -- Adrignola talk contribs 18:31, 8 July 2009 (UTC) [edit] C++ Programming The C++ Programming page has apparently been fully protected for at least a year now, apparently due to some sort of edit war... I don't really know, or care, about the reasons that it was originally protected, but I imagine that the original conflict has been either resolved or forgotten by now. Isn't it time to remove protection from the page?Ohms law (talk) 21:18, 8 July 2009 (UTC) - There are three different tables of contents for the book. It's something, isn't it? Unprotecting would be the easy part. Choosing a table of contents, apparently, was and is the hard part. From the number of C++ books, people just took their balls and went home, so to speak, instead of contributing to the C++ Programming book. -- Adrignola talk contribs 01:47, 9 July 2009 (UTC) - Sorry but you are new to the problem. The existence of multiple tocs aren't an issue. For correctness lets clearly state that there was no edit war, the issue was already readdressed many times but I'm always willing to explain one more time... - The edit conflict that generated the "issue" was a result of (an admin) unilaterally and against stated opposition, proceeded to unprotect the original toc moving it into toc1 and replacing the frontpage with what is presently there. This actions have been requested to be reverted at the time and several times since then... - As a last attempt to resolve the issue and because several Wikibookias requested action. I, using the normal process of discussion (clearly publicized to the interested book community and previous active actors on the dispute) obtained a status of nonblocking to the requested reversal (still pending as valid) that all previous admins refused to act upon (as they are allowed to do). More information for both of you is available on the talk page of the project there is a log of the book history and previous discussions on the subject can be examined on VFD and the Administrative Assistance archive... --Panic (talk) 02:34, 9 July 2009 (UTC) - A show of consensus is needed to resolve the problem with the book's main page. Unfortunately I think its likely the page will remain forever protected because some people just aren't able to move on and won't accept putting it to a vote to decide its future. --darklama 12:50, 9 July 2009 (UTC) [edit] report vandalism - Special:Contributions/Bfbggonnnnn --Ans (talk) 13:58, 9 July 2009 (UTC) - Special:Contributions/Bfbggonnnn --Ans (talk) 14:00, 9 July 2009 (UTC) Lets not forget - Special:Contributions/Bfbggonnn - Special:Contributions/Bfbggonn - Special:Contributions/Bfbggon - Special:Contributions/Bfbggonnnnnn --Thenub314 (talk) 14:46, 9 July 2009 (UTC) Well, they've all been blocked by myself or SB Johnny. I've escalated this and two of our CheckUsers, SB Johnny and Mike.lifeguard, will be looking into whether an IP range block will be feasible. -- Adrignola talk contribs 14:59, 9 July 2009 (UTC) - Looks relatively safe to block... there are some other accounts with no edits, and a medicinal product spammer that's probably unrelated. Keep an eye on Category:Requests for unblock just in case, please. --SB_Johnny talk 15:50, 9 July 2009 (UTC) - I've also added the offending image that was being posted to MediaWiki:Bad image list, so it won't be displayed as a picture (only a link) if this ever becomes a problem again. -- Adrignola talk contribs 17:05, 9 July 2009 (UTC)
http://en.wikibooks.org/wiki/WB:VIP
crawl-002
refinedweb
1,602
60.14
I am not sure why I get continuing told the error of java22 in my code. I searched other person's question like around. like here Compiler error: "class, interface, or enum expected" But I could not find suitable answer for this. It seems like error not only class, interface or enum import part. Some cording has issue it. But but if so I would like to know, which part is course of the problem in this case? Also, I would like to know the if I want disable to use the num2 for case2. Since it is factorial, it should ask only num1. Thank you for all the help. This is the message Calc.java:22: error: class, interface, or enum expected import java.util.*; ^ 1 error import java.util.*; public class Calc { public static void main(String[] args) { NumCalc calc = new NumCalc(); System.out.println("Welcome to Math NumCalc!\nPlease choose an option:" + "\n\t1 " + "- add two real numbers" + "\n\t2 " + "- subtract two real numbers" + "\n\t3 " + "- multiply two real numbers" + "\n\t4 " + "- devide two real numbers" + "\n\t5 " + "- get the factorial of an number" + "\n\t6 " + "- menu" + "\n\t0 " + "- exit" ); calc.run(); } } import java.util.*; public class NumCalc { private int option = -1; private Scanner scan, num1, num2; //private int opt; double ans = 0.0; //int category; public NumCalc() { scan = new Scanner(System.in); } // entry point for class public void run() { System.out.println("\n? " + scan); int scan = scan.nextInt(); for (int i=0;i < count; i++) { option = option + scan.nextInt(); } System.out.println("Enter 1st num:"); int num1 = scan.nextInt(); System.out.println("Enter 2nd num"); int num2 = scan.nextInt(); switch (option) { case 6: ans = num1 + num2; System.out.println(num1 + " + " + num2 + "=" + ans); break; case 5: ans = num1 - num2; System.out.println(num1 + " - " + num2 + "=" + ans); break; case 4: ans = num1 * num2; System.out.println(num1 + " * " + num2 + "=" + ans); break; case 3: ans = num1 / num2; System.out.println(num1 + " / " + num2 + "=" + ans); break; case 2: num2 = boolean(false); // No 2nd number. int ans = 1; for (i = 1;i <= n; i++) { ans *= n; } break; System.out.println("Factorial of" + num1 + " = "); case 1: //opt = opt + scan.nextInt(); continue; default: } } } The simple solution, as other people have said, is to split your two public classes into two separate .java files. That will solve both the error you've already encountered and another that you were going to encounter later... but "too many public classes" is not what your Java compiler is complaining about. The real reason you're getting that error is that you can't put import statements after class declarations. The error message is easy to misread. It seems to be complaining about what you're importing --- probably provoking a response like, "But I am importing a class!". But note where the ^ is pointing --- not at java.util.*, but at the word import: Calc.java:22: error: class, interface, or enum expected import java.util.*; ^ 1 error This error is actually complaining about the out-of-place import statement --- it shouldn't be there at all. Once you've declared your first class, it's too late to import anything else. In a roundabout way, it actually says so: By line 22 of Calc.java, nothing can appear at the top level but type declarations --- the " interface, class, or enum" it mentioned --- so encountering a line that starts with import is "unexpected", meaning not allowed. You can verify this by commenting out the second import (line 22) and compiling. You'll still get errors, but different ones. As an aside, you are allowed to import java.util.*; more than once. The redundant statements will be ignored... as long as they're in the right place. You can verify this by moving the second import up to around line 3 or 4 and compiling. Again, you'll still get errors, but not about that. A single .java file (called a "compilation unit" in the language spec) has the following three parts, which must appear in this order: packagedeclarations. importstatements. class, enum, or interface. From the Java 1.8 Language Specification, Section 7.3: "Compilation Units"]: CompilationUnitis the goal symbol (§2.1) for the syntactic grammar (§2.3) of Java programs. It is defined by the following productions: CompilationUnit: [ PackageDeclaration] { ImportDeclaration} { TypeDeclaration} A compilation unit consists of three parts, each of which is optional[...] In case that last phrase made you wonder: Yes, a completely empty .java file will compile without warnings... and without producing any .class files. As has been pointed out by others, you can't have more than one top-level public class or other type declaration in a single file. Unless you're willing to nest one of Calc and NumCalc inside the other, they have to split up into Calc.java and NumCalc.java. Actually, you could sidestep the problem by reducing one class's visibility to package-default, but that's fragile and not the way Java is generally done. If you tried to use the package-default class in any other .java file, even one in the same package, it would fail to compile because it couldn't find the supposedly-package-visible class --- either Calc would be in the wrongly-named NumCalc.java (not where the compiler will look for it), or NumCalc would be hiding out inside Calc.java. But why bother with all that? You could combine the two classes into one class very easily, and have a more coherent project. (I'm not sure why they're separate classes in the first place.)
https://codedump.io/share/i2ROCNFAlsWY/1/error-java23-error-class-interface-or-enum-expected-import-javautil
CC-MAIN-2019-09
refinedweb
921
68.26
Ticket #1241 (new bug) Executing long-running python scripts hang the orange-canvas UI Description Steps to reproduce: Add a python script node with: while True: pass Now try to move the node in the canvas. I'd suggest running every such codebyte in a separate thead or process. A different process would be nice because that way exit() won't kill orange-canvas. If this would cause too much overhead for data transfer then the thread option has another problem: E.g. try to use this python node: import thread def func(): print(123) thread.start_new_thread(func, ()) But nothing is printed! See this error: Calling <function write at 0x9b24d4c> with ('123',) {} from the wrong thread. Queuing the call! Calling <function write at 0x9b24d4c> with ('\n',) {} from the wrong thread. Queuing the call! So something went wrong in the queuing I guess. Change History Note: See TracTickets for help on using tickets. I tried loading orange with a not small data set (250,000 rows, 30 columns) from a .tab file and it completely broke down. I couldn't close the file loading dialog and there's no indication whether it's stuck temporarily or forever. After a few minutes the process was stuck at 700MB memory usage and 100% cpu. So I gave up and killed it. I believe orange should keep the data stored and processed in one process and the GUI in another. That way there GUI will always be responsive. Also, there should always be an indication of what's orange doing now (e.g. in the bottom status bar).
http://orange.biolab.si/trac/ticket/1241?cversion=0&cnum_hist=1
CC-MAIN-2014-41
refinedweb
264
76.32
How to use Graph Toolkit in Teams App inside Teams Tab In this article, we will learn about Graph Toolkit and how to integrate Graph toolkit in Teams App. What is Graph Toolkit? Microsoft Graph Toolkit is a library that provides us a collection of reusable components that can be easily configured in our applications(mobile, web, SPA, teams app), etc which takes care of underlying authentication and accessing the data from Graph API and display it to the user. Graph Toolkit provides various authentication providers that also can be used based on our business case. These providers are to be initialized once and then all the components available in Graph Toolkit will automatically use this auth and authorization flow and get data from Graph API. Once everything is configured properly, it would just take a couple of lines to use the components Available. Let us see step by step on how to use Graph Toolkit in Microsoft Teams App(tab) Note- if you don’t have Teams Yeoman Generator installed, use the below command to install it npm install generator-teams@preview --global Step 1 – Create Teams App of type Tab Open command prompt, create a new folder of your choice in your drive where you wish to create the solution. Run the below command. yo teams We would be asked with series of questions, please refer to the below screenshot for options you have to choose. For this sample, we are going to create a tab without SSO support. Note – As we are choosing SSO support as No, the user will have to log in to Teams Tab separately if you wish to make the Graph API calls…We won’t be able to use the Teams Login token to make Graph API calls but have to make separate calls. It is also possible to have SSO support where users don’t have to log in but we would also need to have a backend(server) making use of ID token from Teams App and getting access token to make Graph API call on behalf of the user flow… I would try to write a separate article on it. It will take some time and finally you should be able to see below. Step – Install Microsoft Graph Toolkit Let us install required packages via npm, run the below command. npm install @microsoft/teams-js @microsoft/mgt-element @microsoft/mgt-teams-msal2-provider @microsoft/mgt-components @microsoft/mgt Note – To use Toolkit, we have to also install Teams SDK and required providers and components. In this sample we are going to use Teams Provider which uses MSAL provider internally, you can read about Teams provider at below link Ideally, we should use Teams MSAL2Provider for authentication purposes as it is more secure, but I had some diffculties making it run while writing this article so went ahead and used Teams Provider….After raising issue in repo, Toolkit team has provided me instruction on mistake I was making and it fixed it…but as all the screenshot etc was referring to TeamsProvider I have kept same as in this artitlce…but later I tried with MSAL2Provider and it worked fine…so I have given a side note at end of the article to specify changes to make it work with MSAL2Provider So I have separately installed ‘@microsoft/mgt’ package, make sure you are also doing so. Open your solution in Visual Studio code using ‘code .’ Step 3 – Creating the auth popup page As mentioned before, the user needs to sign in to make use of Graph Toolkit and indirectly get data from Graph API. So in this step, we will create a page in our app that will open in a popup to follow the auth flow. On this particular page, we have to use import the provider class and call handleAuth method, we can make it as fancy as we want based on our need but ideally, if this method would be called it will be automatically asking the user to sign in when the Login Graph Toolkit component is used. Create a new page in public folder as “src\public\auth.html”. Copy below code <!DOCTYPE html> <html> <head> <script src=" crossorigin="anonymous"></script> <script src=" </head> <body> <script> mgt.TeamsProvider.handleAuth(); </script> </body> </html> Step 4- Create a new app registration in Azure Active Directory Go to portal.azure.com Choose Azure Active Directory Click on App Registration from left Blade, Select New Registration Provide the name of your App ‘TeamsAppGraphToolkit1 ‘. Click on Register at the bottom of the page Once created, click on Authentication on the left blade, choose Add platform and select Single-page application Enter ‘Redirect URIs’ as for a sample, ideally, once you publish this app, it should be the domain of your team’s app. We will also have to change this to ngrok url while doing testing. Next thing here we have to enable Implicit this App regisration supports. As Teams Provider user MSAL(not MSAL2) which only supports Implicit Flow for OAuth, we have enable both Access tokens and ID tokens. Save it and note down client Id of this App from Overview tab, we would required it later. Step – Install Microsoft Graph Toolkit React components. Run the below command to install mgt react components to be used. npm i @microsoft/mgt-react Step – Modify code to use Graph Toolkit components Go to src\client\graphToolkitDemoTab\GraphToolkitDemoTab.tsx Import below libraries import {Providers, TeamsProvider} from '@microsoft/mgt' import { Login } from '@microsoft/mgt-react'; Modify the Tab component and on top, initialize the Teams Provider export const GraphToolkitDemoTab = () => { TeamsProvider.microsoftTeamsLib = microsoftTeams; Providers.globalProvider = new TeamsProvider({ clientId: '4t2eba12-24c4-4e23-b1d8-c22c4051545b', scopes: ['User.Read','Mail.ReadBasic'], authPopupUrl:"/auth.html" }); //..... Modify the clientId you noted earlier from Azure AD App Registration. Next, let us add the Login component to the render method to display the Sign In button.> </Flex.Item> <Flex.Item styles={{ padding: ".8rem 0 .8rem .5rem" }}> <Text size="smaller" content="(C) Copyright Siddharth Vaghasia" /> </Flex.Item> </Flex> </Provider> ); Step – Test the app Once you have all the above setup, let us first see if everything works fine, and then we will try different Graph Toolkit components. Go to command prompt and run the below command, this command comes with yo teams which run ngrok in the background and also create teams app package for us.. gulp ngrok-serve Once it has run successfully, it should show some like below Next thing, we will have to add the ngrok URL in Azure AD App registration as a redirect URL. Step – Test the App in Teams Go to teams and Click on Apps on left panel and then select upload a custom app(this button will only visible if side loading is enabled by Teams Adminstrator) Click on Upload a custom app and select ‘Upload for me and my teams’, Select the zip package at ‘D:\SP\samples\teamsapps\teams-graphtoolkit\package\teamsgraphtoolkit.zip’ Note -This zip file will be updated everything you run gulp ngrok-serve, so you have to make sure you upload the latest zip package whenever you have new ngrok url and also update the same in App Registration in Azure portal. Click on Add Once installed, we should see below output As you see the Sign In button has come from Login Component which we added. Click on it, it should open below auth popup and ask us to log in Once logged in, we should see below that our integration with Graph Toolkit worked 🙂 Now let us see how we can use another component with some minor changes. Agenda Component The agenda component will display the currently logged-in user’s meeting . You can read about the Agenda component here First, modify import to include the Agenda component import { Login ,Agenda} from '@microsoft/mgt-react'; Then add Scope to add permission for the user’s constent. Providers.globalProvider = new TeamsProvider({ clientId: '4t2eba12-24c4-4e23-b1d8-c22c4051545b', scopes: ['User.Read','Mail.ReadBasic','Calendars.Read'], authPopupUrl:"/auth.html" }); Add Agenda component to render method> My Meetings <div> <Agenda ></Agenda> </div> </div> </div> </Flex.Item> <Flex.Item styles={{ padding: ".8rem 0 .8rem .5rem" }}> <Text size="smaller" content="(C) Copyright Siddharth Vaghasia" /> </Flex.Item> </Flex> </Provider> You need to rerun the solution again as we have added new scope permission. Run the gulp ngrok-serve command again, add the url in Azure AD app registration and add the new package to Teams, Click on Sign In, you must provide consent again as we have added new Scope. Once you Sign In, we should see the current user’s meeting as below Conclusion In this article, we have seen step by step guide on how to integrate Graph Toolkit in your Teams app and use the available component by just configuration. You can read more about all the components available here As of today, the below components are available which can be used easily and there are many configurations also available for each component to customize. Side Note – If you want to use MSAL2Provider, you have just made the below changes, everything else should work as it is as we are just changing the provider we are using. The initialize provider code would look like below “GraphToolkitDemoTab” TeamsProvider.microsoftTeamsLib = microsoftTeams; Providers.globalProvider = new TeamsMsal2Provider({ clientId: '123213-123-4233-232-c72232312345b', scopes: ['User.Read','Mail.ReadBasic','Calendars.Read'], authPopupUrl:"/auth.html" }); Below would be library imports import {Providers, TeamsProvider} from '@microsoft/mgt' In your auth.html, there would be below code <!DOCTYPE html> <html> <head> <script src=" crossorigin="anonymous"></script> <script src=" </head> <body> <script> mgt.TeamsMsal2Provider.handleAuth(); </script> </body> </html> Hope this helps…Happy Coding..!!!
https://siddharthvaghasia.com/2022/01/07/how-to-use-graph-toolkit-in-teams-app-inside-teams-tab/
CC-MAIN-2022-21
refinedweb
1,614
56.89
Posted 04 Jan 2009 Link to this post Posted 05 Jan 2009 Link to this post Posted 08 Jan 2009 Link to this post Posted 10 Mar 2009 Link to this post Posted 11 Mar 2009 Link to this post Posted 12 Mar 2009 Link to this post Posted 16 Mar 2010 Link to this post Posted 17 Mar 2010 Link to this post Posted 13 Jan 2011 Link to this post Posted 18 Jan 2011 Link to this post LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression Posted 19 Jan 2011 Link to this post Posted 24 Jan 2011 Link to this post Posted 25 Jan 2011 Link to this post Posted 14 17 Sep 2012 Link to this post < asp:PresenterObjectDataSource ...some more attributes... > SelectParameters > asp:ControlParameter ControlID = "RadGrid" PropertyName "MasterTableView.FilterExpression" Name "filter" /> </ Posted 22 Apr 2015 Link to this post I am trying to update some old code that uses the approach outlined here. I have successfully updated the Telerik controls etc. but now the old code is obsolete. Is there any sort of guideline to show how this should NOW be done? Thank you. Here are the first few lines of the old approach. The IQueryable<T> is not defined anymore. using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Threading; public static class DynamicQueryable { public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values) Posted 23
http://www.telerik.com/forums/filtering-with-linq-through-an-objectdatasource
CC-MAIN-2017-13
refinedweb
267
65.93
HTTP/2 is the second major version of the Hyper Text Transfer Protocol used to transfer web data. Note Not all ASGI Servers support HTTP/2. The recommended ASGI server, Hypercorn, does. To use HTTP/2 in development you will need to create some SSL certificates and run Quart with SSL. With HTTP/2 the server can choose to pre-emptively push additional responses to the client, this is termed a server push and the response itself is called a push promise. Server push is very useful when the server knows the client will likely initiate a request, say for the css or js referenced in a html response. In Quart server push can be initiated during a request via the function make_push_promise(), for example, make_push_promise() async def index(): await make_push_promise(url_for('static', filename='css/minimal.css')) return await render_template('index.html') The push promise will include (copy) header values present in the request that triggers the push promise. These are to ensure that the push promise is responded too as if the request had made it. A good example is the Accept header. The full set of copied headers are SERVER_PUSH_HEADERS_TO_COPY in the request module. Accept SERVER_PUSH_HEADERS_TO_COPY This functionality is only useable with ASGI servers that implement the HTTP/2 Server Push extension. If the server does not support this extension Quart will ignore the push promises (as with HTTP/1 connections). Hypercorn, the recommended ASGI server, supports this extension. HTTP/2 Server Push When testing server push,the QuartClient push_promises list will contain every push promise as a tuple of the path and headers, for example, QuartClient push_promises async def test_push_promise(): test_client = app.test_client() await test_client.get("/push") assert test_client.push_promises[0] == ("/", {}) At the time of writing there aren’t that many HTTP/2 clients. The best option is to use a browser and inspect the network connections (turn on the protocol information). Otherwise curl can be used, if HTTP/2 support is installed, as so, $ curl --http2 ... If you wish to communicate via HTTP/2 in python the Hyper library is the best choice. It can be configured to work with requests.
https://pgjones.gitlab.io/quart/how_to_guides/using_http2.html
CC-MAIN-2020-40
refinedweb
355
56.96
Community Wiki Post Drafts #Question: Why does my Tkinter Button command execute early and only once? I want to create a GUI, where I can click a button, and it will print a message on the command line. #compatibility note: #Python 2.7 users should import Tkinter; 3.X users should import tkinter. from tkinter import Tk, Button def excited(message): print(message + "!") root = Tk() button = Button(text="Click Me!", command=excited("Hello, World")) button.pack() root.mainloop() When I run this, it prints “Hello, World!” once during startup, and clicking the button has no effect. Why is this? #Answer ##What’s Going On button = Button(text="Click Me!", command=excited("Hello, World")) This code is equivalent to: result = excited("Hello, World") button = Button(text="Click Me!", command=result) Since you’re calling excited before you even create the button, “Hello, World!” is printed at the start of the program. excited has no explicit return value, so when you call it, it returns None. Your Button initialization is effectively the same as: button = Button(text="Click Me!", command=None) Since command is None, nothing happens when you click the button. ##How to Fix it One possible solution is to only bind functions that take no arguments: from tkinter import Tk, Button def excited(): print("Hello, World!") root = Tk() #be sure to NOT put parentheses after `excited` on this next line button = Button(text="Click Me!", command=excited) button.pack() root.mainloop() But this may be impossible. What if you have to pass arguments? In that case, you can use a lambda expression to construct a callable with no arguments. from tkinter import Tk, Button def excited(message): print(message + "!") root = Tk() button = Button(text="Click Me!", command=lambda: excited("Hello, World")) button.pack() root.mainloop() Simply put, because excited("Hello, World") is in a lambda, it won’t execute right away, instead waiting until the button is clicked.
https://sopython.com/wiki/Community_Wiki_Post_Drafts
CC-MAIN-2019-13
refinedweb
318
52.56
Although a lot of database work in many web applications involves single table queries and changes, in many cases you make multiple changes to a database. In these cases, you should consider using transactions. A transaction defines a unit of work to be performed, and for the transaction to complete, each part of it has to complete successfully. If everything works, the transaction is committed to the database. If not, all the changes are rolled back. You also have the option to nest transactions, in case you have a very complicated unit of work that is broken into “sub-units” of work. In some of my own code, I’ve created a method to manage these nested transactions by using a Stack collection. A stack is a basic computer science concept that helps implement a last-in, first-out structure. When you start a transaction, you push the transaction onto the stack. When you commit the transaction, you pop it off the stack. If you have to roll back a transaction, you need to roll back each nested transaction in reverse order. The stack is perfect for this arrangement. Here are the functions I added to my database class: public void BeginTransaction() { SqlTransaction currentTrans = currentConnection.BeginTransaction(); transactions.Push(currentTrans); } public void RollbackTransaction() { SqlTransaction currentTrans; while (transactions.Count > 0) { currentTrans = (SqlTransaction)transactions.Pop(); currentTrans.Rollback(); } } public void CommitTransaction() { SqlTransaction currentTrans = (SqlTransaction)transactions.Peek(); currentTrans.Commit(); transactions.Pop(); } public SqlTransaction CurrentTransaction { get { if (transactions.Count > 0) return (SqlTransaction)transactions.Peek(); else return null; } } I have the transactions variable declared as: private Stack transactions = new Stack(); Each time I run a function within the Database class, I look to see whether the CurrentTransaction is null; if not, I set the Transaction property of each SqlCommand object equal to it. This enlists the command in the transaction. When I’m done with all my work, I call CommitTransaction, which commits the current transaction to the database. If any errors occur, I can call RollbackTransaction, which rolls back all pending transactions. A failure in one part of the transaction means the entire thing needs to be undone in this model. In regards to using the Stack object, the Peek method returns the top object without removing it from the stack; doing this lets you use the object without removing it from the stack, because a transaction may have three or four actions before it’s [email protected].
https://www.codeguru.com/csharp/database-tip-managing-transactions-with-a-stack/
CC-MAIN-2021-43
refinedweb
402
55.34
Translate an address to symbolic information #include <dlfcn.h> int dladdr( void *address, Dl_info *dlip ); The Dl_info structure includes the following members: If dladdr() can't find a symbol that describes the specified address, the function sets dli_sname and dli_saddr to NULL. libc Use the -l c option to qcc to link against this library. This library is usually included automatically. The dladdr() function determines whether the specified address is located within one of the objects that make up the calling application's address space. 0 if the specified address can't be matched, or nonzero if it could be matched.
http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.neutrino.lib_ref/topic/d/dladdr.html
CC-MAIN-2021-17
refinedweb
101
55.03
thanks ken, i knew i was fudging by not listing out the various services. what do you think of Joe's idea of not trying to list the services, but leaving it open? I guess the "XML thing" to do would be to use a URI, like how namespaces work. ----- Original Message ----- From: "Ken Keiser" <address@hidden> To: "John Caron" <address@hidden>; <address@hidden> Sent: Tuesday, May 14, 2002 2:08 PM Subject: RE: New Catalog XML Draft > This looks like a good attempt to handling the issue of multiple access interfaces for the same dataset and it seems fairly straightforward to me. One comment, I don't think OpenGIS is a service type. Rather specific OpenGIS services would be individual service types - such as WMS, WCS, WFS, etc. The service type specification implies the resulting output of the service and how to communicate with it. In the same sense that specifying type=DODS lets a DODS client know that it can then get data from the described server, then type=WCS would let a WCS client know that the server is compatible. > > -----Original Message----- > From: John Caron [mailto:address@hidden > Sent: Tuesday, May 14, 2002 1:28 PM > To: address@hidden > Subject: New Catalog XML Draft > > > Proposed changes to the THREDDS catalog format are at: > > > > The current format is documented at: > > > > > Summary of changes: > a.. add <attribute> elements to collection, dataset, service > b.. rename "server" element to "service". > c.. add new service types: (DODS | ADDE | NetCDF | Catalog | FTP | OpenGIS > | WSDL | Other) . > d.. allow multiple services per dataset: add <access> child element of > dataset, where you list any number of services for that dataset, and add > <serviceList> element so you can define a list of services. "serviceId" now > refers to either a service or a serviceList. Use a serviceList when the same > dataset urlPath can be appended onto all service bases. > e.. generalize <datasetDescRef> element to <metadataRef>, where > "DatasetDesc" is one of several metadata types. proposed types: (DatasetDesc > | DublinCore | DIF | ADN | FGDC | LAS | Other) > f.. add "ID" and "alias" attributes to dataset, so that a dataset can be > an alias to another dataset. > Please send comments to me or to this.
https://www.unidata.ucar.edu/support/help/MailArchives/thredds/msg00095.html
CC-MAIN-2019-09
refinedweb
361
69.72
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards Let's say you have a sample mean, you may wish to know what confidence intervals you can place on that mean. Colloquially: "I want an interval that I can be P% sure contains the true mean". (On a technical point, note that the interval either contains the true mean or it does not: the meaning of the confidence level is subtly different from this colloquialism. More background information can be found on the NIST site). The formula for the interval can be expressed as: Where, Ys is the sample mean, s is the sample standard deviation, N is the sample size, /α/ is the desired significance level and t(α/2,N-1) is the upper critical value of the Students-t distribution with N-1 degrees of freedom. From the formula, it should be clear that: The following example code is taken from the example program students_t_single_sample.cpp. We'll begin by defining a procedure to calculate intervals for various confidence levels; the procedure will print these out as a table: // Needed includes: #include <boost/math/distributions/students_t.hpp> #include <iostream> #include <iomanip> // Bring everything into global namespace for ease of use: using namespace boost::math; using namespace std; void confidence_limits_on_mean( double Sm, // Sm = Sample Mean. double Sd, // Sd = Sample Standard Deviation. unsigned Sn) // Sn = Sample Size. { using namespace std; using namespace boost::math; // Print out general info: cout << "__________________________________\n" "2-Sided Confidence Limits For Mean\n" "__________________________________\n\n"; cout << setprecision(7); cout << setw(40) << left << "Number of Observations" << "= " << Sn << "\n"; cout << setw(40) << left << "Mean" << "= " << Sm << "\n"; cout << setw(40) << left << "Standard Deviation" << "= " << Sd << "\n"; We'll define a table of significance/risk levels for which we'll compute intervals: double alpha[] = { 0.5, 0.25, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 }; Note that these are the complements of the confidence/probability levels: 0.5, 0.75, 0.9 .. 0.99999). Next we'll declare the distribution object we'll need, note that the degrees of freedom parameter is the sample size less one: students_t dist(Sn - 1); Most of what follows in the program is pretty printing, so let's focus on the calculation of the interval. First we need the t-statistic, computed using the quantile function and our significance level. Note that since the significance levels are the complement of the probability, we have to wrap the arguments in a call to complement(...): double T = quantile(complement(dist, alpha[i] / 2)); Note that alpha was divided by two, since we'll be calculating both the upper and lower bounds: had we been interested in a single sided interval then we would have omitted this step. Now to complete the picture, we'll get the (one-sided) width of the interval from the t-statistic by multiplying by the standard deviation, and dividing by the square root of the sample size: double w = T * Sd / sqrt(double(Sn)); The two-sided interval is then the sample mean plus and minus this width. And apart from some more pretty-printing that completes the procedure. Let's take a look at some sample output, first using the Heat flow data from the NIST site. The data set was collected by Bob Zarr of NIST in January, 1990 from a heat flow meter calibration and stability analysis. The corresponding dataplot output for this test can be found in section 3.5.2 of the NIST/SEMATECH e-Handbook of Statistical Methods.. __________________________________ 2-Sided Confidence Limits For Mean __________________________________ Number of Observations = 195 Mean = 9.26146 Standard Deviation = 0.02278881 ___________________________________________________________________ Confidence T Interval Lower Upper Value (%) Value Width Limit Limit ___________________________________________________________________ 50.000 0.676 1.103e-003 9.26036 9.26256 75.000 1.154 1.883e-003 9.25958 9.26334 90.000 1.653 2.697e-003 9.25876 9.26416 95.000 1.972 3.219e-003 9.25824 9.26468 99.000 2.601 4.245e-003 9.25721 9.26571 99.900 3.341 5.453e-003 9.25601 9.26691 99.990 3.973 6.484e-003 9.25498 9.26794 99.999 4.537 7.404e-003 9.25406 9.26886 As you can see the large sample size (195) and small standard deviation (0.023) have combined to give very small intervals, indeed we can be very confident that the true mean is 9.2. For comparison the next example data output is. __________________________________ 2-Sided Confidence Limits For Mean __________________________________ Number of Observations = 3 Mean = 37.8000000 Standard Deviation = 0.9643650 ___________________________________________________________________ Confidence T Interval Lower Upper Value (%) Value Width Limit Limit ___________________________________________________________________ 50.000 0.816 0.455 37.34539 38.25461 75.000 1.604 0.893 36.90717 38.69283 90.000 2.920 1.626 36.17422 39.42578 95.000 4.303 2.396 35.40438 40.19562 99.000 9.925 5.526 32.27408 43.32592 99.900 31.599 17.594 20.20639 55.39361 99.990 99.992 55.673 -17.87346 93.47346 99.999 316.225 176.067 -138.26683 213.86683 This time the fact that there are only three measurements leads to much wider intervals, indeed such large intervals that it's hard to be very confident in the location of the mean.
http://www.boost.org/doc/libs/1_53_0/libs/math/doc/sf_and_dist/html/math_toolkit/dist/stat_tut/weg/st_eg/tut_mean_intervals.html
CC-MAIN-2014-52
refinedweb
910
56.79
Opened 7 years ago Closed 7 years ago #11227 closed (wontfix) tutorial #02 - Description Code part: def was_published_today(self): return self.pub_date.date() == datetime.date.today() This baffled me for some time - after adding anything I got false. The problem was with time zones - Django's settings.py had another time zone. I would add a small comment in the documentation, or change datetime.date.today() to some function which respects time zone in settings.py. Change History (1) comment:1 Changed 7 years ago by Note: See TracTickets for help on using tickets. In the tutorial, all the data should be created using Django, so all the data should have the same time zone. The tutorial has been run many times, by many people, in many time zones, and to the best of my knowledge, this is the first time this problem has been reported. Without more details to describe exactly what you did to generate this problem, I'm not sure what comment we should be adding.
https://code.djangoproject.com/ticket/11227
CC-MAIN-2016-44
refinedweb
169
64
Another approach to error propagation Posted March 07, 2013 at 09:26 AM | categories: statistics | tags: | View Comments Updated April 23, 2013 at 09:28 PM In the previous section we examined an analytical approach to error propagation, and a simulation based approach. There is another approach to error propagation, using the uncertainties module (). You have to install this package, e.g. pip install uncertainties. After that, the module provides new classes of numbers and functions that incorporate uncertainty and propagate the uncertainty through the functions. In the examples that follow, we repeat the calculations from the previous section using the uncertainties module. Addition and subtraction import uncertainties as u A = u.ufloat((2.5, 0.4)) B = u.ufloat((4.1, 0.3)) print A + B print A - B >>> >>> >>> 6.6+/-0.5 -1.6+/-0.5 Multiplication and division F = u.ufloat((25, 1)) x = u.ufloat((6.4, 0.4)) t = F * x print t d = F / x print d >>> >>> >>> 160.0+/-11.8726576637 >>> >>> 3.90625+/-0.289859806243 Exponentiation t = u.ufloat((2.03, 0.0203)) print t**5 from uncertainties.umath import sqrt A = u.ufloat((16.07, 0.06)) print sqrt(A) # print np.sqrt(A) # this does not work from uncertainties import unumpy as unp print unp.sqrt(A) 34.4730881243+/-1.72365440621 >>> >>> >>> >>> 4.00874045057+/-0.00748364738749 ... >>> >>> 4.00874045057+/-0.00748364738749 Note in the last example, we had to either import a function from uncertainties.umath or import a special version of numpy that handles uncertainty. This may be a limitation of teh uncertainties package as not all functions in arbitrary modules can be covered. Note, however, that you can wrap a function to make it handle uncertainty like this. import numpy as np wrapped_sqrt = u.wrap(np.sqrt) print wrapped_sqrt(A) >>> >>> 4.00874045057+/-0.00748364738774 Propagation of errors in an integral import numpy as np import uncertainties as u x = np.array([u.ufloat((1, 0.01)), u.ufloat((2, 0.1)), u.ufloat((3, 0.1))]) y = 2 * x print np.trapz(x, y) >>> >>> ... ... >>> >>> >>> >>> 8.0+/-0.600333240792 Chain rule in error propagation v0 = u.ufloat((1.2, 0.02)) a = u.ufloat((3.0, 0.3)) t = u.ufloat((12.0, 0.12)) v = v0 + a * t print v >>> >>> >>> >>> 37.2+/-3.61801050303 A real example? This is what I would setup for a real working example. We try to compute the exit concentration from a CSTR. The idea is to wrap the “external” fsolve function using the uncertainties.wrap function, which handles the units. Unfortunately, it does not work, and it is not clear why. But see the following discussion for a fix. from scipy.optimize import fsolve Fa0 = u.ufloat((5.0, 0.05)) v0 = u.ufloat((10., 0.1)) V = u.ufloat((66000.0, 100)) # reactor volume L^3 k = u.ufloat((3.0, 0.2)) # wrapped_fsolve = u.wrap(fsolve) CA_sol = wrapped_fsolve(func, CA_guess) print 'The exit concentration is {0} mol/L'.format(CA_sol) >>> >>> >>> >>> >>> >>> >>> ... ... ... ... ... >>> ... >>> >>> >>> <function fsolve at 0x148f25f0> >>> >>> The exit concentration is NotImplemented mol/L I got a note from the author of the uncertainties package explaining the cryptic error above, and a solution for it. The error arises because fsolve does not know how to deal with uncertainties. The idea is to create a function that returns a float, when everything is given as a float. Then, we wrap the fsolve call, and finally wrap the wrapped fsolve call! - Step 1. Write the function to solve with arguments for all unitted quantities. This function may be called with uncertainties, or with floats. - Step 2. Wrap the call to fsolve in a function that takes all the parameters as arguments, and that returns the solution. - Step 3. Use uncertainties.wrap to wrap the function in Step 2 to get the answer with uncertainties. Here is the code that does work: import uncertainties as u from scipy.optimize import fsolve Fa0 = u.ufloat((5.0, 0.05)) v0 = u.ufloat((10., 0.1)) V = u.ufloat((66000.0, 100.0)) # reactor volume L^3 k = u.ufloat((3.0, 0.2)) # rate constant L/mol/h # Step 1 # Step 2 def Ca_solve(v0, k, Fa0, V): 'wrap fsolve to pass parameters as float or units' # this line is a little fragile. You must put [0] at the end or # you get the NotImplemented result sol = fsolve(func, 0.1 * Fa0 / v0, args=(v0, k, Fa0, V))[0] return sol # Step 3 print u.wrap(Ca_solve)(v0, k, Fa0, V) 0.005+/-0.000167764327667 It would take some practice to get used to this, but the payoff is that you have an “automatic” error propagation method. Being ever the skeptic, let us compare the result above to the Monte Carlo approach to error estimation below. import numpy as np from scipy.optimize import fsolve N = 10000 Fa0 = np.random.normal(5, 0.05, (1, N)) v0 = np.random.normal(10.0, 0.1, (1, N)) V = np.random.normal(66000, 100, (1,N)) k = np.random.normal(3.0, 0.2, (1, N)) SOL = np.zeros((1, N)) for i in range(N): def func(Ca): return Fa0[0,i] - v0[0,i] * Ca + V[0,i] * (-k[0,i] * Ca**2) SOL[0,i] = fsolve(func, 0.1 * Fa0[0,i] / v0[0,i])[0] print 'Ca(exit) = {0}+/-{1}'.format(np.mean(SOL), np.std(SOL)) Ca(exit) = 0.00500829453185+/-0.000169103578901 I am pretty content those are the same! 1 Summary The uncertainties module is pretty amazing. It automatically propagates errors through a pretty broad range of computations. It is a little tricky for third-party packages, but it seems doable. Read more about the package at. Copyright (C) 2013 by John Kitchin. See the License for information about copying.
http://kitchingroup.cheme.cmu.edu/blog/2013/03/07/Another-approach-to-error-propagation/
CC-MAIN-2018-30
refinedweb
963
69.89
OTP Generation in Java In this tutorial, I will show you the program to generate a random OTP in java. They are a unique pattern of numbers of a defined length, used for security purposes. For instance, OTP is used to access our bank account while doing online transaction in order to verify our identity from the bank account, they send us OTP(One Time Password) on our registered number or email-id making the process quicker. The following code explains how to generate OTP easily. So let’s get started to learn OTP generation in Java using random class. Java program to generate OTP This program we will use Random class: Since Java Random class is used to generate a series of random numbers. - java.util package contains Random class. - An instance of Random class is used to generate random numbers. - If two instances have the same seed value, then they will generate the same sequence of random numbers. Java Code: import java.util.*; public class Prog { public static char[] generatorOTP(int length) { System.out.print("Your OTP is : "); //Creating object of Random class Random obj = new Random(); char[] otp = new char[length]; for (int i=0; i<length; i++) { otp[i]= (char)(obj.nextInt(10)+48); } return otp; } public static void main(String[] args) { System.out.println(generatorOTP(4)); } } In this program, the method generatorOTP(int) takes in the length of OTP as parameter. We have created an array of characters which will store the desired OTP. Each execution of the program generates a unique OTP. The method nextInt() returns next int value from random number generator sequence. We add a displacement of 48 to the generated number. It converts number to its ascii value before casting it to a character. As a result, the method returns the OTP at the end of the loop. Output: Your OTP is : 7916 Also read,
https://www.codespeedy.com/otp-generation-in-java/
CC-MAIN-2019-43
refinedweb
314
57.37
[SCRIPT] Automatic turnlights Should be simple. When the GPS tells me to turn left or right on the next intersection by showing an arrow in the lower left corner of the minimap, also activate the corresponding blinker. Would add a lot to the immersion. No need to be a dick towards people, okay? Yes I tried doing it myself, but I couldn't find the way to read the direction of that arrow. Still, there are much more skilled scripters than me on this site, so I think they will be able to do it easily. If they want to, that is. Oh, thank you. Didn't know I could mention other members to attract their attention. I really hope someone makes it real, it would be so awesome. @Claude_Lib I'm thinking about it. Wow, awesome, thank you! i have automatic turn lights but i don't know which mod is causing it You too, thank you. Sorry to bother you, but did you look into it? @Claude_Lib I haven't yet, sorry. Maybe I should ask Eddlm? He did make a similar mod, so he probably knows how to do this. @Claude_Lib If you'd like. @Claude_Lib I looked into this and got it to work with the GPS using GENERATE_DIRECTIONS_TO_COORD. But the GPS and the waypoint route dont always match. Sometimes it shows to turn. But the route shows to keep going to the next intersection and then turn. The arrow in the mini map also is incorrect. So unless there is a different way. I think thats the best you can hope fore. Also it only works if you set a waypoint. If no one else wants to do this and this is acceptable to you i will upload it. - Claude_Lib So I assume it's just not possible to read where the arrow is pointing? Did you do it in CS? I'd like to look into the code, maybe I'll learn something. @Claude_Lib Yes you can. Thats the problem. The arrow is not matching. Here is the code. You can un comment out //UI.ShowSubtitle(directions.ToString()); to see what its returning. 3 = left 4 = right ext. using System; using System.Collections.Generic; using System.Windows.Forms; using GTA; using GTA.Native; using GTA.Math; using Font = GTA.Font; using System.Linq; public class AutoTurnSignals : Script { bool LeftTurnSignalOn = false; bool RightTurnSignalOn = false; int Timer = 0; public AutoTurnSignals() { Tick += OnTick; Timer = (int)Game.GameTime; } public void OnTick(object o, EventArgs e) { unsafe { int directions = -1; float poop = 0; float distance = 0; if (Game.Player.Character.CurrentVehicle != null) { if (Game.IsWaypointActive) { var blip = World.GetActiveBlips().FirstOrDefault(b => b.Type == 4 && b.Sprite == BlipSprite.Waypoint); Function.Call(Hash.GENERATE_DIRECTIONS_TO_COORD, blip.Position.X, blip.Position.Y, blip.Position.Z, 0, &directions, &poop, &distance); //UI.ShowSubtitle(directions.ToString()); if (!Game.Player.Character.IsInVehicle(Game.Player.Character.CurrentVehicle) || Timer < (int)Game.GameTime) { LeftTurnSignalOn = false; RightTurnSignalOn = false; Function.Call<int>(Hash.SET_VEHICLE_INDICATOR_LIGHTS, Game.Player.Character.CurrentVehicle, 1, false); Function.Call<int>(Hash.SET_VEHICLE_INDICATOR_LIGHTS, Game.Player.Character.CurrentVehicle, 0, false); } if (directions == 3) { Timer = (int)Game.GameTime + 2000; Function.Call<int>(Hash.SET_VEHICLE_INDICATOR_LIGHTS, Game.Player.Character.CurrentVehicle, 0, false); if (!LeftTurnSignalOn) { Function.Call<int>(Hash.SET_VEHICLE_INDICATOR_LIGHTS, Game.Player.Character.CurrentVehicle, 1, true); Function.Call<int>(Hash.SET_VEHICLE_INDICATOR_LIGHTS, Game.Player.Character.CurrentVehicle, 0, false); Game.Player.Character.CurrentVehicle.RightIndicatorLightOn = true; LeftTurnSignalOn = true; RightTurnSignalOn = false; } } if (directions == 4) { Timer = (int)Game.GameTime + 2000; Function.Call<int>(Hash.SET_VEHICLE_INDICATOR_LIGHTS, Game.Player.Character.CurrentVehicle, 1, false); if (!RightTurnSignalOn) { Game.Player.Character.CurrentVehicle.LeftIndicatorLightOn = true; Function.Call<int>(Hash.SET_VEHICLE_INDICATOR_LIGHTS, Game.Player.Character.CurrentVehicle, 0, true); Function.Call<int>(Hash.SET_VEHICLE_INDICATOR_LIGHTS, Game.Player.Character.CurrentVehicle, 1, false); RightTurnSignalOn = true; LeftTurnSignalOn = false; } } } if (!Game.IsWaypointActive) { Function.Call<int>(Hash.SET_VEHICLE_INDICATOR_LIGHTS, Game.Player.Character.CurrentVehicle, 1, false); Function.Call<int>(Hash.SET_VEHICLE_INDICATOR_LIGHTS, Game.Player.Character.CurrentVehicle, 0, false); } } } } } Thank you! I will try it out when I get home. The script I coded didn't take into account GPS, so I'm afraid I can't help. Only thing I can think of, that can help, is looking into @ImNotMentaL 's Voice Navigation script and see how it figures out the next turn the player would have to make. NPCs can activate the car turning signals by themselves when they know they have to make a turn, but I don't know how to translate this to the player. - Claude_Lib @aimless' script does exactly what I wanted. Thank you again, man! I modified it a bit, though, to suit my needs. I'll never play the game without it anymore. @Claude_Lib @stillhere@aimless You guys should release this on the main site @Claude_Lib Nice. I never thought to check the distance. And you should release this. @Jitnaught Think you meant to tag aimless, not me @stillhere You're right, sorry about that @Claude_Lib Yes but you made work correctly. I just got you started. So its your mod.
https://forums.gta5-mods.com/topic/9086/script-automatic-turnlights
CC-MAIN-2021-21
refinedweb
820
54.29
Here is an example fiendishly designed to point out what could go wrong with floating point arithmetic, even with high precision. I found the following example by Jean-Michel Muller in John Gustafson’s book End of Error. The task is to evaluate the following function at 15, 16, 17, and 9999. Here e(0) is defined by continuity to be 1. That is, we define e(0) to be the limit of e(x) as x approaches 0. That limit exists, and it equals 1, so we define e(0) to be 1. If you directly implement the functions above in C++, you will get 0 as the output, whether you use single, double, or even quadruple precision as the following code shows. However, the correct answer in each case is 1. #include <iostream> #include <math.h> #include <quadmath.h> using namespace std; template <typename T> T e(T x) { return x == 0. ? 1. : (exp(x) - 1.)/x; } template <typename T> T q(T x) { return fabs(x - sqrt(x*x + 1.)) - 1./(x + sqrt(x*x + 1.)); } template <typename T> T h(T x) { return e( q(x)*q(x) ); } int main() { int x[] = {15, 16, 17, 9999}; for (int i = 0; i < 4; i++) { cout << h( float(x[i]) ) << endl; cout << h( double(x[i]) ) << endl; cout << h(__float128(x[i]) ) << endl; } } A little algebra shows that the function q(x) would return 0 in exact arithmetic, but not in floating point arithmetic. It returns an extremely small but non-zero number, and the numerator of (exp(x) - 1.)/x evaluates to 0. If q(x) returned exactly zero, h(x) would correctly return 1. Interestingly, if q(x) were a little less accurate, returning a little larger value when it should return 0, h would be more accurate, returning a value close to 1. I tried replacing exp(x) - 1 with expm1(x). This made no difference. (More on expm1 here.) Incidentally, bc -l gives the right result, no matter how small you set scale. define ee(x) { if (x == 0) return 1 else return (e(x) - 1)/x } define abs(x) { if (x > 0) return x else return -x } define q(x) { return abs(x - sqrt(x^2 + 1)) - 1/(x + sqrt(x^2 + 1)) } define h(x) { return ee( q(x)^2 ) } Update: See the next post for another example, this time evaluating a polynomial. 12 thoughts on “Floating point oddity” Is exp() the problem? It’s going to take and return a double regardless of how wide of a float you give it and how wide of a float you interpret the result to be. On your system, does using expl() or an equivalent that uses quad-precision instead of extended-precision give the correct result? This post has been posted to Hacker News under the title “Floating Point C vs C++.” The reason is that initially I thought there was a difference between my C and C++ implementations, but that turned out to be an error on my part. After fixing the error, I changed the post title. But the post hit HN while I was editing. Sorry for any confusion. I tried your code on my setup and it produced 0 as you claimed, except that for whatever peculiar reason I got a “1” for the float case when x=9999. Also, when I tried expm1 replacement instead of exp it fixed the problem for all cases. Maybe it is something about your setup? My specific results may be particular to my setup, but the problem gives odd results on a wide variety of platforms according to Gustafson, and Muller before him. Gustafson says that William Kahan, contributor to and critic of the IEEE standard, popularized Muller’s example. Cleaning up the actual equations as you would in real life helps quite a bit. I don’t know the purpose of the post, but it is clear how to fix it. Hmmm. With Julia julia> using Quadmath [ Info: Precompiling Quadmath [be4d8f0f-7fa4-5f49-b795-2f01399ab2dd] julia> e(x) =(exp(x)-1)/x e (generic function with 1 method) julia> q(x)=abs(x – sqrt(x^2 -1)) – 1/(x + sqrt(x^2 + 1)) q (generic function with 1 method) julia> h(x)=e(q(x)^2) h (generic function with 1 method) julia> h(15) 0.9999999940844259 julia> h(16) 0.9999999998809705 julia> h(17) 0.9999999704098268 julia> h(9999) 0.0 julia> x=Float128(9999) 9.99900000000000000000000000000000000e+03 julia> h(x) 1.00000000013028353236076189330504676e+00 Basically, at certain arguments, your functions suffer from a catastrophic loss of precision. I recall worrying about this in grad school computing forward/backward difference numerical derivatives. Generally, when you subtract nearly equal quantities, such as exp(x)-1 near x->0, the whole q(x) function, you should expect that you are not going to have much precision left. This isn’t so much that floating point is “bad”, and arbitrary precision isn’t good either. Its more about understanding how floating point works, and why it really isn’t a 1 to 1 mapping of the reals, rationals, or other categories of numbers. I wrote something like this a long time ago ( ) about a very simple summation. One might point out that the sum I chose in this case was not convergent, and one needs to be especially careful when playing with non-convergent or conditionally convergent series numerically. I explored the same thing later with my Riemann Zeta Function tests ( ). I’m not sure bc is doing what you’re supposing it’s doing: in my case it returns 1, but the ee() function used directly gives an error: e() does not exist. I wonder if a 0 or 1 is coming into play due to error, not due to calculation. @Ed: If the function e() doesn’t exist, you launched bc without the -l flag. You almost always want the -l flag, so it’s annoying that it’s not the default. @Alex: One lesson from the example is that it pays to clean up equations if you can, and that this can be more beneficial than extra precision. Another lesson is that in real applications, you might run into something analogous where you can’t make the problem go away with a little algebra. For whatever it’s worth, I tried the equivalent code in Matlab (for single, double anyway) and I get a slightly different answer (all 0’s on output) than the C++ result I got ( 1 on float, 0 in other cases). Using expm1 still fixed the problem for me, though (all 1’s on output). This reminds me of the bad-old-days of the late ’80’s, trying to fit high-level math into a slow (2 MHz) 8-bit embedded processor, and trying to generate results in real-time. On one project I had a scientist insist that 32-bit float was required for a given algorithm. I had to do days of work to show my hand-crafted fixed-point solution not only had a 10x performance gain, but did so with better precision (less precision loss). Turned out that the floating point precision on his PDP-11 was worse than the IEEE library I had for the 8-bit processor, meaning I was actually working against myself to have my fixed-point approach beat IEEE 32-bit floating point. I should have used his accuracy data for his PDP runs against that my 8-bit fixed-point runs. It’s somewhat surprising that switching to expm1 doesn’t fix this. For a small value of x, the e function (with exp – 1 replaced by expm1) seems like it should give something very close to 1 since expm1(x) = x + x^2/2… is very close to x, and dividing by x doesn’t lose any precision.
https://www.johndcook.com/blog/2019/11/11/floating-point-oddity/
CC-MAIN-2019-51
refinedweb
1,313
70.53
Here's the problem... Tax number for all companies is being changed in Croatia. This means a lot of hassle collecting new tax numbers from your customers, vendors and contact to ensure seamless opereation when it becomes mandatory to use. Specially, tax reporting for December needs to be done using old tax number and you need to start using new in your accounting from 1.1.2010. Nightmare in this holiday time of year you'd like to spend with family and friends. So, I thought, why not using what you already have in Dynamics NAV? RIM's Data migration tools? Style sheet tool? Some logistics first, before I get started. Currently, we have 2 versions of Dynamics NAV supported in Croatia (NAV 4.0 SP3 and NAV 5.0 SP1 with Feature Pack 1). Rapid Implementation Methodology Toolkit (RIM Toolkit), which is now part of Sure Step methodology, is localized and available for both of these versions on Dynamics NAV. From July 2009, RIM Toolkit (part of Sure Step Methodology) is available to all partners, so why not taking advantage of this tool? For Croatian version of Dynamics NAV 4.0, there was a separate release of localized RIM Toolkit (download link). Localized RIM toolkit is available as integral part of latest Croatian version of Dynamics NAV release (download link for NAV 5.0 SP1 FP1). Style Sheet tool is also available for download from this link. I used Style Sheet Tool version 1.1 while preparing this guide. At the moment new tax number regulations were published (OiB), it seemed to me, users will only have to replace current VAT Registration Number with new tax number Tax Authority will supply them with. Apart from updating their own VAT Registration number, users will have to do this for their master data (Customers, Vendors and Contacts) and open documents (orders, invoices and credit memos) as well. However, from conversations I had with partners, most trouble customers will have will be the transition period where they still need to do reporting with old VAT Registration No, while at the same time create new documents with new tax number, that, as per legislation, has clear usage cut-off date - 1.1.2010. Handling VAT Registration No update process out of the system should enable users do their day to day business in with no interruptions, keeping their customer, vendor and contact data in structured format, out of the system, until new tax numbers are collected. When users receive new tax numbers from their customers, vendors and contacts they will update data prepared by RIM toolkit and import it back in the system (on 1.1.2010). RIM toolkit will ensure validation logic is executed over changed data. On the other hand Style Sheet Tool will enable users prepare documents to send to customers, vendors and contacts to collect their new tax numbers (OiB). Business process from customer perspective looks like this: Over the next few weeks, I will post parts 2 and 3 in this series, which describe these four steps. -Ivan Koletic The Best Practices Analyzer for Microsoft Dynamics NAV 2009 is a tool for identifying issues that can prevent you from successfully deploying a three-tier environment of Microsoft Dynamics NAV 2009. Three-tier environment deployments can be challenging because they often require additional domain administration tasks. The Best Practices Analyzer for Microsoft Dynamics NAV 2009 queries various sources and produces reports that can help you diagnose issues with your deployment. The Best Practices Analyzer for Microsoft Dynamics NAV 2009 performs the following verifications: You can find more information about the tool and download it from CustomerSource here: or from PartnerSource here: Multiple When If you utilize some of the warehousing functionality - you have several reasons to look after 2009 SP1! While improved productivity - for customers and partners alike - is one of the main benefits of Microsoft Dynamics NAV 2009, we continue to focus on quality. We strive to make improvements in the product application with every release. Microsoft Dynamics NAV 2009 SP1 is no different. NAV 2009 SP1 provides application enhancements to address customer and partner requests including the correction of up to 170 different issues in Warehousing. Some of these include fixes, redesign or consolidation in the following three areas: Headlines of some of the fixes are added here: -Philippe Jacobsen The feature enhancements documents for Microsoft Dynamics NAV 2009 describe the enhancements to Microsoft Dynamics NAV 2.60 through 4.0 that are included in Microsoft Dynamics NAV 2009. The feature enhancements are categorized by granule ID. This will show the new features added to granules customers have already purchased and aid customers and partners in the upgrade process to Microsoft Dynamics NAV 2009. As a follow-up on my recent webcast (found HERE), here is the general walkthrough of how to create an XMLport and use it for sending data to NAV. First, what we want to do is create our XMLport and make sure it has the elements and values that we want. For the root element, I have set maxOccurs = 1 to avoid any confusion. For the general XMLport, the UseDefaultNamespace and the DefaultNamespace values have been edited as seen below. Other than that, I have no code on my XMLport, but naturally, anything goes that would work on a regular XMLport. Now to the Codeunit: ImportDim(VAR DimImport : XMLport DimImport) Return : Text[30] DimImport.IMPORT; EXIT('Import Run'); So basically we’re telling the XMLport to run an import and we’re returning to the Web Service that we’ve run. All we need to do now is expose the Web Service using Form 810: Remember that the actual name of the codeunit does not have to match that of the service name here. So now we move over to Visual Studio and start working with what we have. The first thing we’ll notice is that the WSDL matches our XMLport. What we see is both the RootDimensions element which consists of multiple Dimension elements. From there, we can see the definition of the Dimension element the fields we’ve chosen to expose. When creating a new project, we will go with a Windows Forms project this time. And from there we will start off by adding a web reference to . The details on how to add a web reference can be found in the Developer and IT Pro Documentation. On my new form, I have created two input boxes for the Code and Name of the dimension and a Create button. And then we have the code on the Create button, along with helpful comments: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace NAV2009SP1WSDemo { using WSDI; public partial class Form1 : Form { //Then we create a List to handle our (possible) multiple dimensions List<Dimension> DimList = new List<Dimension>(); //And then we create a single dimension Dimension Dim = new Dimension(); if (dimInputCode.Text != "" && dimInputName.Text != "") { //We assign the values from our textboxes to the single dimension Dim.DimensionCode = "AREA"; Dim.Code = dimInputCode.Text; Dim.Name = dimInputName.Text; //Then we add the single dimension to our list DimList.Add(Dim); //To get the list of dimensions "attached" to the root element, we use the following RootDim.Dimension = DimList.ToArray(); try { //Then we send to NAV and show our result ResultLabel.Text = NAVImport.ImportDim(ref RootDim); } catch (Exception ex) { //Show a possible exception ResultLabel.Text = ex.ToString(); } } else { //Make sure there are values ResultLabel.Text = "Both values must be filled"; } } } } Our wonderful application is now ready to run and all we have to do is press F5: We have now created our XMLport, exposed it using a codeunit and set data into it from a form based application. Lars Thomsen Microsoft Customer Service and Support (CSS) EMEA The C/AL Application Test Toolset for Microsoft Dynamics NAV 2009 SP1 is now available on PartnerSource. This toolset helps NAV developers to quickly develop and run C/AL-based tests in their primary development environment. The toolset includes sample tests to help you get started with C/AL test development, tools for test case management and execution, and useful test library functions, such as assert and database state restore. These tools build on top of the Test Features released with Microsoft Dynamics NAV 2009 SP1. Download from PartnerSource One of the problems when troubleshooting why a 3-tier setup of NAV 2009 doesn't work is, that the same error - typically this one on the SQL Server: "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'" can be caused by any number of problems between NAV Server, SQL Server and Active Directory settings. One quite common cause of this problem is duplicate SPNs. This post describes the problem with duplicate SPNs, and how to locate and solve it. What is the problem: When the NAV Server and SQL Server are on two different machines, a connection between Role Tailored Client (RTC) and the NAV Server requires Kerberos. Kerberos uses SPNs to locate which Windows account the NAV Server is running under. For this reason, each SPN must point to exactly one Windows account. Once you start setting up and troubleshooting a 3-tier setup it is easy to end up trying new SPNs on new accounts, and forgetting to remove the original SPNs. And you may end up with the same SPN assigned to two different Windows accounts. More about SPNs in this post: What do SPNs actually do - NAV 2009 How to check if you have duplicate SPNs: This is easy if you have Windows 2008 somewhere on the domain. If you do, then from a command prompt, just run this command: setspn -X This command is new in Windows 2008, and was introduced exactly and specifically to help locating this problem. If you do not have Windows 2008 anywhere on the domain, then use the command line tool called "ldifde" from a Windows Server 2000 or 2003. More details and examples about ldifde in this KB article: LDIFDE - Export / Import data from Active Directory - LDIFDE commands For the purpose of finding duplicate SPNs, use ldifde from a command prompt like this: ldifde -f "c:\x\AD.txt" -l ServicePrincipalName This will export values of the ServicePrincipalName-property for all accounts in Active Directory to a text file. Here is an example of the output of this command: Then you must search manually for your SPNs, and see if they appear more than once. In this example, the SPN "DynamicsNAV/NAV-SERVER:7046" is set up for both accounts navservice and SQLDUI, so in this case you would have to remove this SPN from one of the accounts. Lars Lohndorf-Larsen "How
http://blogs.msdn.com/b/nav/archive/2009/11.aspx?PostSortBy=MostRecent&PageIndex=1
CC-MAIN-2014-10
refinedweb
1,794
52.9
Important: Please read the Qt Code of Conduct - [Qt Design Studio] Does QDS support graphical effect “ThresholdMask”? hi, I'm a designer. I have read the document and found that there is a QML type "ThresholdMask" which interests me. (doc link:) But when I try it in Qt Designer Studio, it doesn't work. version: QDS v1.2 community, Qt 5.12 code bellow: import QtQuick 2.0 import QtGraphicalEffects 1.0 Item { id: root default property alias contentStack: stack.children implicitWidth: Math.max(32, stack.implicitWidth) implicitHeight: Math.max(32, stack.implicitHeight) Item { z: -1 id: stack implicitWidth: blend.source.width + blend.source.x implicitHeight: blend.source.height + blend.source.y visible: false } ThresholdMask { id: blend anchors.fill: parent source: root.background maskSource: root.foreground } property Item background property Item foreground property Item foo: Item {} Component.onCompleted: { root.background = stack.children[0] root.foreground = stack.children[1] } } QDS screenshot: Is QDS supports this QML type? Thanks for your help. - BrookCronin last edited by Yeah, it should work (as in it works for me). But i'm running the latest 1.4 release, perhaps try updating to that one? @BrookCronin thank you, Bro! it worked! QDS v1.4 adds more effect. QDS v1.4 QDS v1.2
https://forum.qt.io/topic/111620/qt-design-studio-does-qds-support-graphical-effect-thresholdmask
CC-MAIN-2021-31
refinedweb
207
64.27
Hi all, with the pyPgSQL some values are not returned as basic Python types. For Postgres 'bigint' I get a PgInt8 type. The problem: with these types, some type comparisons (created by PythonGenerator.py) and some assert statements fail because type(PgInt8Type)!=type(0L). Looking around, I found no way to tell the DB-API 2.0 compliant PyPgSQL to return only native types. These are two possible solutions: 1. The assert statements and type(value) comparison should check for not only one type, but a compatible type family. In my PostgresStorage I would override it and place the compatible types into the lists. (IntTypes, LongTypes, FloatTypes,DateTimeTypes, ObjRefTypes). The checks have to be changed in desing/PythonGenerator.py. 2. After retrieving rows from the database, all values are converted. So I need a function to convert values (file SQLObjectStore.py, function fetchObjectsOfClass) insert a hook (convertValues) after fetchall() but before further processing. Any other suggestions? Could Chuck as MiddleKit chief give his opinion on this? Thanx, Erny aerd@... wrote: > Hi all, > > with the pyPgSQL some values are not returned as basic Python types. For Postgres 'bigint' I get a PgInt8 type. > Hi, Its been a very long time, but I was the one who wrote this code. Here is the discussion that I had with Chuck at the time: At 11:57 PM 7/26/2001 -0700, Greg Brauer wrote: -----Original Message----- From: Chuck Esterbrook <ChuckEsterbrook@...> Date: Thu, 26 Jul 2001 23:33:40 -0400 Subject: Re: Think I've got it. > At 07:54 PM 7/26/2001 -0700, Gregory Brauer wrote: > >In otherwords, internally were always storing as Pg types. You had > >mentioned that a PgInt8 would be better than a long, memory wise, > >and had suggested using that as the internal storage mechanism. > >To be consistent then, a boolean would be the same. Do you think > I'm > >on the right track here? > > Basically and this obviously works. But then I'm wondering if this > will > affect the portability of MK code. Like if I switch my database from > Postgres to MySQL to something else, will this approach make it more > likely > for things to break? > > I'm leaning towards sticking with ordinary Python ints and longs for > this > reason. Ok, here's another factor. An ObjRef is hard coded in SQLObjectStore to be a long. So, I can't store references internally as an PGInt8, which is how they come out of the database. So now I'm faced with either a) overriding a major part of SQLObjectStore in PgSQLObjectStore, b) having ObjRefs be converted to Python native types, while Bools and Longs are Pg types, or c) converting all Pg Types to Python types across the board. What are your thoughts? I prefer (c) for bona fide Python values like bools and ints, but an obj ref that is a "long" really isn't about Python, it's about internal MK implementation. Looking at SQLObjectStore, it looks like the hard coding is the assertion in fetchObjRef(). We could change that to: assert type(value) in self.joinedObjRefTypes() def joinedObjRefTypes(self): return (types.LongType,) Then a subclass could override the method to return a tuple with more elements. There are also the funcs objRefJoin() and objRefSplit(), but since they use numerical operators, I don't think there should be interference with PgInt8. So in summary, my thoughts are, - convert all data (bool, int, long, float) to Pythonic data - let "joined" obj ref values be as efficient as they can be, which in this case would be a PgInt8 -Chuck And I'm pretty sure I did what was recommended here, so that is why a PgInt8 remains so... because it is most typically used to describe an obj ref. It's been 6 months since I looked at this code, so I appologize in advance if I'm wrong about something here. Greg
http://sourceforge.net/p/webware/mailman/webware-discuss/thread/20020404200300.OKOJ4004.smtp03.retemail.es@smtp03/
CC-MAIN-2016-07
refinedweb
648
74.29
Beginner Tutorial: Recommender Systems in Python The purpose of this tutorial is not to make you an expert in building recommender system models. Instead, the motive is to get you started by giving you an overview of the type of recommender systems that exist and how you can build one by yo In this tutorial, you will learn how to build a basic model of simple and content-based recommender systems. While these models will be nowhere close to the industry standard in terms of complexity, quality, or accuracy, it will help you to get started with building more complex models that produce even better results. Recommender systems are among the most popular applications of data science today. They are used to predict the "rating" or "preference" that a user would give to an item. Almost every major tech company has applied them in some form. Amazon uses it to suggest products to customers, YouTube uses it to decide which video to play next on autoplay, and Facebook uses it to recommend pages to like and people to follow. What's more, for some companies like Netflix, Amazon Prime, Hulu, and Hotstar, the business model and its success revolves around the potency of their recommendations. Netflix even offered a million dollars in 2009 to anyone who could improve its system by 10%. There are also popular recommender systems for domains like restaurants, movies, and online dating. Recommender systems have also been developed to explore research articles and experts, collaborators, and financial services. YouTube uses the recommendation system at a large scale to suggest you videos based on your history. For example, if you watch a lot of educational videos, it would suggest those types of videos. But what are these recommender systems? Broadly, recommender systems can be classified into 3 types: - Simple recommenders: offer generalized recommendations to every user, based on movie popularity and/or genre. The basic idea behind this system is that movies that are more popular and critically acclaimed will have a higher probability of being liked by the average audience. An example could be IMDB Top 250. - Content-based recommenders: suggest similar items based on a particular item. This system uses item metadata, such as genre, director, description, actors, etc. for movies, to make these recommendations. The general idea behind these recommender systems is that if a person likes a particular item, he or she will also like an item that is similar to it. And to recommend that, it will make use of the user's past item metadata. A good example could be YouTube, where based on your history, it suggests you new videos that you could potentially watch. - Collaborative filtering engines: these systems are widely used, and they try to predict the rating or preference that a user would give an item-based on past ratings and preferences of other users. Collaborative filters do not require item metadata like its content-based counterparts. Simple Recommenders As described in the previous section, simple recommenders are basic systems that recommend the top items based on a certain metric or score. In this section, you will build a simplified clone of IMDB Top 250 Movies using metadata collected from IMDB. The following are the steps involved: Decide on the metric or score to rate movies on. Calculate the score for every movie. Sort the movies based on the score and output the top results. About the Dataset The dataset files contain metadata for all 45,000 movies listed in the Full MovieLens Dataset. The dataset consists of movies released on or before July 2017. This dataset captures feature points like cast, crew, plot keywords, budget, revenue, posters, release dates, languages, production companies, countries, TMDB vote counts, and vote averages. These feature points could be potentially used to train your machine learning models for content and collaborative filtering. This dataset consists of the following files: - movies_metadata.csv: This file contains information on ~45,000 movies featured in the Full MovieLens dataset. Features include posters, backdrops, budget, genre, revenue, release dates, languages, production countries, and companies. - keywords.csv: Contains the movie plot keywords for our MovieLens movies. Available in the form of a stringified JSON Object. - credits.csv: Consists of Cast and Crew Information for all the movies. Available in the form of a stringified JSON Object. - links.csv: This file contains the TMDB and IMDB IDs of all the movies featured in the Full MovieLens dataset. - links_small.csv: Contains the TMDB and IMDB IDs of a small subset of 9,000 movies of the Full Dataset. - ratings_small.csv: The subset of 100,000 ratings from 700 users on 9,000 movies. The Full MovieLens Dataset comprises of 26 million ratings and 750,000 tag applications, from 270,000 users on all the 45,000 movies in this dataset. It can be accessed from the official GroupLens website. Note: The subset dataset used in today's tutorial can be downloaded from here. To load your dataset, you would be using the pandas DataFrame library. pandas library is mainly used for data manipulation and analysis. It represents your data in a row-column format. Pandas library is backed by the NumPy array for the implementation of pandas data objects. pandas offer off the shelf data structures and operations for manipulating numerical tables, time-series, imagery, and natural language processing datasets. Basically, pandas is useful for those datasets which can be easily represented in a tabular fashion. Before you perform any of the above steps, let's load your movies metadata dataset into a pandas DataFrame: # Import Pandas import pandas as pd # Load Movies Metadata metadata = pd.read_csv('movies_metadata.csv', low_memory=False) # Print the first three rows metadata.head(3) 3 rows × 24 columns One of the most basic metrics you can think of is the ranking to decide which top 250 movies are based on their respective ratings. However, using a rating as a metric has a few caveats: For one, it does not take into consideration the popularity of a movie. Therefore, a movie with a rating of 9 from 10 voters will be considered 'better' than a movie with a rating of 8.9 from 10,000 voters. For example, imagine you want to order Chinese food, you have a couple of options, one restaurant has a 5-star rating by only 5 people while the other restaurant has 4.5 ratings by 1000 people. Which restaurant would you prefer? The second one, right? Of course, there could be an exception that the first restaurant opened just a few days ago; hence, fewer people voted for it while, on the contrary, the second restaurant is operational for a year. - On a related note, this metric will also tend to favor movies with a smaller number of voters with skewed and/or extremely high ratings. As the number of voters increases, the rating of a movie regularizes and approaches towards a value that is reflective of the movie's quality and gives the user a much better idea as to which movie he/she should choose. While it is difficult to discern the quality of a movie with extremely few voters, you might have to consider external sources to conclude. Taking these shortcomings into consideration, you must come up with a weighted rating that takes into account the average rating and the number of votes it has accumulated. Such a system will make sure that a movie with a 9 rating from 100,000 voters gets a (far) higher score than a movie with the same rating but a mere few hundred voters. Since you are trying to build a clone of IMDB's Top 250, let's use its weighted rating formula as a metric/score. Mathematically, it is represented as follows: \begin{equation} \text Weighted Rating (\bf WR) = \left({{\bf v} \over {\bf v} + {\bf m}} \cdot R\right) + \left({{\bf m} \over {\bf v} + {\bf m}} \cdot C\right) \end{equation} In the above equation, v is the number of votes for the movie; m is the minimum votes required to be listed in the chart; R is the average rating of the movie; C is the mean vote across the whole report. You already have the values to v (vote_count) and R (vote_average) for each movie in the dataset. It is also possible to directly calculate C from this data. Determining an appropriate value for m is a hyperparameter that you can choose accordingly since there is no right value for m. You can consider it as a preliminary negative filter that will simply remove the movies which have a number of votes less than a certain threshold m. The selectivity of your filter is up to your discretion. In this tutorial, you will use cutoff m as the 90th percentile. In other words, for a movie to be featured in the charts, it must have more votes than at least 90% of the movies on the list. (On the other hand, if you had chosen the 75th percentile, you would have considered the top 25% of the movies in terms of the number of votes garnered. As percentile decreases, the number of movies considered will increase). As a first step, let's calculate the value of C, the mean rating across all movies using the pandas .mean() function: # Calculate mean of vote average column C = metadata['vote_average'].mean() print(C) 5.618207215133889 From the above output, you can observe that the average rating of a movie on IMDB is around 5.6 on a scale of 10. Next, let's calculate the number of votes, m, received by a movie in the 90th percentile. The pandas library makes this task extremely trivial using the .quantile() method of pandas: # Calculate the minimum number of votes required to be in the chart, m m = metadata['vote_count'].quantile(0.90) print(m) 160.0 Since now you have the m you can simply use a greater than equal to condition to filter out movies having greater than equal to 160 vote counts: You can use the .copy() method to ensure that the new q_movies DataFrame created is independent of your original metadata DataFrame. In other words, any changes made to the q_movies DataFrame will not affect the original metadata data frame. # Filter out all qualified movies into a new DataFrame q_movies = metadata.copy().loc[metadata['vote_count'] >= m] q_movies.shape (4555, 24) metadata.shape (45466, 24) From the above output, it is clear that there are around 10% movies with vote count more than 160 and qualify to be on this list. Next and the most important step is to calculate the weighted rating for each qualified movie. To do this, you will: - Define a function, weighted_rating(); - Since you already have calculated mand Cyou will simply pass them as an argument to the function; - Then you will select the vote_count(v) and vote_average(R) column from the q_moviesdata frame; - Finally, you will compute the weighted average and return the result. You will define a new feature score, of which you'll calculate the value by applying this function to your DataFrame of qualified movies: # Function that computes the weighted rating of each movie def weighted_rating(x, m=m, C=C): v = x['vote_count'] R = x['vote_average'] # Calculation based on the IMDB formula return (v/(v+m) * R) + (m/(m+v) * C) # Define a new feature 'score' and calculate its value with `weighted_rating()` q_movies['score'] = q_movies.apply(weighted_rating, axis=1) Finally, let's sort the DataFrame in descending order based on the score feature column and output the title, vote count, vote average, and weighted rating (score) of the top 20 movies. #Sort movies based on score calculated above q_movies = q_movies.sort_values('score', ascending=False) #Print the top 15 movies q_movies[['title', 'vote_count', 'vote_average', 'score']].head(20) Well, from the above output, you can see that the simple recommender did a great job! Since the chart has a lot of movies in common with the IMDB Top 250 chart: for example, your top two movies, "Shawshank Redemption" and "The Godfather", are the same as IMDB and we all know they are indeed amazing movies, in fact, all top 20 movies do deserve to be in that list, isn't it? Content-Based Recommender Plot Description Based Recommender In this section of the tutorial, you will learn how to build a system that recommends movies that are similar to a particular movie. To achieve this, you will compute pairwise cosine similarity scores for all movies based on their plot descriptions and recommend movies based on that similarity score threshold. The plot description is available to you as the overview feature in your metadata dataset. Let's inspect the plots of a few movies: #Print plot overviews of the first 5 movies. metadata['overview'].head() 0 Led by Woody, Andy's toys live happily in his ... 1 When siblings Judy and Peter discover an encha... 2 A family wedding reignites the ancient feud be... 3 Cheated on, mistreated and stepped on, the wom... 4 Just when George Banks has recovered from his ... Name: overview, dtype: object The problem at hand is a Natural Language Processing problem. Hence you need to extract some kind of features from the above text data before you can compute the similarity and/or dissimilarity between them. To put it simply, it is not possible to compute the similarity between any two overviews in their raw forms. To do this, you need to compute the word vectors of each overview or document, as it will be called from now on. As the name suggests, word vectors are vectorized representation of words in a document. The vectors carry a semantic meaning with it. For example, man & king will have vector representations close to each other while man & woman would have representation far from each other. You will compute Term Frequency-Inverse Document Frequency (TF-IDF) vectors for each document. This will give you a matrix where each column represents a word in the overview vocabulary (all the words that appear in at least one document), and each column represents a movie, as before. In its essence, the TF-IDF score is the frequency of a word occurring in a document, down-weighted by the number of documents in which it occurs. This is done to reduce the importance of words that frequently occur in plot overviews and, therefore, their significance in computing the final similarity score. Fortunately, scikit-learn gives you a built-in TfIdfVectorizer class that produces the TF-IDF matrix in a couple of lines. - Import the Tfidf module using scikit-learn; - Remove stop words like 'the', 'an', etc. since they do not give any useful information about the topic; - Replace not-a-number values with a blank string; - Finally, construct the TF-IDF matrix on the data. #Import TfIdfVectorizer from scikit-learn from sklearn.feature_extraction.text import TfidfVectorizer #Define a TF-IDF Vectorizer Object. Remove all english stop words such as 'the', 'a' tfidf = TfidfVectorizer(stop_words='english') #Replace NaN with an empty string metadata['overview'] = metadata['overview'].fillna('') #Construct the required TF-IDF matrix by fitting and transforming the data tfidf_matrix = tfidf.fit_transform(metadata['overview']) #Output the shape of tfidf_matrix tfidf_matrix.shape (45466, 75827) #Array mapping from feature integer indices to feature name. tfidf.get_feature_names()[5000:5010] ['avails', 'avaks', 'avalanche', 'avalanches', 'avallone', 'avalon', 'avant', 'avanthika', 'avanti', 'avaracious'] From the above output, you observe that 75,827 different vocabularies or words in your dataset have 45,000 movies. With this matrix in hand, you can now compute a similarity score. There are several similarity metrics that you can use for this, such as the manhattan, euclidean, the Pearson, and the cosine similarity scores. Again, there is no right answer to which score is the best. Different scores work well in different scenarios, and it is often a good idea to experiment with different metrics and observe the results. You will be using the cosine similarity to calculate a numeric quantity that denotes the similarity between two movies. You use the cosine similarity score since it is independent of magnitude and is relatively easy and fast to calculate (especially when used in conjunction with TF-IDF scores, which will be explained later). Mathematically, it is defined as follows: Since you have used the TF-IDF vectorizer, calculating the dot product between each vector will directly give you the cosine similarity score. Therefore, you will use sklearn's linear_kernel() instead of cosine_similarities() since it is faster. This would return a matrix of shape 45466x45466, which means each movie overview cosine similarity score with every other movie overview. Hence, each movie will be a 1x45466 column vector where each column will be a similarity score with each movie. # Import linear_kernel from sklearn.metrics.pairwise import linear_kernel # Compute the cosine similarity matrix cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix) cosine_sim.shape (45466, 45466) cosine_sim[1] array([0.01504121, 1. , 0.04681953, ..., 0. , 0.02198641, 0.00929411]) You're going to define a function that takes in a movie title as an input and outputs a list of the 10 most similar movies. Firstly, for this, you need a reverse mapping of movie titles and DataFrame indices. In other words, you need a mechanism to identify the index of a movie in your metadata DataFrame, given its title. #Construct a reverse map of indices and movie titles indices = pd.Series(metadata.index, index=metadata['title']).drop_duplicates() indices[:10] title Toy Story 0 Jumanji 1 Grumpier Old Men 2 Waiting to Exhale 3 Father of the Bride Part II 4 Heat 5 Sabrina 6 Tom and Huck 7 Sudden Death 8 GoldenEye 9 dtype: int64 You are now in good shape to define your recommendation function. These are the following steps you'll follow: Get the index of the movie given its title. Get the list of cosine similarity scores for that particular movie with all movies. Convert it into a list of tuples where the first element is its position, and the second is the similarity score. Sort the aforementioned list of tuples based on the similarity scores; that is, the second element. Get the top 10 elements of this list. Ignore the first element as it refers to self (the movie most similar to a particular movie is the movie itself). Return the titles corresponding to the indices of the top elements. # Function that takes in movie title as input and outputs most similar movies def get_recommendations(title, cosine_sim=cosine_sim): # Get the index of the movie that matches the title idx = indices[title] # Get the pairwsie similarity scores of all movies with that movie sim_scores = list(enumerate(cosine_sim[idx])) # Sort the movies based on the similarity scores sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) # Get the scores of the 10 most similar movies sim_scores = sim_scores[1:11] # Get the movie indices movie_indices = [i[0] for i in sim_scores] # Return the top 10 most similar movies return metadata['title'].iloc[movie_indices] get_recommendations('The Dark Knight Rises') 12481 The Dark Knight 150 Batman Forever 1328 Batman Returns 15511 Batman: Under the Red Hood 585 Batman 21194 Batman Unmasked: The Psychology of the Dark Kn... 9230 Batman Beyond: Return of the Joker 18035 Batman: Year One 19792 Batman: The Dark Knight Returns, Part 1 3095 Batman: Mask of the Phantasm Name: title, dtype: object get_recommendations('The Godfather') 1178 The Godfather: Part II 44030 The Godfather Trilogy: 1972-1990 1914 The Godfather: Part III 23126 Blood Ties 11297 Household Saints 34717 Start Liquidation 10821 Election 38030 A Mother Should Be Loved 17729 Short Sharp Shock 26293 Beck 28 - Familjen Name: title, dtype: object You see that, while your system has done a decent job of finding movies with similar plot descriptions, the quality of recommendations is not that great. "The Dark Knight Rises" returns all Batman movies while it is more likely that the people who liked that movie are more inclined to enjoy other Christopher Nolan movies. This is something that cannot be captured by your present system. Credits, Genres, and Keywords Based Recommender The quality of your recommender would be increased with the usage of better metadata and by capturing more of the finer details. That is precisely what you are going to do in this section. You will build a recommender system based on the following metadata: the 3 top actors, the director, related genres, and the movie plot keywords. The keywords, cast, and crew data are not available in your current dataset, so the first step would be to load and merge them into your main DataFrame metadata. # Load keywords and credits credits = pd.read_csv('credits.csv') keywords = pd.read_csv('keywords.csv') # Remove rows with bad IDs. metadata = metadata.drop([19730, 29503, 35587]) # Convert IDs to int. Required for merging keywords['id'] = keywords['id'].astype('int') credits['id'] = credits['id'].astype('int') metadata['id'] = metadata['id'].astype('int') # Merge keywords and credits into your main metadata dataframe metadata = metadata.merge(credits, on='id') metadata = metadata.merge(keywords, on='id') # Print the first two movies of your newly merged metadata metadata.head(2) 2 rows × 27 columns From your new features, cast, crew, and keywords, you need to extract the three most important actors, the director and the keywords associated with that movie. But first things first, your data is present in the form of "stringified" lists. You need to convert them into a way that is usable for you. # Parse the stringified features into their corresponding python objects from ast import literal_eval features = ['cast', 'crew', 'keywords', 'genres'] for feature in features: metadata[feature] = metadata[feature].apply(literal_eval) Next, you write functions that will help you to extract the required information from each feature. First, you'll import the NumPy package to get access to its NaN constant. Next, you can use it to write the get_director() function: # Import Numpy import numpy as np Get the director's name from the crew feature. If the director is not listed, return NaN def get_director(x): for i in x: if i['job'] == 'Director': return i['name'] return np.nan Next, you will write a function that will return the top 3 elements or the entire list, whichever is more. Here the list refers to the cast, keywords, and genres. def get_list(x): if isinstance(x, list): names = [i['name'] for i in x] #Check if more than 3 elements exist. If yes, return only first three. If no, return entire list. if len(names) > 3: names = names[:3] return names #Return empty list in case of missing/malformed data return [] # Define new director, cast, genres and keywords features that are in a suitable form. metadata['director'] = metadata['crew'].apply(get_director) features = ['cast', 'keywords', 'genres'] for feature in features: metadata[feature] = metadata[feature].apply(get_list) # Print the new features of the first 3 films metadata[['title', 'cast', 'director', 'keywords', 'genres']].head(3) The next step would be to convert the names and keyword instances into lowercase and strip all the spaces between them. Removing the spaces between words is an important preprocessing step. It is done so that your vectorizer doesn't count the Johnny of "Johnny Depp" and "Johnny Galecki" as the same. After this processing step, the aforementioned actors will be represented as "johnnydepp" and "johnnygalecki" and will be distinct to your vectorizer. Another good example where the model might output the same vector representation is "bread jam" and "traffic jam". Hence, it is better to strip off any space that is present. The below function will exactly do that for you: # Function to convert all strings to lower case and strip names of spaces def clean_data(x): if isinstance(x, list): return [str.lower(i.replace(" ", "")) for i in x] else: #Check if director exists. If not, return empty string if isinstance(x, str): return str.lower(x.replace(" ", "")) else: return '' # Apply clean_data function to your features. features = ['cast', 'keywords', 'director', 'genres'] for feature in features: metadata[feature] = metadata[feature].apply(clean_data) You are now in a position to create your "metadata soup", which is a string that contains all the metadata that you want to feed to your vectorizer (namely actors, director and keywords). The create_soup function will simply join all the required columns by a space. This is the final preprocessing step, and the output of this function will be fed into the word vector model. def create_soup(x): return ' '.join(x['keywords']) + ' ' + ' '.join(x['cast']) + ' ' + x['director'] + ' ' + ' '.join(x['genres']) # Create a new soup feature metadata['soup'] = metadata.apply(create_soup, axis=1) metadata[['soup']].head(2) The next steps are the same as what you did with your plot description based recommender. One key difference is that you use the CountVectorizer() instead of TF-IDF. This is because you do not want to down-weight the actor/director's presence if he or she has acted or directed in relatively more movies. It doesn't make much intuitive sense to down-weight them in this context. The major difference between CountVectorizer() and TF-IDF is the inverse document frequency (IDF) component which is present in later and not in the former. # Import CountVectorizer and create the count matrix from sklearn.feature_extraction.text import CountVectorizer count = CountVectorizer(stop_words='english') count_matrix = count.fit_transform(metadata['soup']) count_matrix.shape (46628, 73881) From the above output, you can see that there are 73,881 vocabularies in the metadata that you fed to it. Next, you will use the cosine_similarity to measure the distance between the embeddings. # Compute the Cosine Similarity matrix based on the count_matrix from sklearn.metrics.pairwise import cosine_similarity cosine_sim2 = cosine_similarity(count_matrix, count_matrix) # Reset index of your main DataFrame and construct reverse mapping as before metadata = metadata.reset_index() indices = pd.Series(metadata.index, index=metadata['title']) You can now reuse your get_recommendations() function by passing in the new cosine_sim2 matrix as your second argument. get_recommendations('The Dark Knight Rises', cosine_sim2) 12589 The Dark Knight 10210 Batman Begins 9311 Shiner 9874 Amongst Friends 7772 Mitchell 516 Romeo Is Bleeding 11463 The Prestige 24090 Quicksand 25038 Deadfall 41063 Sara Name: title, dtype: object get_recommendations('The Godfather', cosine_sim2) 1934 The Godfather: Part III 1199 The Godfather: Part II 15609 The Rain People 18940 Last Exit 34488 Rege 35802 Manuscripts Don't Burn 35803 Manuscripts Don't Burn 8001 The Night of the Following Day 18261 The Son of No One 28683 In the Name of the Law Name: title, dtype: object Great! You see that your recommender has been successful in capturing more information due to more metadata and has given you better recommendations. There are, of course, numerous ways of experimenting with this system to improve recommendations. Some suggestions: Introduce a popularity filter: this recommender would take the 30 most similar movies, calculate the weighted ratings (using the IMDB formula from above), sort movies based on this rating, and return the top 10 movies. Other crew members: other crew member names, such as screenwriters and producers, could also be included. The increasing weight of the director: to give more weight to the director, he or she could be mentioned multiple times in the soup to increase the similarity scores of movies with the same director. Collaborative Filtering with Python In this tutorial, you have learned how to build your very own Simple and Content-Based Movie Recommender Systems. There is also another extremely popular type of recommender known as collaborative filters. Collaborative filters can further be classified into two types: User-based Filtering: these systems recommend products to a user that similar users have liked. For example, let's say Alice and Bob have a similar interest in books (that is, they largely like and dislike the same books). Now, let's say a new book has been launched into the market, and Alice has read and loved it. It is, therefore, highly likely that Bob will like it too, and therefore, the system recommends this book to Bob. Item-based Filtering: these systems are extremely similar to the content recommendation engine that you built. These systems identify similar items based on how people have rated it in the past. For example, if Alice, Bob, and Eve have given 5 stars to The Lord of the Rings and The Hobbit, the system identifies the items as similar. Therefore, if someone buys The Lord of the Rings, the system also recommends The Hobbit to him or her. An example of collaborative filtering based on a rating system: You will not be building these systems in this tutorial, but you are already familiar with most of the ideas required to do so. A good place to start with collaborative filters is by examining the MovieLens dataset, which can be found here. Conclusion Congratulations on finishing this tutorial! You have successfully gone through our tutorial that taught you all about recommender systems in Python. You learned how to build simple and content-based recommenders. One good exercise for you all would be to implement collaborative filtering in Python using the subset of MovieLens dataset that you used to build simple and content-based recommenders. If you are just getting started in Python and would like to learn more, take DataCamp's Introduction to Data Science in Python course.
https://www.datacamp.com/community/tutorials/recommender-systems-python
CC-MAIN-2022-05
refinedweb
4,864
61.16
.NET contains an entire XML Framework. This Framework comprises a number of classes that make it easy for you to implement and work with XML in your applications. Because .NET is so reliant on XML, Microsoft spent a great deal of time making these classes robust, easy to use, and very performant (i.e., it performs well in terms of CPU and execution time). As I have said before, these classes all follow the W3C specification for XML, and they are an evolution to MSXML, which you may have already used. Much of .NET actually uses XML for its native data representation. Examples of this can be seen in ASP.NET and Web Services (which rely on SOAP), and you can even see XML in the automatic source-code comments that are added when you create classes with Visual Studio .NET. XML is also an integral part of ADO.NET and SQL Server 2000. The .NET XML classes enable you to easily work with relational data and hierarchical data. The classes provide a unified programming model. NOTE: The .NET XML Framework can be found in several namespaces. The core types are contained in System.Xml. The XPath and Xslt types can be found in System.Xml.XPath and System.Xml.Xsl. Another important namespace is System.Xml.Serialization. To use these classes, you must import the correct namespaces through the using directive, as follows: using System.Xml; using System.Xml.Xpath; using System.Xml.Xsl; using System.Xml.Serialization; At the core of the .NET Framework XML classes are two abstract classes: XmlReader and XmlWriter. XmlReader provides a fast, forward-only, read-only cursor for processing an XML document stream. XmlWriter provides an interface for producing XML document streams that conform to the W3C's XML recommendations. Applications that need to process XML documents use XmlReader, whereas applications that want to create XML documents use XmlWriter. Both classes imply a streaming model that doesn't require an expensive in-memory cache. This makes them both attractive alternatives to the classic DOM approach. The XmlReader and XmlWriter classes are abstract base classes. They define functionality that all derived classes must support. At present, three implementations of XmlReader are included in the .NET Framework: XmlTextReader, XmlNodeReader, and XslReader. The implementation of XmlWriter is in the .NET Framework. It is XmlTextWriter. The XmlTextReader and XmlTextWriter classes support reading from and writing to text-based streams. XmlNodeReader is used for in-memory DOM trees. One of the biggest advantages of this design is that custom readers and writers can be developed to extend the built-in functionality. I expect to see many of these extended classes appear on the Internet and in newsgroups as developers extend the classes to meet their needs and share the classes with others.
https://flylib.com/books/en/2.627.1.69/1/
CC-MAIN-2019-43
refinedweb
464
59.8
Claire wrote: >hi, >i use vars() or dir() to get variables. I use them in a def block, so >i get variables of that block. How can i get variables from the >namespace __main__ ? >I use python in interactive mode and want to have a function to get a >dictionnary for python types (int, ...) and another for my types (my >classes). this function will be in my pythonstartup file. > >If i use python in interactive mode, is there a main module defined ? >i don't know how to use namespace __main__ to get information on this >"global namespace" like i can do with math or another module > > There is also a globals() function which operates in a manner parallel to vars(). Note that vars(), without an argument, is equivalent to locals(). Also beware that, while these functions will return a dictionary containing the current global/local variables, modifying that dictionary may not modify actual variables. (In general, you're best off using them as read-only.) Jeff Shannon Technician/Programmer Credit International
https://mail.python.org/pipermail/python-list/2004-August/285775.html
CC-MAIN-2019-30
refinedweb
172
65.83
I received this homework assignment, it basically tells me to read GPAs of male and female students from a text file and then output averages to another text file. This is an idea of what the file looks like that is read: f 3.40 f 4.00 m 3.56 m 3.80 f 2.30 f 3.95 My question is how do I read whether the character before the gpa is "m" or "f"? This is what I have so far: Code:import java.io.*; import java.util.*; public class HW2 { public static void main (String[] args) throws FileNotFoundException { double mGPA, fGPA; String m,f; double mGPAsum = 0; double fGPAsum = 0; int numberMales = 0; int numberFemales = 0; Scanner inFile=new Scanner(new FileReader("input.txt")); PrintWriter outFile = new PrintWriter("outputGPA.txt"); while (inFile.hasNext()) { if (inFile.equals("f")) { double gpa = inFile.nextDouble(); fGPAsum += gpa; numberFemales++; } if (inFile.equals("m")) { double gpa = inFile.nextDouble(); mGPAsum += gpa; numberMales++; } } outFile.println("Sum female GPA = " + fGPAsum); outFile.println("Sum male GPA = " + mGPAsum); outFile.println("Female count = " + numberFemales); outFile.println("Male count = " + numberMales); fGPA = fGPAsum / numberFemales; mGPA = mGPAsum / numberMales; outFile.println("Average female GPA = " + fGPA); outFile.println("Average male GPA = " + mGPA); inFile.close(); outFile.close(); } } And this is what it's saying: 2 warnings found: Warning: The local variable m is never read Warning: The local variable f is never read
http://forums.devshed.com/java-help-9/hw-read-string-text-file-931508.html
CC-MAIN-2017-34
refinedweb
229
54.9
org.apache.commons.pipeline.StageDriver.State; 021 022 /** 023 * This exception class is used to store detailed information about 024 * a failure in the processing step of a stage including the failing data, 025 * the driver state at the time of failure, and any exceptions encountered. 026 */ 027 public class ProcessingException extends StageException { 028 private final Object data; 029 private final State driverState; 030 031 /** 032 * Creates a new instance of ProcessingException 033 * 034 * @param data The object which was not able to be processed. 035 * @param throwable The exception that occurred. 036 */ 037 public ProcessingException(Stage stage, Throwable cause, Object data, State driverState) { 038 super(stage, cause); 039 this.data = data; 040 this.driverState = driverState; 041 } 042 043 /** 044 * Returns the object that was being processed at the time of failure. 045 * @return The object which was not able to be processed. 046 */ 047 public Object getData(){ 048 return this.data; 049 } 050 051 /** 052 * Returns the saved driver state at the time of processing failure. 053 * @return the driver state at the time of processing failure. 054 */ 055 public State getDriverState() { 056 return this.driverState; 057 } 058 }
http://commons.apache.org/sandbox/pipeline/apidocs/src-html/org/apache/commons/pipeline/ProcessingException.html#line.27
crawl-003
refinedweb
189
56.45
28 November 2011 16:56 [Source: ICIS news] LONDON (ICIS)--Abu Dhabi’s IPIC will sell back its 70% stake in chemical engineering firm Ferrostaal for €350m ($467m) to Germany-based industrial firm MAN as the two groups agreed to settle a long-running dispute, they said on Monday. At the same time, MAN plans to transfer all of Ferrostaal to MPC Group, a Hamburg-based investment and commodities firm. MAN expect to received up to €160m from MPC for Ferrostaal. IPIC, which owns ?xml:namespace> However, IPIC subsequently sought to back out of the deal because of a corruption scandal at Ferrostaal that saw two of the company’s managers charged with alleged bribery. The matter pre-dated IPIC’s acquisition of the stake. “This settlement is the outcome of very good cooperation between both shareholders, and enables IPIC and MAN to finally put their differences aside,” said IPIC managing director Khadem Al Qubaisi. MAN's settlement with IPIC and the planned transfert of Ferrostaal to MPC are both subject to regulatory approvals. Essen-based Ferrostaal builds chemical, fertilizer and other industrial
http://www.icis.com/Articles/2011/11/28/9512170/ipic-returns-70-stake-in-chem-engineer-ferrostaal-to-man.html
CC-MAIN-2014-10
refinedweb
183
52.19
Ionic Framework has been around for a few years now and has completely changed the way people develop hybrid mobile applications. With Angular out and Ionic 2 nearing stable release, the Ionic 1 and AngularJS predecessor will be a thing of the past and forgotten. What if you’ve gone all in with the first version of Ionic Framework, how do you convert to the latest and greatest? We’re going to see how to take a simple Ionic Framework application and convert it to Ionic 2. While there will be similarities, the process is manual, but better in the long run. To make this migration as easy as possible, we’re going to first develop a fresh Ionic Framework 1 application. After we have a fully functional Ionic 1 application, we’re going to create an Ionic 2 application from it. While the code will be different, the end result will be the same. The application we build for both Ionic 1 and Ionic 2 will be a simple todo list type application. It will have two different screens and store data in HTML5 local storage. The goal here isn’t to build something extravagant, but instead show the conversion process. Note that before going further, you need to have the Ionic 2 CLI installed. The original CLI will not create Ionic 2 applications. To create a fresh Ionic Framework project, execute the following from your Command Prompt (Windows) or Terminal (Mac and Linux): ionic start Ionic1Project blank --v1 cd Ionic1Project ionic platform add ios ionic platform add android Notice that we’re using the --v1 tag to specify an Ionic Framework 1 project. Also notice that we’re adding the iOS platform. If you’re not using a Mac with Xcode installed, you cannot build for the iOS platform. Now we can worry about developing the application, but before we start writing code, we need to create a few files and directories. Create the following: mkdir www/pages touch www/pages/list.html touch www/pages/create.html If your Command Prompt or Terminal does not have the mkdir or touch commands, go ahead and create the above manually. Each of the two pages will be in the navigation stack via the AngularJS UI-Router. Before we write the UI markup in the HTML files, let’s worry about the AngularJS logic. Open the project’s www/js/app.js file and include the following:(); } }); }) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state("list", { url: "/list", templateUrl: "pages/list.html", controller: "ListController", cache: false }) .state("create", { url: "/create", templateUrl: "pages/create.html", controller: "CreateController" }); $urlRouterProvider.otherwise("/list"); }) .controller("ListController", function($scope, $state) { $scope.people = localStorage.getItem("people") ? JSON.parse(localStorage.getItem("people")) : []; $scope.create = function() { $state.go("create"); }; }) "); } }; }); There is a lot of code above, so we’re going to break it down to understand what is happening. We need a firm understanding to make the migration a success. The first thing you’ll notice that isn’t part of the default Ionic 1 template is the .config method: .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state("list", { url: "/list", templateUrl: "pages/list.html", controller: "ListController", cache: false }) .state("create", { url: "/create", templateUrl: "pages/create.html", controller: "CreateController" }); $urlRouterProvider.otherwise("/list"); }) This is where we define all the possible routes for navigation in the application. We are defining two different routes, each of which having an HTML UI file and its own controller for page logic. The default page will be the list page. The list page has its own controller called ListController: .controller("ListController", function($scope, $state) { $scope.people = localStorage.getItem("people") ? JSON.parse(localStorage.getItem("people")) : []; $scope.create = function() { $state.go("create"); }; }) We are injecting $scope and $state components in this controller so we can bind data to the UI and navigate to different routes. When the controller loads data will be read from local storage. If the data does not exist, the people variable will be initialized as an empty array. When the create method is called, the next screen will be navigated to. That brings us to the CreateController which is part of the next screen: "); } }; }); Like with the previous controller we are loading the saved data. We are defining a person object that will be bound to the UI and we are defining a save method. When the save method is called we first make sure that the firstname and lastname properties of the person object are not undefined or blank. If not, push the data into the array and serialize it to be stored again in local storage. After saving the data, navigate to the previous component. This brings us to the HTML that goes with the logic code. Open the project’s www/pages/list.html file and include the following markup: <ion-view <ion-nav-buttons <button class="button button-clear" ng- <i class="icon ion-plus"></i> </button> </ion-nav-buttons> <ion-content> <ion-list> <ion-item {{person.firstname}} {{person.lastname}} </ion-item> </ion-list> </ion-content> </ion-view> In the list page we have a single button in the navigation bar. When the button is pressed, the create method from the ListController is executed. In the core content we have a list of data. The list is populated by looping through the people array and printing out the data to the screen. In the www/pages/create.html file, we have the following markup: <ion-view <ion-nav-buttons <button class="button button-clear" ng- <i class="icon ion-checkmark"></i> </button> </ion-nav-buttons> <ion-content> <ion-list> <ion-item <span class="input-label">First Name</span> <input type="text" ng- </ion-item> <ion-item <span class="input-label">Last Name</span> <input type="text" ng- </ion-item> </ion-list> </ion-content> </ion-view> Like with the previous page we have a single button in the navigation bar. When pressed the save method will be called. In the core content we have another list, but this time the list has two form elements bound by properties in the person object through the ng-model tags. Finally we need to make some changes to the project’s www/index.html file. Open it and include-nav-bar</ion-nav-bar> <ion-nav-view></ion-nav-view> </ion-pane> </body> </html> Really we only changed what is in the <ion-pane> tags. By creating an <ion-nav-bar> we can set the title and navigation buttons from each of the pages. Each of the pages will be routed through the <ion-nav-view> tags. At this point you should have a function Ionic Framework 1 application. It can be tested by executing the following from the Command Prompt or Terminal: ionic run [platform] Of course remember to swap out [platform] with the correct platform. If you’d like to save yourself some time, you can download the full project listed above, here. Running the downloaded project will require you to restore the state first which involved downloading the dependencies, platforms, and plugins. With the base of our project created, it is now time to convert it to Ionic 2. To make things easier to understand, we’ll create a fresh Ionic 2 project and I’ll point out the changes as we go along. From the Command Prompt (Windows) or Terminal (Linux and Mac), execute the following: ionic start Ionic2Project blank --v2 cd Ionic2Project ionic platform add ios ionic platform add android Notice the --v2 tag in the above. This means we are creating an Ionic 2 project that uses Angular and TypeScript rather than AngularJS. Just like with the previous application, we are adding the iOS build platform, but you won’t be able to build unless you’re using a Mac. The base template comes with a default page called HomePage, but we are not going to use it. Create the following directories and files: mkdir app/pages/list mkdir app/pages/create touch app/pages/list/list.html touch app/pages/list/list.ts touch app/pages/list/list.scss touch app/pages/create/create.html touch app/pages/create/create.ts touch app/pages/create/create.scss If you don’t have the mkdir and touch commands, create them manually. Want to save yourself some major time? The Ionic 2 CLI has some convenience features. Run the following instead of all the commands listed above: ionic g page list ionic g page create The above uses the Ionic 2 generator functions. Those commands or similar should be used when creating any new files in the project. Things are a bit different in Ionic 2. While we didn’t have to mash all controllers, routes, etc., into the AngularJS www/js/app.js file, it wouldn’t have made too much of a difference. It still would have looked messy. With Ionic 2, each page has its own HTML and TypeScript file. This keeps the code incredibly clean. Starting with the default page, being our list page. Open the project’s src/pages/list/list.ts file and include the following code: import {Component} from '@angular/core'; import {NavController} from 'ionic-angular'; import {CreatePage} from '../create/create'; @Component({ templateUrl: 'list.html' }) export class ListPage { public people: Array<Object>; public constructor(public navCtrl: NavController) { } public ionViewDidEnter() { this.people = localStorage.getItem("people") ? JSON.parse(localStorage.getItem("people")) : []; } public create() { this.navCtrl.push(CreatePage); } } You can already tell TypeScript and Angular is different from AngularJS. Don’t let it scare you away though. We start things off by including essential Angular and Ionic 2 component dependencies. We also include the page for creating data which we’ve yet to design. In the @Component block we are defining which HTML file should pair with this TypeScript file. The real magic happens in the ListPage class though. In Ionic Framework 1, anything that was part of the $scope was accessible from the UI. In the case of Ionic 2, anything that is defined as public is accessible from the UI. This means that our array of objects called people and all methods in this file are accessible. The constructor method is where we do all our dependency injections, similarly how we defined things like $scope and $state in AngularJS. It is also where we can initialize variables. In Ionic Framework 1 we were able to navigate using $state, but in Ionic 2 we navigate using the NavController component. While it is fine to initialize things in the constructor method, it is frowned upon to load data in it. This is why we make use of the reserved ionViewDidEnter method that gets triggered every time the page is navigated to. We also need to use this because the constructor method does not trigger when navigating backwards in the stack. Finally we have the create method where we push the next page into the navigation stack. Before we look at that next page, let’s look at the HTML that goes with this TypeScript file. Open the project’s src/pages/list/list.html file and include the following markup: <ion-header> <ion-navbar> <ion-title> Ionic 2 List </ion-title> <ion-buttons end> <button ion-button icon-only (click)="create()"> <ion-icon</ion-icon> </button> </ion-buttons> </ion-navbar> </ion-header> <ion-content padding> <ion-list> <ion-item * {{person.firstname}} {{person.lastname}} </ion-item> </ion-list> </ion-content> Like with the previous application we create a navigation bar with a title and a button. The UI components are slightly different in Ionic 2 than they were in Ionic 1. In the core content we again have a list where we loop through each of the items in the people array and present them on the screen. There are differences though. Instead of using the AngularJS ng-click tag, we are now using the Angular (click) tag. Not a big deal here. Instead of using the AngularJS ng-repeat to loop through items we are using the Angular *ngFor tag. Overall, the differences in the markup are not too different. This brings us to the page for creating data. Open the project’s src/pages/create/create.ts file and include the following code: import {Component} from '@angular/core'; import {NavController} from 'ionic-angular'; @Component({ templateUrl: 'create.html' }) export class CreatePage { private people: Array<Object>; public firstname: string; public lastname: string; public constructor(public navCtrl: NavController) { } public ionViewDidEnter() { this.people = localStorage.getItem("people") ? JSON.parse(localStorage.getItem("people")) : []; } public save() { if(this.firstname && this.lastname) { this.people.push({ firstname: this.firstname, lastname: this.lastname }); localStorage.setItem("people", JSON.stringify(this.people)); this.navCtrl.pop(); } } } Like with the previous page we are importing the essentials and defining an HTML page in the @Component block. In the CreatePage class we have a few private and public variables. Since we never need to display the people array in the UI of this page, it can be private. The other two variables will be bound to a form in the UI. In the constructor method we are injecting the NavController for navigation and loading our data from local storage in the reserved onPageDidEnter method. This is nothing new to us so far. In the save method we first make sure the two public variables are defined and not empty. If this is true, push them into our people array so we can serialize it and save it to local storage. When the save is complete, use the navigation controller to pop backwards in the navigation stack. This is essentially saying, go to the previous page. Time to work on the HTML markup that goes with this TypeScript file. Open the project’s src/pages/create/create.html file and include the following markup: <ion-header> <ion-navbar> <ion-title> Ionic 2 Create </ion-title> <ion-buttons end> <button ion-button icon-only (click)="save()"> <ion-icon</ion-icon> </button> </ion-buttons> </ion-navbar> </ion-header> <ion-content padding> <ion-list> <ion-item> <ion-label stacked>First Name</ion-label> <ion-input</ion-input> </ion-item> <ion-item> <ion-label stacked>Last Name</ion-label> <ion-input</ion-input> </ion-item> </ion-list> </ion-content> Again we have a navigation bar with a title and a button. When the button is pressed it will call the save method that was listed as public. In the core content we have another list, but this time with input fields in it. Remember in AngularJS we used the ng-model tags to bind data to the logic file? We can use the same, they are just called [(ngModel)] instead. We’re not in the clear yet. We’re no longer using the default HomePage so we have to configure the new default page. Open the project’s src/app/app.component.ts file and make it look like the following: import { Component } from '@angular/core'; import { Platform } from 'ionic-angular'; import { StatusBar, Splashscreen } from 'ionic-native'; import { ListPage } from '../pages/list/list'; @Component({ templateUrl: 'app.html' }) export class MyApp { rootPage = ListPage; constructor(platform: Platform) { platform.ready().then(() => { StatusBar.styleDefault(); Splashscreen.hide(); }); } } Notice we’ve just swapped out HomePage with our ListPage class. Being that this is a multiple page application, we also need to define the possible pages in Angular’s @NgModule block. Open the project’s src/app/app.module.ts file and include the following: import { NgModule, ErrorHandler } from '@angular/core'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { ListPage } from '../pages/list/list'; import { CreatePage } from '../pages/create/create'; @NgModule({ declarations: [ MyApp, ListPage, CreatePage ], imports: [ IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, ListPage, CreatePage ], providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}] }) export class AppModule {} Notice that both pages were imported and added to the declarations and entryComponents arrays of the @NgModule block. Now we’re able to navigate between them. When it comes to running the project, it is exactly the same as with Ionic Framework 1. Using the Terminal or Command Prompt, execute the following: ionic run [platform] Just remember to swap out [platform] with the platform you want to run for. If you want to download this project and run it, you can download the source code here. Again, running the downloaded project will require you to restore the state which involves restoring the platforms, plugins, and project dependencies that were downloaded with NPM. In this example we took a basic Ionic Framework 1 project that used AngularJS and converted it to an Ionic 2 project that used Angular and TypeScript. While much of the logic was the same, TypeScript does have a significantly different structure than AnguarJS. It may seem difficult at first, but the end result will be a much more maintainable project. If you downloaded the source code to these projects, enjoy it, but please do not share it. I put a lot of time into coming up with the source and this tutorial and wouldn’t want my credit to be lost.
https://www.thepolyglotdeveloper.com/2016/08/converting-ionic-framework-1-android-ios-app-ionic-2/
CC-MAIN-2022-40
refinedweb
2,819
57.37
Changelog¶ 4.2.0 (2021-11-18)¶ Field groups in forms. There is a new string groupmember on Fieldthat is used to group, a groupnamespace on Formyou can use to set attrs, tag, etc. Global styling for form groups is done via the FieldGroupclass. The bootstrap style has been updated to support this feature out of the box. Validation could be bypassed for forms if they have been saved via form.refine_done(). This became the default behavior for .as_view()in iommi 4.1 so that release is broken. 4.1.0 (2021-11-15)¶ as_view()calls refine_done, giving you a nice little performance win for free Introduce @iommi_renderview decorator. Use this to get correct behavior when using transactions by default in views. The iommi middleware will now produce an error if you try to use it incorrectly. Re-initializable select2 enhancement. If you dynamically modify with javascript you can call iommi_init_all_select2to re-initialize iommi select2 components Break out the select2 enhancement from the base style into a separate select2_enhanced_formsstyle, and added it to all the built in styles. If you have a custom style that extended baseyou must now also add select2_enhanced_formsto that style to get the same behavior as before. should_ignore_frame() is more robust against acrobatic frames. This is a rather obscure bug that won’t affect normal iommi usage. 4.0.0 (2021-11-01)¶ Dropped support for __in names of declared columns/fields/filters (deprecated since 3.2.0) Big internal refactoring. You should see some performance improvements accross the board. 3.4.0 (2021-10-22)¶ Ability to customize the Celland Cellsclasses used by Tablerendering Improved ability to customize Table.tbody. You can now add html after or before the rows from the table itself Template-based rendering should get iommi_evaluate_parameters as context. This was the case in some cases but not all, most notably when rendering a Fragment. 3.3.0 (2021-10-20)¶ Added snakeviz profiling (use it by passing _iommi_prof=snakeas a url parameter) Fixed stack traces in SQL tracing Fixed jump to code for several scenarios German translation fixes and updates Improved error message for invalid admin config write_nested_form_to_instancenow takes keyword arguments 3.2.2 (2021-10-01)¶ Fix bug causing any endpoint invocation of table fields to force a bind of the paginator (Which should be lazy) 3.2.1 (2021-09-24)¶ Fix enforcement on required=Trueon Field.multi_choiceand others where value is a list. 3.2.0 (2021-08-23)¶ Names with underscore are deprecated and will be removed in the next major version. This means you can no longer write this: class MyTable(Table): foo__bar = Column() You must now instead write: class MyTable(Table): some_name = Column(attr='foo__bar') Using foo__bar had some weird consequences like you not being able to later target that name without getting ambiguities in what __ meant. 3.1.1 (2021-06-18)¶ Expand ajax reload on filter change of tables to also include the bulk form. If not done, the bulk options are not in sync with the filtering. Remove reference to non-existant errors.htmlin bootstrap style Make Table.visible_rowsnon-lazy and not a property Table.rowsis no longer a property 3.1.0 (2021-06-09)¶ Form: Evaluate parameters now contain instance Use the same redirect logic for delete as create/edit. This means you can now use extra__redirectand extra__redirect_tofor delete too When stopping the live editing, a full runserver restart is now triggered so you get the new code you just edited 3.0.0 (2021-05-24)¶ Styles have a new sub_stylesparameter. This change greatly simplifies how you set up a custom style for your project if you want to customize the query form. IOMMI_DEFAULT_STYLEcan now be a Styleobject Breaking change: The horizontal styles are removed and replaced with the substyle feature. If you use for example 'bootstrap_horizontal', you need to replace it with 'horizontal'. Mixed case filter fields didn’t work Respect browsers preferred dark/light mode for profiler and sql tracer 2.8.12 (2021-05-18)¶ Major bug: tables based on querysets would implicitly use the django result cache. This resulted in the contents of the table not changing until after process restart 2.8.11 (2021-05-07)¶ Fragmentshould have @with_meta Fixed nesting tables inside forms. This would previously crash with a strange error message. Avoid infinite loop in sort_after on too large indicies 2.8.10 (2021-04-28)¶ Read defaults from model for initial of fields Increased log level of SQL logging from 11 to 21 (DEBUG+1 -> INFO+1) Added null factory for JSONField Fixed live editing code to use the same logic as ‘jump to code’ to find the code Fixed one case where live edit broke Prettier debug menu for live editing Prettier query help text (thanks new contributor flying_sausages!) 2.8.9 (2021-03-08)¶ Fixed bad html escape in SQL trace magnitude graph (this is not a security problem, as it’s a developer tool with very restricted access) Renamed freetext to freetext_search. It was too easy to collide with a user defined model with a field called freetext 2.8.8 (2021-02-23)¶ Automatically generating a Query from a model with a foreign key was broken in cases where the name field wasn’t the same as name field of the parent model 2.8.7 (2021-02-22)¶ Make it possible to pass a lambda to title of Page/Form/Table Improved error when trying to register an already registered style 2.8.6 (2021-02-19)¶ Revert to the old (pre 2.8.2) way of using search_fieldsto compose queries. The new approach failed for cases when there was a custom value_to_qdefinition. A proper fix needs to have a unified approach also when using .pkformat. 2.8.5 (2021-02-17)¶ Render title of Pageobjects. To turn off the rendering of the title pass h_tag__include=False. Removed the register_search_fields warning, it was 90% annoying and 10% useful 2.8.4 (2021-02-15)¶ Form: support passing instance as a lambda, even in combination with auto__model 2.8.3 (2021-02-14)¶ Removed bad assert that prevented passing instance as a lambda for auto__model of Form SQL trace was broken for postgres query_from_indexes should automatically generate filters for foreign keys. This especially affected the admin. 2.8.2 (2021-02-09)¶ Avoid using search_fieldswhen composing queries from model filter values. Always using the .pkfallback approach is more stable when the search field values might not be unique. This will remove a bunch of warnings that weren’t very helpful too. Fixed crash when setting query__include=Falseon Table capitalize()now handles safe strings properly. This will enable you to pass safe strings to titlefor example. Translation of Yes/No Fixed error message for register_search_fields Updated to fontawesome 4.7 Renamed live edit asset to not conflict with the name ‘custom’ which might be fairly common Nicer title in the admin for apps 2.8.1 (2021-02-01)¶ Auto generated tables had “ID” as the column name for foreign keys, instead of the name of the remote model. Profiler fixed: the bind and render of iommi objects that were handled by the middleware weren’t profiled Fixed live edit to work for views with URL arguments Handle settings.BASE_DIR as Path objects fix bulk__include = False on table Make DebugMenu created on demand to avoid setting of breakpoints when debugging your own code Models in admin are now in alphabetical order Fieldis not a Tag, so you can render a Formas a div if you want. The root menu item for the iommi admin was broken if you inherited from Admin Force the live edit view to be bootstrap. This avoids the live edit feature looking a big broken for your own custom styles. Minor bootstrap styling fix for non-editable fields 2.8.0 (2021-01-13)¶ Nested forms The paginator is now lazy. This means we can avoid a potentially expensive .count()database hit in many situations Added Table.bulk_container Table.post_bulk_edittakes evaluate parameters now Column.include=False implies that the column shouldn’t get anything in the bulk form. If you want bulk editing without a visible column use Column.render_column=False Support auto__include=[‘pk’] Fix reinvoke/reinvoke_new_defaults when shortcut is changed Date/datetime parsing bugs fixed after mutation testing Do not do form post_validation if we are in initial display mode Forms now don’t create a submit button by default. If you have a post handler you will get a submit button though. SQL trace bugfixes Custom raw_data callback should have same semantics as constant value (and parsed_data callback) Improved error message on disallowed unbound object access Documentation improvements, for example new pages for dev tools, and styles Live editing on .as_view()style views work in the case of an explicitly declared class Fixed bug where the ajax enhanced table didn’t work if you used Table.divor otherwise changed the tagof Table Fixed auto__model column/filter for CharFieldwith choices 2.7.0 (2020-12-14)¶ A Formcan now contain non- Fieldparts. Iterate over everything to render with form.partsand all the fields to be validated with form.fields. Fields that are not direct children are also collected, so you can easily add extra structure by wrapping a bunch of fields in a html.divfor example. Support Django’s CharField.choicesfeature You can now customize the name shown in the advanced search via Filter.query_name Form submit buttons ( Actions.submit) are now rendered as <button>not as <input type="submit">. Added SQL trace feature You can now apply styles on the root object. Example: root__assets__my_asset=Asset(...) Edit button only present in debug menu when the edit middleware is installed Added profile button to debug menu Make collected assets more accessible when rendering iommi in your own templating environment: you can now access them on the iommi objects: my_iommi_obj.iommi_collected_assets() Removed broken validation of sort columns. This validation prevented sorting on annotations which was very confusing as it worked in debug mode Make it possible to target the live edit page with styles (via LiveEditPage) The live edit view can be flipped between horizontal and vertical layouts The debug tree view is slimmed down (by not including endpoints and assets on lots of things) Field.raw_data_listis removed. You can know if it’s a list or not by checking is_list, so raw_datacovers the uses cases. Include decorators in live edit The debug jump to code feature should work for some more scenarios, and it will not display if it has no good guess. DEPRECATED: Field.choice_to_option. This is replaced by choice_id_formatterand choice_display_name_formatter 2.6.1 (2020-12-01)¶ Fixed live editing to work when distributing iommi 2.6.0 (2020-12-01)¶ Live editing of function based views in DEBUG. Works for both iommi views and normal django views. Added ajax enhanced table filtering You can now turn off the advanced mode on queries: Table(query__advanced__include=False) Queryhas two new refinables: filterand post_process. These are hook points if you need to further customize what query is generated. Enable profiling when DEBUG mode is on, even if you’re not staff Fixed multiselect on empty list Added missing get_errors()member function on Field Fixed select2 widget when the base url do not end with / Styling fixes. Primarily for bulma. 2.5.0 (2020-11-19)¶ include=False on a Column should imply not generating the query filter and bulk field. If you want to not render a column but still want the filters, use the render_column=False feature Added callbacks for saving a form: extra__pre_save_all_but_related_fields, extra__on_save_all_but_related_fields, extra__pre_save Added extra__new_instancecallback to Form.createfor custom object creation The errors list has been changed. You should always use add_error()to add an error on a Fieldor a Form It is now possible to call is_valid()and get_errors()and get what you expect from post_validationon Fieldand Form Query forms can now have additional fields, that are ignored by the filter handling code (when you want to do additional filtering outside of the query logic) Bug fixes with state leaking between binds Fixed jump to code Improved error message for is_valid_filter Added a nice error message if you try to shoot in styleor classas raw strings Fixed empty table message, and invalid query form messages 2.4.0 (2020-11-04)¶ The given rowsqueryset and filtering were not respected for the “Select all rows” bulk feature. This could produce some pretty bad bugs! Support custom bulk post_handlers on lists and not just querysets Tablehas a few new members: initial_rows: the rows you pass (or that gets created by auto__model) is stored unchanged here sorted_rows: initial_rows+ sorting applied sorted_and_filtered_rows: sorted_rows+ filtering applied visible_rows: sorted_and_filtered_rows+ pagination applied rows: this is now a property and will map to the old behavior which is the “most applied” member that exists Fixed passing dunder paths to auto__include. You got a weird crash if the target of the path was a foreign key. There are still issues to be resolved adjacent to this, but the base case now works. Fixed the “select all” feature for pages with multiple tables. 2.3.0 (2020-10-30)¶ Every part can now have assets that are added to the assets of the style and included in the head. This is particularly useful for bundling small pieces of javascript or css with the components that need them and thereby gets us closer to being able to write truly self contained “component”. As a proof of concept I did so for the tables javascript parts. The naming takes care of deduplication of assets. Only include select2 assets when needed (possible because of the point above) Filtering on booleans was very broken. It always returned empty querysets and didn’t produce errors when you tried to do stuff like my_boolean<3 It’s now possible to configure stuff on the freetext field of a query iommi will now grab the root page title from the text from Headerinstances in addition to Part.title Render date fields as such Fixed date and time formatting Support for optgroups in forms Make it possible to insert fields into the form of a query, and filters into a query Differentiate between primary and other actions. This should make iommi pages look more in line with the majority of design systems. If you have a custom style you probably want to add a style definition for Action.primary. Fixed a case of a silent overwrite that could be surprising. This was found during reading the code and has never happened to us in practice. Style fixes for bulma 2.2.0 (2020-10-16)¶ Fix so that style application does not alter definitions destructively. This could lead to some strange behavior if you tried to switch between styles, and it could leak over definitions between things you would not expect. The title of Tableis Nonewhen there is no model Assets as first class concept. You can now insert asset definitions into your style with assets__js=...instead of defining a base_template. This change also removes the base templates for all the built in styles as they are now obsolete. Made it easy to hide the label of a Field by setting display_name=None, or include=False 2.1.0 (2020-10-07)¶ Internationalization! iommi now has i18n support and ships with English, German and Swedish languages out of the box. We welcome more translations. Out of the box support for the Bulma CSS framework Make auto__includespecifications allow foreign key paths By default we now grab display_name from the model fields verbose_name (if applicable) Sometimes you got reordering of parts when doing a post to a form for example, this is now fixed The traversableargument to lambdas is now the leaf and not the root. This was a bug. Support reverse_lazyas url argument to MenuItem Two id attributes were rendered on the input tags in forms (thanks Benedikt Grundmann for reporting!) 2.0.1 (2020-09-22)¶ delete_object__post_handleraccessed instance.idwhich might be valid. It should have accessed instance.pkwhich is always valid. 2.0.0 (2020-09-22)¶ BACKWARDS INCOMPATIBLE: Stylemust now take a base_templateargument. This replaces the setting IOMMI_BASE_TEMPLATE. BACKWARDS INCOMPATIBLE: IOMMI_CONTENT_BLOCKis removed. Replaced by the content_blocksetting for Style. Allow table rows to be provided from a generator. (Disabling paginator) Added blocks ( iommi_head_contents, iommi_top, and iommi_bottom) as useful hook points to add custom data in the templates if you don’t need a totally new template but want to just customize a little bit. The default sort_key on a Column.foreign_key now looks at the searchable field of the remote field (‘name’ by default). This means by default sorting will mostly be more what you expect. Changed the error from get_search_field() for non-unique name to a warning. Removed <table> for layout in query advanced/simple stuff. Don’t warn for missing register_search_fields when attr=None Set admin to bootstrap by default. Added form for changing password. Used by the admin but also usable from your code. Added form for login. Used by the admin but also usable from your code. Fixed foundation styling for query form. Introduced Field.help. This is the fragment that renders the help text for a Field. This means you can now style and customize this part of forms more easily. For example set a CSS class: Field(help__attrs__class__foo='foo'. Use django default date and time formatting in tables. New shortcut for Table: Table.divfor when you want to render a Tableas a bunch of divs. This is useful because a Tableis really a view model of a sequence of stuff, not just a <table>. Possibility to set Actions.tagto Noneto not get a wrapping html tag. Added Table.outeras a tag you can style that encompasses the entire table part. Moved Form.h_tagrendering inside the form tag to make it stylable as a coherent whole. Grab html title from first part if no title is given explicitly. This means you’ll get the <title>tag filled more often by what you expect automatically. Templateinstances are now collected properly by Part. Read admin config from modules. The Admin is now opt in, not opt out. The admin is now MUCH prettier and better. Actions for Tableare now rendered above the table by default. Set actions_belowto Trueto render them the old way. Many misc improvements 1.0.3 (2020-08-24)¶ Changed Table.bulk_formto Table.bulk. The old name was a mistake as the name was always bulk. This meant that styling didn’t work like you expected and the pick feature also lead you down the wrong path. 1.0.2 (2020-08-21)¶ Support user inputted relative dates/datetimes Support more time formats automatically Introduced Filter.parse() which is a hook point for handling special parsing in the query language. The query language will no longer try to convert to integers, floats and dates for you. You have to specify a parse() method. Added traversablekey to evaluate parameters. Think of it like something similar to self. cell__formatnow gets all evaluate parameters like you’d expect Filters: If attris Nonebut you’ve specified value_to_qthen your filter is now included Various bug fixes 1.0.1 (2020-06-24)¶ Optimizations Use select2 as the default for multi_choice Improved usability: Make icon column behavior on falsy values more guessable Accidentally changed default style to foundation, change back to bootstrap Improved usability: Don’t fall back to default template name if the user specified an explicit template name: fail on TemplateNotFound Style on root uses correct base template Allow model fields called context 1.0.0 (2020-06-10)¶ Backwards incompatible: register_search_fieldsreplaces register_name_field. This new system is a list of field names and not just a single field. There is also new searching and filtering behavior based on this that means you will get better search results Backwards incompatible: field_nameas used by model factories is replaced with model_field_name. If you used register_factoryyou will need to change this. The field names on Column, Fieldand Filterare also renamed. Support fields named keys, valueor itemson Django models Added basic styling support for CSS frameworks Water and Foundation Fix include to make None mean False Change Filter.text to search using icontains instead of iexact by default in the basic search mode Change post_validation callback to receive standard evaluate parameters Improved help text for queries Field.radio was broken in the bootstrap style: it specified the input template as the template for the entire field, so the label got erased 0.7.0 (2020-05-22)¶ Fixed default text argument to Fragment Fixed issue where endpoint dispatch parameter was left over in the pagination and sorting links Parts that are None should not be collected. This affected the admin where it printed “None” below the “Admin” link. Added header for bulk edit form in tables Fixed textarea readonly when field is not editable Fixed is_paginated function on Paginator Add request to evaluate parameters Make evaluate and evaluate_recursive match even the **_case by default No dispatch command on a POST is invalid and will now produce an error Lazy bind() on members. This is a performance fix. Fixed bug where display_name could not be overridden with a lambda due to incorrect evaluate handling Removed Table.rendered_columns container. You have to look at the columns and check if they have render_column=False 0.6.2 (2020-04-22)¶ Fixed data-endpoint attribute on table 0.6.1 (2020-04-21)¶ Fixed tbody endpoint and added a div to make the endpoint easier to use 0.6.0 (2020-04-17)¶ Fixed an issue where fragments couldn’t be customized later if built with the htmlbuilder Actioninherits from Fragment. This should be mostly transparent. You can now pass multiple argument to Fragment/ html.foo(). So html.div('foo', 'bar')is now valid and creates two child nodes child0and child1 Uncouple auto__*from rowparameter. auto__only suggests a default. This avoids some confusion one could get if mixing auto__rows, auto__modelsand rowsin some ways. Fixed setting active on nested submenus where the parent had url None 0.5.0 (2020-04-01)¶ Include iommi/base_bootstrap.html and iommi/base_semantic_ui.html in package, and use them if no base.html is present. This improves the out of the box experience for new projects a lot Support mixing of auto__model/ auto__rowbased columns and declarative columns Support attrs__class and attrs__style as callables Added support for context namespace on Page, which is passed to the template when rendering (for now only available on the root page) Fixed how we set title of bulk edit and delete buttons to make configuration more obvious 0.4.0 (2020-03-30)¶ Fixed rendering of grouped actions for bootstrap Respect auto__include order boolean_tristate should be the default for the Field of a Column.boolean New class Header that is used to automatically get h1/h2/etc tags according to nesting of headers Table.rows should be able to be evaluated Added feature that you can type ‘now’ into date/datetime/time fields Feature to be able to force rendering of paginator for single page tables Paginator fixes: it’s now no longer possible to use the Django paginator, but the iommi paginator is more full features in trade. Removed jQuery dependency for JS parts Big improvements to the Menu component filters that have freetext mode now hide their field by default Added “pick” in the debug toolbar. This is a feature to quickly find the part of the document you want to configure Introduced Form.choice_queryset.extra.create_q_from_value Changed so that Query defaults to having the Field included by default Renamed BoundRow/bound_row to Cells/cells Major improvements to the admin Lots and lots of cleanup and bug fixes
https://docs.iommi.rocks/en/latest/history.html
CC-MAIN-2021-49
refinedweb
3,946
55.44
Standard HTML: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ""> <html> <head> <title></title> <link rel='stylesheet' href='css source' /> <script src='Script Source'></script> <script> All that jazz; </script> </head> <body> Content </body> </html> Because you don't understand this, you need to (at this point) completely give up of JavaScript and learn static HTML. If you don't you will NEVER comprehend ANY web development language. @Hawkee Hawkee, one way would be to set up a git server in parallel, meaning running git and current model in tandem. It would require figuring out how to display git's contents in a graphical manner, which shouldn't be too difficult. With the demand you have now, you can run git off of your current web server (assuming you have access). If you need help with that, I can help you out. @Hawkee Is git not more social than static codes? Forks grab the entirety of a project and allow you to edit them and re-upload respectively. I think that collaboration is the most social way to program, and at this point the most social collaboration is done with git. Git is a program, not a host, Github is a site that hosts git projects in a graphical manner. In no way is Hawkee competing with Git, it's nowhere near even the same category. @Hawkee Sean, those sites are using Git, which is 100% different than hawkee's current system (which you probably already know). In order to implement git, he'd require a larger amount of storage, and a full dedicate git server cluster. It's doable, but would require reuploading every script that currently exists under different user accounts on a server cluster which will be incredibly difficult. In other words, this would require an entirely new site! Furthermore, those systems require Git, which while easy to setup, is not so easy to use (especially when a lot of people here are under 15). On the other hand, this would be well worth the time assuming people can figure out how to use git. If Hawkee decides to do this, I suggest making it open source (at least partially), we here at Hawkee can all contribute and make the system in no time. @Hawkee I second Jethro's statement, I don't come here much anymore, but seeing his comments and general demeanor makes me feel like this whole site is full of children. He thinks its [funny|not childish] while the inverse is true. This site isn't made for foolishness, it's a place where people can come together and share their successes and get credit for their advancements. At least that's the way it was for me. At the very least, see mine and Jethro's contributions and loyalty throughout the years vs this kids month of idiocy as weight in the form of authority. function array_peek($a,$k) { $a=array_keys($a); return (array_search($k,$a)!=count($a)-1?$a[array_search($k,$a)+1]:false); } That's how I'd do it =] He did. Get a random number from 0 to 4294967295 (The maximum number that can be represented in hexidecimal representations) then convert it to hex using the dechex() function. This would be much better if you just made the IRC bot with PHP. Also, a nice API would be beneficial. Would be nice if the value didn't need to be different, for easy php generation, this could be done by setting all of the options into an array. I'd like to fix your accordion script if you'd allow me to, it needs a stop so it doesn't constantly expand and contract if you jam it. Pretty cool, but would be better if it was shortened, or you didn't have to include http://. alias secret $iif($isid,return,echo) $iif($len($1-) > 1,$!+ $+ $chr(40)) $+ $replace($mid($regsubex($1-,/(.)/g,$+($!chr,$chr(40),$asc(\t),$chr(41),$chr(1))),1,-1),$+($chr(1),$!chr(32),$chr(1)),$+($chr(41) $!+,$chr(40))) $+ $iif($len($1-) > 1,$chr(41)) Does I win? EDIT: Damnit sunslayer =[ i'd add a check to make sure that the key exists, and if not return [@KEY] id use on *:text:.*:#: as the added . will speed up other non . triggers. t.forum_id != 4 not every forum's mod forum has the id 4 =p regardless of my sensitivity, you don't need to correct in such a demeaning tone. Korvin, you're right about hash data being saved on the ram (temporarily, that is), but NOT for when mirc is closed and then all the data gets lost. /hsave is needed as xDaeMoN stated. Please get the facts straight. what was intended was that upon disconnecting hashes aren't saved, i worded that badly, either way, that doesn't account for you being a douchebag, any word on why that's occuring? you seem to know everything about anything and are willing to defend it violently, might as well explain why you're such a faggot. Warning: Invalid argument supplied for foreach() in /home/hawkee/public_html/post_snippet.php on line 162 Warning: Cannot modify header information - headers already sent by (output started at /home/hawkee/public_html/post_snippet.php:162) in /home/hawkee/public_html/post_snippet.php on line 180 Warning: Cannot modify header information - headers already sent by (output started at /home/hawkee/public_html/post_snippet.php:162) in /home/hawkee/public_html/phpBB2/includes/page_header.php on line 503 Warning: Cannot modify header information - headers already sent by (output started at /home/hawkee/public_html/post_snippet.php:162) in /home/hawkee/public_html/phpBB2/includes/page_header.php on line 509 Warning: Cannot modify header information - headers already sent by (output started at /home/hawkee/public_html/post_snippet.php:162) in /home/hawkee/public_html/phpBB2/includes/page_header.php on line 510 going to bed gn. edit>edited>save>php error with header.php>upload screenshot>saved as new snippet. there is no prob with screenshot, was a random image wasn't meant to be a new post, didn't let me edit and save. couldn't save without a screenie, so uploading one, which wasn't saved and apparently caused it to be a whole new snippet. hash, being saved on your ram, only is lost upon computer shutdown. tryit
http://hawkee.com/profile/16537/
CC-MAIN-2018-05
refinedweb
1,052
64.1
:) !). There's a lot of fodder for future posts here, so now I have no excuse not to blog. For now I will just say that MochiKit does make JavaScript suck less, but suckiness is still greater than zero. I'll also take this time to plug the Amazon Web Services. We're currently using both S3 and EC2, which we expect will make it quite easy for us to scale up as we need to. I hope companies with the infrastructure will follow Amazon's lead—a competitive marketplace for storage and computing services would be awesome. Perhaps overly optimistically we've already structured our internal interfaces to allow us to easily switch providers :) p.s. I'll be at the Office 2.0 Conference next week, drop me a line if you want to meet up. Over. After reading this diatribe on the use of the final modifier, I decided to implement one of the commenters' suggestions: write a tool to strip them out. Of course, by the time I was almost finished I stumbled across Xzajo's BCEL-based implementation, which was only posted a couple of weeks ago. My implementation has a couple of advantages: Here is all the code: package com.sixlegs.definalizer; import java.lang.instrument.*; import java.security.ProtectionDomain; import org.objectweb.asm.*; import static org.objectweb.asm.Opcodes.ACC_FINAL; public class Main implements ClassFileTransformer { public static void premain(String args, Instrumentation inst) { inst.addTransformer(new Main()); } public byte[] transform(ClassLoader loader, String className, Class<?> clazz, ProtectionDomain protectionDomain, byte[] b) { ClassReader reader = new ClassReader(b); ClassWriter writer = new ClassWriter(true); ClassAdapter adapter = new Definalizer(writer, className); reader.accept(adapter, true); return writer.toByteArray(); } static class Definalizer extends ClassAdapter { public Definalizer(ClassVisitor cv, String className) { super(cv); } @Override public void visit(int version, int access, /* ... */) { access &= ~ACC_FINAL; cv.visit(version, access, name, signature, superName, interfaces); } @Override public MethodVisitor visitMethod(int access, String name, /* ... */) { access &= ~ACC_FINAL; return cv.visitMethod(access, name, desc, signature, exceptions); } } } Compile this code into a jar and specify a "Premain-Class" manifest entry: Premain-Class: com.sixlegs.definalizer.Main Now the jar can be specified as an argument to -javaagent. Here is an example which demonstrates using CGLIB to create a subclass at runtime: import net.sf.cglib.proxy.*; import java.lang.reflect.Method; public class Test { public static class FinalExample { @Override final public String toString() { return "final method"; } } public static void main(String[] args) throws Exception { Enhancer e = new Enhancer(); e.setSuperclass(FinalExample.class); e.setCallback(new MethodInterceptor(){ public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.err.println("calling " + method); return proxy.invokeSuper(obj, args); } }); System.err.println("RESULT: " + (FinalExample)e.create()); } } The command line I used to run it was: CLASSPATH=.:cglib.jar java -javaagent:definalizer.jar Test Normally this would fail because the class and method are final, but because definalizer has stripped all of the final modifiers, the method is successfully intercepted: calling public java.lang.String Test$FinalExample.toString() The entire source distribution can be downloaded here, or just the binary jar (use at your own risk). If someone is interested in integrating this into their own project, let me know. Today. Classpath wildcards are a long-awaited feature which are finally making their appearance in Mustang. You can read more about them here and here. Now that the syntax is nailed down I've added the same capabilities to the latest release of the Jar Jar Links library. In particular the dependency finding feature is much easier to use now: $ java -jar jarjar.jar --find --level=jar 'lib/*' This will parse all of the jar files in the lib directory and print out all of the inter-jar dependencies. Note that the asterisk normally must be quoted in order to prevent expansion by the shell. One good use I've found for the dependency code is in building WAR files. We have a number of web applications built from the same source tree, and each one depends on a slightly different set of libraries. The simple approach is to just dump every library into every WAR, but it is not too much harder to use Jar Jar to determine exactly which libraries should be included. Because the format of the --find command to Jar Jar is not exactly what we need, we can use the programmatic API instead: import com.tonicsystems.jarjar.*; public class DepDump { public static void main(String[] args) throws Exception { DepHandler handler = new AbstractDepHandler(DepHandler.LEVEL_JAR){ public void handle(String from, String to) { System.out.println(new File(to).getName()); } }; new DepFind().run(args[0], args[1], handler); } } This will only print out the dependencies in the second classpath argument. For example: $ java DepDump build/main 'lib/*' > includes.txt Assuming all of your class files are in build/main and your libraries in lib, this will only print out the names of the libraries that your code actually uses. Redirecting the output to includes.txt is useful because in our Ant task we can use the includesfile option to only add those particular libraries to our WAR: <zipfileset dir="lib" prefix="WEB-INF/lib" includesfile="includes.txt"/> If you are using the JarJarTask to embed other libraries, using the DepFind API can also be useful to verify that the resulting library has zero dependencies. I've been working on an application which can be deployed via Java Web Start. One nice think about Web Start is that it will use content negotiation with the server to download highly compressed jar files when they are available. The documentation includes sample Servlet code to handle the negotiation, which is nice, but I didn't want to run a Servlet container just for this. Thankfully I ran across Keith Lea's blog entry Guide: How to use Pack200 for your Java Web Start applications on Apache Web Server which shows how to use Apache's own content negotiation modules and eliminates the need for any Servlets. However, it seemed like it could still be made a little simpler. In particular, I didn't like having to create a "type map" for each compressed jar. What follows is what I think is the simplest possible configuration for getting this to work on Apache 2. Add the following to your global httpd.conf file: AddType application/x-java-jnlp-file .jnlp AddType application/x-java-archive .jar <Files *.jar.gz> AddEncoding x-gzip .jar ForceType application/x-java-archive </Files> <Files *.jar.pack.gz> AddEncoding pack200-gzip .jar ForceType application/x-java-archive </Files> In each folder where you will serve jar files from, add an .htaccess file with these lines: Options +MultiViews MultiviewsMatch Any That's it for configuration! Now you just have to drop the right jars into the folder with the .htaccess file. If your original jar is named foo.jar, you should put the following into the folder: foo.jar.unpacked foo.jar.gz foo.jar.pack.gz For my application these three jars were 823, 698, and 234 kilobytes, respectively. Because Web Start auto-updates those bytes can really add up in saved bandwidth costs over time. Here is a simple shell script which will take a single unpacked jar file and create the three necessary files: #!/bin/sh gzip -c $1 > $1.gz pack200 $1.pack.gz $1 mv $1 $1.unpacked Note that renaming foo.jar to foo.jar.unpacked is a critical step. The Apache MultiViews feature will disregard the compressed jars and always serve foo.jar if it actually exists. You don't have to use the .unpacked suffix, just make sure to tack on something. I recently came across Matthias Ernst's blog entry on compiling the JSP expression language. Back in the day this was something that I spent a bit of time on myself, but the code has been languishing ever since we decided to focus on PowerPoint solutions, so Matthias has inspired me to dust it off and release it as an open source project. This zip file includes the entire project: Ant build file, JUnit tests, and all the necessary libraries. It uses ASM 3.0 (beta) for bytecode generation, and Jar Jar Links to embed the ASM libraries when building the library Jar file. The source uses the same license as GNU Classpath (GPL with library exception). The library needs some more documentation, but essentially it is just an implementation of the javax.servlet.jsp.el.ExpressionEvaluator interface: ExpressionEvaluator eval = new com.tonicsystems.el.Evaluator(); Expression e = eval.parseExpression("${8 * 8}", String.class, null); assertEquals("64", e.evaluate(null)); The main benefit of byte-compiling is of course performance. In my very simple tests the performance ranges from about 5-10x faster than the Apache Commons EL, which uses an interpreter. However there are some areas of the EL spec which cause big problems for byte-compiling. In particular, the resulting type when dereferencing variables, Maps, and Lists cannot be known until runtime. The general solution to the unknown type issue is to compile as much of an expression as you can, and lazily compile the rest once you have enough information (i.e. when the variables have been defined). The problem with this is it is possible to design some degenerate expressions which have to be split up into many different subexpressions, all compiled separately. To help counter this, I've added an extension to the parsing interface whereby you can optionally specify a prototype for your variables. This is basically just a Map which "resembles" the variables you will actually end up using. The compiler ignores the actual values, but uses the types of the objects to generate more efficient bytecode: Map prototypes = new HashMap(); prototypes.put("a", new Integer(0)); Expression e = eval.parseExpression("${a + 3}", String.class, null, prototypes); Another bytecode-specific issue is that the JSP EL interfaces only provide a way to parse one expression at a time, but you really do not want to compile each expression into a new class. For this I've added a Precompiler class which can take multiple expressions and ensure that they are all compiled into a single underlying class: Precompiler.process(new Expression[]{ e1, e2, e3 }); BTW, I recently changed the code to use a custom ClassLoader instead of injecting the classes into the parent, in order to facilitate garbage collection compiled expressions. However, this seems to have a negative effect on the runtime performance--the expressions run about twice as slow. Does the use of custom ClassLoaders affect HotSpot somehow? Because the code is relatively old and was never completely finished, there are a few things on the TODO list: If people are interested in working on the code, let me know and I'll register a project somewhere like SourceForge. I just came across a this article on CGLIB. It's the kind of thing I've meant to write for a long time, so I'm glad someone has done it. It provides a nice overview of the proxy side of CGLIB, including using a CallbackFilter and multiple interceptors. As part of our Java PowerPoint renderer I've had to decode all of the image formats that can be embedded within PowerPoint, including the three metafile formats: WMF, EMF, and PICT. Now I could write a whole essay on the how ugly these formats are, but it wouldn't really be fair. All three are mostly just straight dumps of API method calls and in-memory records to disk. A fine choice at the time, I'm sure, but it means that to accurately render them you have to reimplement a big chunk of Windows GDI and Color QuickDraw. On the Windows platform, GDI+ promised to make a lot of the headaches of GDI go away. First and foremost, GDI+ is much more device-independent than GDI. For example, GDI+ did away with raster operations, which are particularly difficult to deal with when converting to modern vector formats like PDF or SVG (although people have made valiant efforts). GDI+ also introduced a new metafile format, EMF+. Because EMF+ uses the new GDI+ records, it should be much nicer to work with. Some other advantages of EMF+ over EMF: Unfortunately, EMF+ is almost completely undocumented. People ask about it on the newsgroups from time to time, but this is the closest thing I found to an answer from Microsoft, three years ago. Luckily, in my searches I did find Jeremy Todd, who as it turned out had reverse-engineered a good chunk of the EMF+ records himself. There are still a number of missing pieces, some of them critical, but it should be a very good base on which to build. One of the reasons for this blog entry is to get the search engines to index his page! What does this have to do with PowerPoint? There is another variation of EMF+, called EMF+ Dual. Dual metafiles are EMF files with EMF+ records hidden inside EMF comments. This lets applications that understand EMF render them as normal. Applications which know to look for the special EMF+ comments can extract the EMF+ records and use them to render instead. In recent version of Microsoft Office, all generated EMFs are actually EMF+ Dual metafiles, including all the charts in Excel and PowerPoint. The upshot is that currently only Microsoft can leverage their knowledge of the EMF+ records in order to produce better looking and more compact output when converting documents to PDF. Even after transitioning to their new XML formats, image objects, including EMF, will exist as binary files within the container ZIP. Hopefully Microsoft will see fit to finally document EMF+, because otherwise I don't see how the presence of secret binary data can be reconciled with the stated goal of an open format.
http://sixlegs.com/blog/atom.xml
crawl-001
refinedweb
2,305
56.05
2 Today, it is not unusual to have programmers spread across buildings, cities, countries (and several time zones) while collaborating on one or more tasks. Distributed version control systems, such as Git, are what makes this possible - from the creation of an app all the way to adding, testing, and shipping new features. This guide is not intended as a complete reference on Git, but as an overview of creating and working with repositories. As such, it assumes that the utility is installed on your system and that you are using a Unix-based operating system. If you are on Windows, Git commands are identical, and you will only need to modify some of the examples. Up until the early 2000s, software developers used to share their work from person to person. As more individuals were involved in the same projects, this approach became time-consuming, error-prone, and far from effective. Version control systems, a set of software tools that help teams share files and track changes over time, were born to address those needs. In 2002, the Linux kernel community was among the first to adopt a version control system known as BitKeeper. Git was later devised by Linus Torvalds and launched in May 2005 after an open and public conflict on licensing terms between these parties. Two months later, a Japanese software engineer named Junio Hamano was appointed as the maintainer, a role that he still fills to this day. Before we dive any further, it is worthy and well to define some common terms we will encounter later: Web-based solutions, such as GitHub, Bitbucket, or GitLab, must not be confused with Git itself. These tools only provide space to store code in the cloud and a friendly interface to perform several operations. In this guide, we will use GitHub, but the process is very similar if you choose another solution. A repository is a folder that contains the files and subdirectories of a project. It can be either public or private, depending on who should have access (anyone or only members of a team, respectively). A branch is a separate development path (in the same repository) that is often used to work on new features without interfering with the main project. Once the code is reviewed and tested, a repository administrator can merge the changes into the master branch. A commit is a snapshot of a repository at a point in time. It allows users to include comments and ask for feedback from other people. Using its hash, one can easily return to a previous state of the project if needed. Before file and directories can be committed, we need to instruct Git to track them. We usually refer to this step simply as adding or staging files. A pull request is a method to inform other developers about and discuss recent changes before incorporating them into the main development path. A fork is an independent project which is based off a given repository. Unlike branches, it is not local to the latter, but it can also be merged into it through a proper pull request. A .gitignore file can be used to indicate which local content should not be committed to the repository. This is particularly useful to avoid pushing temporary files to or exposing sensitive information (such as passwords, SSH or API keys, and credit card numbers) in a web-based solution. With that in mind, let us learn how to use Git and leverage GitHub for a software development project. Albeit simple, the following example will help us illustrate the basics of these utilities. To begin, we will need to create a separate directory and then initialize Git on it: 1 2 3 mkdir learn-git cd learn-git git init . As shown in Fig. 1, the last command automatically placed us in the master branch and generated a hidden subdirectory called .git. This folder contains all the files and directories that allow Git to manage the repository. At this point, we have a local working repository but have not added or committed any files yet. Before we do that, we will follow these steps to create an empty remote repository in GitHub where we will push our code. We are now prepared to start adding files to our staging area and committing them. For this test, we will create a short Python file named disk_info.py with the following content: 1 2 3 4 5 6 7 8 import shutil def disk_percent_usage(directory): ''' Return percent usage of disk where directory resides ''' disk_info = shutil.disk_usage(directory) return round(disk_info.used * 100 / disk_info.total, 2) When this module is used, it is compiled to byte code in a file with the .pyc extension, usually in the same directory or in a subdirectory called __pycache__. In any event, we certainly want to include disk_info.py in our repository but not the associated .pyc file - and that is where .gitignore enters the picture. To avoid keeping track of byte code files, we can add a single line to .gitignore as follows: 1 echo "*.pyc*" >> .gitignore With that, let us add both files (disk_info.py and .gitignore) to the staging area. Fig. 5 shows the difference in the output of git status before and after this step. 1 git add disk_info.py .gitignore The next step consists of committing the files to the repository. The -m option allows to include a message to describe the operation. 1 git commit -m "Initial commit for Pluralsight guide" Until files are committed as explained above, they are not part of the repository although they reside in the same directory where it is initialized. Finally, push the local repository over to GitHub. Note that you will be prompted for your credentials as seen in Fig. 6: 1 2 git remote add origin git push -u origin master If we now browse to our GitHub repository, we should see the files as shown in Fig. 7. The commit hash is enclosed in a red rectangle and should be identical to the one that was returned by git commit earlier. You can always view the changes that were introduced in a given commit via the URL for that commit. In the example above, it is. Additionally, the full commit list (including messages, dates, hashes, and the user account who was responsible for each change) is available through git log. So far, we have only used the master branch, which is where our production-ready program resides. If we want to add a new feature, we should consider creating a separate branch called development, although you can choose another name if you wish, and make changes there to start. 1 git checkout -b development The above command not only created the branch but switched us to it, as you can see in Fig. 8: We can now open our text editor and create a new file named system_info.py with the following lines: 1 2 3 4 5 6 7 8 import platform def kernel_info(): ''' Return Linux kernel information ''' kernel_info = platform.uname() return {'release': kernel_info.release, 'version': kernel_info.version} Next, we will proceed to stage the file, commit the change, and push it to the remote repository. 1 2 3 git add system_info.py git commit -m "Added function to retrieve kernel information" git push -u origin development To switch between branches in GitHub, we can use the dropdown list as illustrated in Fig. 9. If we select development, we should see the file we just added. Additionally, we can compare branches and create a pull request to merge development into master, but we will leave that for later. Once our code is in GitHub, other developers can clone our repository to start working on it on their local machines. Before another developer can contribute to our repository, we need to add him or her as a collaborator in GitHub. To do so, we should go to Settings, click on Collaborators, and type the username or email address to send an invitation. Once our colleague accepts it, he or she will be able to: 1 git clone 1 git checkout development 1 2 echo "# learn-git" > README.md echo "Check out my guide at Pluralsight" >> README.md 1 git add README.md If you need to add several files at once, you may want to stage the entire current directory with git add .instead. 1 git commit -m "Added README.md" 1 git push After making all these changes in the development branch, it is time to create a pull request for merging them into master. To incorporate the latest changes to the master branch, we will raise a pull request. Although this can also be done through the command line, it is much easier in GitHub. When you click on Pull request, you will be taken to a page where you can view the list of the commits in development to be included and add comments as you can see in Fig. 10. Next, click on Create pull request to continue: Finally, go to Pull requests and click on Merge pull request as shown in Fig. 11. Note that you will still be asked to Confirm merge afterward: At this point, the master branch should be up to date when compared to development as you can confirm in Fig. 12: Although it was not the case in this example, Git also provides a method to resolve conflicts between commits in the same branch if needed, as we will see next. If a developer attempts to do a git pull after committing a file and there are discrepancies between his local repository and the remote one, a merge conflict occurs. Generally speaking, a merge conflict arises whenever more than one person edits one or more lines in a file at the same time. When this happens, an indication is added to the offending file(s) as you can see in Fig. 13. To resolve the conflict, you need to edit the file leaving the line(s) you want to keep, commit again, and push. As we mentioned previously, Git also allows us to return to a previous commit if we wish. To do so, we can do git log to view the history and choose a specific snapshot using its hash. For example, to reset the status of master to what it was at commit 1cbe0f3, do 1 git reset 1cbe0f3 This results in the changes that can be seen in Fig. 14: Thus, README.md and system_info.py are still present in the current directory but were removed from the staging area after we ran the previous command. In this guide, we have learned how to create a Git repository, work with branches, merge changes, and resolve conflicts. With these new skills, you will be able to work with other developers more effectively from here on out. 2 Test your skills. Learn something new. Get help. Repeat.Start a FREE 10-day trial
https://www.pluralsight.com/guides/create-git-repository-branching-code
CC-MAIN-2019-22
refinedweb
1,831
62.58
6 AnswersNew Answer It's urgent... 4/12/2021 7:39:24 PMSrijito Ghosh 6 AnswersNew Answer It would be easier if you provided some more details, do you have any code, or anything? Your brief message is cryptic Thanks very much, Steven... I put the data in a data frame, I still don't know what youre trying to do, but the code shows True if the value is less than the std in the stv column and it will show True if the value is less than the mean Hey Steven thanks for your help but can it be done without a data frame? I mean just by using the numpy library without using pandas...😅😅😅 import numpy as np data = np.array([150000, 125000, 320000, 540000, 200000, 120000, 160000, 230000, 280000, 290000, 300000, 500000, 420000, 100000, 150000, 280000]) stv=np.std(data) me_an=np.mean(data) count=0 i=0 while i < len(data): i=i+1 if data[i] in range(stv, me_an): count = count + 1 print ((count/len(data))*100) #this's the code I wrote but it seems that it's not appropriate as per the question. Please help me identify the flaw... Sololearn Inc.4 Embarcadero Center, Suite 1455
https://www.sololearn.com/Discuss/2753305/can-someday-please-help-me-with-the-houses-program-in-data-science-python-please
CC-MAIN-2021-39
refinedweb
205
78.79
Build an Off-Road Raspberry Pi Robot: Part 2 In the previous article, I showed how to do the initial build of our Mantis robot, featuring a RoboClaw motor controller board and a Raspberry Pi. Here, I’ll move on to attaching motors, connecting the RoboClaw to your Pi through a USB port, and supplying the RoboClaw with its own power source. The RoboClaw Controller The Roboclaw series of motor controller starts with a model that can control two motors at up to 7 amps each and ranges up to controlling two motors at 160 amps each with many models in between. I’ll be using the 45-amp model, which is available in two versions: one with pin heads for rotary encoders and the other with screw terminals for those connections. Attaching Motors You might be wondering how the motors on the Mantis will be driven using a motor controller that has two outputs. All of the motors on the left side of the Mantis use one motor output and all of the motors on the right side use the other output. To turn left, all the motors on the left side will be set to turn at the same slower rate than all the motors on the right side of the Mantis. Because each of the x motors on one side of the Mantis is connected to the same motor controller output in parallel, in a worst case if all the motors on the left side stall, they will each draw 20 amps, and the potential draw from the motor controller is 20x amps. For the four-wheel Mantis, I used the 45-amp RoboClaw controller so the controller was happy to serve up enough power to run all the motors in a stalled state. In the course of this build, I clarified some things with ON Motion Control (ionmc) who make the RoboClaw board. According to ionmc, each Roboclaw will handle over-current cases automatically. The maximum current that can be supplied is limited by the temperature of the RoboClaw board. "For example under 85 C the 2x45amp and 2x30amp [RoboClaw] can output up to 60 amps (the amount will vary on a linear slope from 25 V to 85C. Once 85C is reached the current limit is at the rated current(eg 45a or 30a per channel). Once temperature goes over 85 C there is an over temperature current limit which will reduce the maximum current down to 0 amps when it reaches 100 C," ionmc said. Never leave an electric motor in a stalled state. It will generate a lot of heat and likely damage the motor. With the Mantis, one of the motors could stall for a bit as the tire it is driving encounters an obstacle on the ground. That's ok, as long as the Mantis gets over that obstacle; then the motor will revert to drawing significantly less current and not become damaged. Looking at the above quote, the 30 amp RoboClaw controller might be able to drive a six-wheel Mantis -- even though the three wheels on a single output might draw 60 amps if they all stall. As long as the RoboClaw doesn't heat up to 100C, it should still provide power. If a stall is prolonged, then the RoboClaw might just heat up to 100C and stop supplying power to the motors automatically. mounted-motors.jpg Other Connections to the RoboClaw A USB port on the RoboClaw allows easy connection to the Raspberry Pi, but the USB port on the RoboClaw cannot power the RoboClaw. So, you will have to supply the RoboClaw with its own power source to talk to it over USB. There are two ways to do this: either having an explicit logic power supply on the "LB IN" pins or by installing the jumper on the LB-MB (logic battery from main battery) jumper header. My RoboClaw came with the jumper on the LB-MB header already. The RoboClaw has many input modes that let you tell the RoboClaw what to do using wireless receivers, serial commands over TTL serial, or the USB port on the RoboClaw. The default mode of the RoboClaw is 7, which allows you to control it over USB. Mode 7, is packet serial control at address 0x80. You must make sure the connect any battery to the RoboClaw with the correct orientation. Reversing the ground and power leads will result in hardware damage or worse. Connecting a 9V battery over the battery input terminals and connecting the microUSB to the Raspberry Pi resulted in the following when looking at the output of dmesg. root@pi:~# dmesg | tail ... [ 3585.758555] cdc_acm 1-1.4:1.0: ttyACM0: USB ACM device [ 3585.760209] usbcore: registered new interface driver cdc_acm [ 3585.760229] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters root@pi:~# ls -l /dev/*ACM* crw-rw---T 1 root dialout 166, 0 Dec 22 07:16 /dev/ttyACM0 root@pi:~# lsusb -v > /tmp/lsusb.txt root@pi:~# emacs /tmp/lsusb.txt ... idVendor 0x03eb Atmel Corp. idProduct 0x2404 bcdDevice 1.00 iManufacturer 1 iProduct 2 USB Roboclaw 2x45A This output tells you that the RoboClaw should be at /dev/ttyACM0. Instead of using that magic value, it can be convenient to have udev create a link for you to the correct device file. The below 99-roboclaw.rules file will have a /dev/roboclaw device created whenever you connect the RoboClaw to a USB port on the Raspberry Pi. A huge advantage here is that, if you connect something else to a USB port that creates a /dev/ttyACM device, you don't have to wonder if the RoboClaw is now at /dev/ttyACM0 or /dev/ttyACM1; it should still be available at /dev/roboclaw. root@pi:~# cat /etc/udev/rules.d/99-roboclaw.rules ACTION=="add", ATTRS{idProduct}=="2404", ATTRS{idVendor}=="03eb", SYMLINK+="roboclaw" root@pi:~# l /dev/roboclaw lrwxrwxrwx 1 root root 15 Dec 22 07:24 /dev/roboclaw -> bus/usb/001/005 Talking to the RoboClaw from the Raspberry Pi To ensure that the connection to the RoboClaw is working, as good test is to ask the RoboClaw what version board it is and what firmware it is running. The command number 21 does this. Because you can have multiple RoboClaw controllers on a single bus, each command starts with the address of the RoboClaw you are wanting to talk to. The default RoboClaw address is 0x80 -- which is what I'm using in the example. The RoboClaw address is mainly useful if you want to have multiple RoboClaw controllers connected to the same TTL serial interface. If you are connecting to the RoboClaw over USB, then each RoboClaw can have the default address of 0x80, because each will have a different serial device on the Linux machine. Boost is a common collection of libraries used in C++ programming. It includes support for many things, such as intrusive reference counting, collections, graph library, parser generator, and more. The following C++ source code uses boost and boost::asio to talk to the RoboClaw over the USB cable and get the version from the RoboClaw. The boost::asio lets you talk to networks and low-level I/O, which is used below to perform serial communication over the USB port. #include <boost/asio.hpp> #include <boost/asio/serial_port.hpp> #include <boost/bind.hpp> #include <boost/integer.hpp> using namespace boost; using namespace boost::asio; #include <string> #include <iostream> using namespace std; int main( int argc, char** argv ) { std::string serialDev = "/dev/roboclaw"; const uint8_t roboclawAddress = 0x80; if( argc > 1 ) { serialDev = argv[1]; } cerr << "serialDevice:" << serialDev << endl; boost::asio::io_service io; boost::asio::serial_port serial( io, serialDev ); // issue the "Read Firmware Version" command 21 // to the RoboClaw at 0x80 uint8_t commands[] = { roboclawAddress, 21 }; write( serial, boost::asio::buffer(commands, 2)); // give the RoboClaw heaps of time to reply. sleep(1); // read the result string ver = ""; char c = 0; bool reading = true; while( reading ) { asio::read(serial,asio::buffer(&c,1)); switch(c) { case '\0': // also read the crc asio::read(serial,asio::buffer(&c,1)); asio::read(serial,asio::buffer(&c,1)); reading = false; break; default: ver+=c; } } cout << "version: " << ver << endl; return 0; } The getversion command should give you something like the following result. pi@pi ~/src/roboclaw $ ./getversion serialDevice:/dev/roboclaw version: USB Roboclaw 2x45a v4.1.13 Next Time In the rest of this series, I’ll extend the communication with the RoboClaw motor controller, leading to a program to control the robot with the keyboard. I will then move on to using a PS3 joystick to control the robot over Bluetooth. This should give you are powerful robot base that can happily adventure outdoors. This is a great base platform with which to start playing with perception and semi-autonomous robot control. Delving deeper, you might like to add some feedback mechanism to the wheels of your Mantis so that you know how far you have traveled. You might also like to run a robotics platform such as ROS on top of an Ubuntu Linux installation on your Mantis. I would like to respectively thank ServoCity and ION Motion Control for supplying the Mantis 4WD Robot Kit and RoboClaw Motor Controller used in these articles. ServoCity also provided a Raspberry Pi Channel mount and RoboClaw mount to help complete the build quickly. Read Build An Off-Road Raspberry Pi Robot: Part 3 - - Print This - Like (0 likes)
https://www.linux.com/comment/17119
CC-MAIN-2019-26
refinedweb
1,585
59.03
A Simple Guide to Material UI Grids React Rafael Rejuso 04/22/2020 0 Comments If you’ve ever had to work with UI frameworks, you know that they can save lots of time on a project. I recently set up a layout for a complicated system using Material UI Grids for the first time. Since I didn't find any simple tutorials to follow, I created this one. You will need these dependencies to follow along: React Material-UI React Developer Tools (optional) randomcolor (optional) What are Grids? A grid is a container or item that automatically handles different screen sizes and orientations. The grids can change their size depending on the window’s current size and adjust shape accordingly. This ensures that we give the users exactly the best interface and it allows the content to appear consistent across different platforms. How to Get Grids If you already know how to add Material-UI to your current project, you can skip this section. Otherwise, you can add the dependency by running: npm install @material-ui/core or yarn add @material-ui/core To make this tutorial easier to follow, we’ll also be adding randomcolor so that we can visually see our grids easier. After that’s done, simply import all the elements we installed, and we can start working on learning the basics of Material-UI Grids. Let's start with: import React from 'react'; import './App.css'; import {Grid} from '@material-ui/core'; import randomColor from 'randomcolor'; function App() { return ( <div className="App" style={{background:randomColor()}}> Hooray nothing is here! </div> ); } export default App; It shows you something like this: Getting Started is Easy To use Material UI Grids, we can start with wrapping our ‘Hooray nothing is here!' with a Grid, and notice that nothing changes. You can think of Grids like a ‘replacement’ for a div, but they’re much more special. Grid Item vs. Grid Container? import React from 'react'; import './App.css'; import {Grid} from '@material-ui/core'; import randomColor from 'randomcolor'; function App() { return ( <div className="App"> <Grid style={{background:randomColor()}}> Hooray something is here! </Grid> </div> ); } export default App; A Grid can have two types of layouts: containers and items. It’s a pretty easy concept, a container contains grid items, and a grid item is in a grid container. A container has special properties that can be set but we’ll touch on that later. The two properties are not mutually exclusive, so you can have a grid that’s both an item and a container. function App() { return ( <div className="App"> <Grid container> <Grid item style={{background:randomColor()}}> Hooray something is here! </Grid> </Grid> </div> ); } Grid Items, Columns, and Break Points This section contains the most important information for understanding Material UI Grids. Feel free to re-read it a few times if it doesn’t make sense at first. By default, Material UI Grids will try to space your items perfectly evenly, so if you have something simple, like 4 grids items, each item will take up 25% of the window. But, Material UI Grids work on a 12 column grid-layout, and each grid width is a certain percentage of that. So, if we have a Grid of 6, that width should be about 50%. So we can have something like this: function App() { return ( <div className="App"> <Grid container> <Grid item xs={6} style={{background:randomColor()}}> Hooray something is here! </Grid> <Grid item xs={6} style={{background:randomColor()}}> Hooray something is too! </Grid> </Grid> </div> ); } There are a couple of key things to note here like containers and items, but we’ll cover that later. What we’re more interested in is the property that says xs={6}. Like I stated before, Material UI divides the numbers we give it to 12 columns and spaces our content appropriately. Now, we have a layout that looks something like this: Material-UI defines how the Grid acts according to specific breakpoints. Below is a table that shows when a specific breakpoint is reached. Breakpoint Key Window Size xs 0-599 px sm 600px – 959px md 960px – 1279px lg 1280 – 1919px xl 1920px+ Breakpoints are defined starting from the bottom up, meaning if we have xs defined, but not sm or md, it will apply that breakpoint style of the lowest possible key. If we were to define an md key, then our xs breakpoint would apply, up until we hit that md window size. Our defined xs key only affects screen widths between 0-959px. At 960+ px, our md key would apply. That was a lot of information, so let’s see it in practice. In the gif above, each of the four different lines on the bottom of the screen represent different breakpoints. As you can see, when the window screen crosses across the different boundaries, we apply the properties that were specified to Material UI. <Grid container> <Grid item xs={6} sm={2} md={8} lg={12} xl={3} style={{background:randomColor()}}> Hooray something is here! </Grid> <Grid item xs={6} sm={10} md={4} lg={12} xl={9} style={{background:randomColor()}}> Hooray something is too! </Grid> </Grid> One thing to note is that, if we look at xs={6} for both of our Grid items, it splits the space evenly. When we get to the breakpoint of lg and specify the {12} size, we basically ‘fill’ that 12 column limit and move our content on to a new row. By placing our breakpoints to equal 12, we say that we want this Grid item to occupy its own row. This might be enough for the given use case, but with Grid containers, we can go even further. Container Magic With Grid Containers, we can arrange all of our grid items the way that we want to. The first thing we want to do is add spaces around the grid items so that the content isn't directly touching one another. We can add the prop ‘spacing’ and which takes in a value between 0 and 10. The space between each grid is the number you chose, times 8pixel. For example, spacing={2} is 16 pixels. For this example, we’ll refactor it slightly so that the background color only applies to the content inside the grid, and not the actual grid itself, so we can see the spacing. function App() { return ( <div className="App"> <Grid container spacing={3}> <Grid item xs={6}> <div style={{background:randomColor()}}>Hooray something is here!</div> </Grid> <Grid item xs={6}> <div style={{background:randomColor()}}> Hooray something is too! </div> </Grid> <Grid item xs={4}> <div style={{background:randomColor()}}> Another item! </div> </Grid> <Grid item xs={4}> <div style={{background:randomColor()}}> Showing off rows! </div> </Grid> <Grid item xs={4}> <div style={{background:randomColor()}}> Last item! </div> </Grid> </Grid> </div> ); } And now, we have our grids spaced apart! We can also add the prop direction to our container to pick if we want the grids to be in row or column form. When the direction is in a column, instead of the default row configuration, each grid gets its own row. We can still define breakpoints to size our component, however, the breakpoint values will only effect width, so an xs={6} will continue to occupy about 50% of the page. Lazy Layouts (Auto-layout) There’s been a lot of talk about breakpoints which may be off-putting, however, Grids has an answer with its auto-layout functionality. In a given row, we only need to define at least one actual numeric value of the items in a given breakpoint for the system to figure itself out. We still have to specify that the Grid items are the same breakpoints, but with this, we only have to write one number: function App() { return ( <div className="App"> <Grid container spacing={3}> <Grid item xs> <div style={{background:randomColor()}}> A</div> </Grid> <Grid item xs={7}> <div style={{background:randomColor()}}> B </div> </Grid> <Grid item xs> <div style={{background:randomColor()}}> C </div> </Grid> <Grid item xs> <div style={{background:randomColor()}}> D </div> </Grid> </Grid> <Grid container spacing={3}> <Grid item xs> <div style={{background:randomColor()}}> 1</div> </Grid> <Grid item xs> <div style={{background:randomColor()}}> 2 </div> </Grid> <Grid item xs> <div style={{background:randomColor()}}> 3 </div> </Grid> <Grid item xs> <div style={{background:randomColor()}}> 4 </div> </Grid> </Grid> </div> ); } That about does it for Material-UI Grids. Learn more about DMC's Application Development Expertise and contact us with project inquiries! Comments There are currently no comments, be the first to post one. Post a comment Name (required) Email (required) Enter the code shown above: Notify me of followup comments via e-mail
https://www.dmcinfo.com/latest-thinking/blog/id/10114/categoryid/95/a-simple-guide-to-material-ui-grids
CC-MAIN-2022-33
refinedweb
1,455
60.24
Liquid Maze 2008-07-28T19:36:33+00:00 Slava BlogEngine.Net Syndication Generator Slava en-US Liquid Maze Simplest way to logging 2008-07-28T18:43:00+00:00 Slava <p> I use <a href="" target="_blank">NLog</a> for logging. I used to keep Logger property in every class I needed to log from and then have <a href="" target="_blank">Winsdor</a> container inject it with appropriate logger. </p> <p> All of that changed when I switched to <a href="" target="_blank">AutoFac</a> and I wanted to simplify working with logger, especially since not all classes I want to log from are managed by the DI container. </p> <p> The best solution I came up with is to use <a href="" target="_blank">extension methods</a> in .NET 3.5. Here's the code: </p> <p> <div class="codeSnippet"> <div class="codeHeader"> <img src="" /> <a href="" onclick="document.getElementById('snippet_2').style.display = document.getElementById('snippet_2').style.display == 'none' ? 'block' : 'none'; return false;" title="Click to expand/collapse..">C#-Code: Logging extension method</a> </div> <pre id="snippet_2" class="codeContainer"><span style="color:#0000FF">using</span> System; <span style="color:#0000FF">using</span> NLog; <span style="color:#0000FF">namespace</span> Logging { <span style="color:#0000FF">public</span> <span style="color:#0000FF">interface</span> INeedToLog { } <span style="color:#0000FF">public</span> <span style="color:#0000FF">static</span> <span style="color:#0000FF">class</span> LogExtensions { <span style="color:#0000FF">public</span> <span style="color:#0000FF">static</span> Logger Log( <span style="color:#0000FF">this</span> INeedToLog needToLogObj ) { var type = needToLogObj.GetType(); <span style="color:#0000FF">return</span> Logging.GetLogger( type ); } } <span style="color:#0000FF">public</span> <span style="color:#0000FF">static</span> <span style="color:#0000FF">class</span> Logging { <span style="color:#0000FF">public</span> <span style="color:#0000FF">static</span> Logger GetLogger( Type typeToLogFrom ) { <span style="color:#0000FF">return</span> LogManager.GetLogger( typeToLogFrom.Name ); } <span style="color:#0000FF">public</span> <span style="color:#0000FF">static</span> Logger GetLogger( <span style="color:#0000FF">object</span> objectToLogFrom ) { var typeToLogFrom = objectToLogFrom.GetType(); <span style="color:#0000FF">return</span> LogManager.GetLogger( typeToLogFrom.Name ); } } } </pre> </div> <!--<script type="text/javascript"> document.getElementById('snippet_2').style.display='none'; </script>--> </p> <p> I simply inherit from <strong>INeedToLog</strong> from any class in which I need to log. Then extension method <strong>Log</strong> becomes available and I can do something like this. </p> <div class="codeSnippet"> <div class="codeHeader"> <img src="" /> <a href="" onclick="document.getElementById('snippet_3').style.display = document.getElementById('snippet_3').style.display == 'none' ? 'block' : 'none'; return false;" title="Click to expand/collapse..">C#-Code: Log usage</a> </div> <pre id="snippet_3" class="codeContainer"><span style="color:#0000FF">this</span>.Log().Info( "<span style="color:#8B0000">Info text</span>" );</pre> </div> <!--<script type="text/javascript"> document.getElementById('snippet_3').style.display='none'; </script>--> <p> This method for logging might be intrusive into interface hierarchy, but it's very simple to set up, even if you don't use DI. I like that! </p> 2008-07-28T18:43:00+00:00 Slava 0 Re-blogging 2008-06-29T13:06:50+00:00 Slava <p>Wow, people are still tuned to my blog, even though more than a year has passed since last time I blogged. Well, I'm back, but I don't know how often I'll write new posts.</p> <p>I moved to a new blogging software (<a href="">BlogEngine.net</a>) and renamed blog just to <a href="">Liquid Maze</a> (to keep it simple). The old feed will continue to function, but a <a href="">new feed</a> is available now.</p> <p>I'll probably write when I feel like it instead of trying to adhere to some kind of schedule. That didn't work out too well for me. Nonetheless I'll try to keep the quality of content high.</p> <p>So, stay tuned...</p> 2008-06-29T13:06:50+00:00 Slava 0 Do less 2007-05-16T21:20:00+00:00 Slava <P>I just read <A href="" mce_href="">Getting Real</A> book and I really liked it. It was written by guys at <A href="" mce_href="">37 Signals</A>, creators of <A href="" mce_href="">Ruby on Rails</A> and a series of successful online services. The book is about how to be more practical by staying simple and focusing only on currently problems. Among other things it shows that by doing less you can be more productive.</P> <P). </P> <P>Doing less is doing just enough, not everything. There's no perfect or complete state.</P> <P>People often talk about <A class="" href="" mce_href="">Pareto principle</A>..</P> <P>Solving only problems at hand seems more practical and easier to do. When I first saw the idea I thought, "Don't I always try to solve problems at hand?" As I read and learned about it, I realized that, no, not really. I make several mistakes.</P> <UL> <LI>Try to optimize my time by solving problems early. Cost of most problems grows over time, but most of the problems I think of never happen or are completely different in reality than I thought they are.</LI> <LI>I act on what's urgent. In many cases urgent isn't important, but I'm afraid to lose an opportunity. What I came to realize is that many things that appear urgent, are not urgent at all and can be done at any time.</LI> <LI>Do something without understanding of what I'm trying to do. I try not to do that anymore :)</LI></UL> <P.</P> <P.</P> <P>Normal life (like I have any) is the same way actually. I can't solve all my health problems, but I can help prevent them and make it easier to handle them if they appear by eating healthy and exercising.</P> <P. </P> 2007-05-16T21:20:00+00:00 Slava 0 Estimation, Part II 2007-05-08T17:41:00+00:00 Slava <P>In the <A title=Estimationlast post</A>.</P> <P.</P> <P.</P> <P.</P> <P. </P> <P>At this stage I've no idea if my estimations are accurate and when I will complete the next Sider release. In several iterations I hope to have a better picture and a better idea when the release will happen.</P> <P>I also want to mention teams. Most of the time people work in teams and they need to give estimations as a team. I usually work alone so I can't really share any experience or talk about related problems. I suggest you check out <A title="Planning Poker" href="" mce_href="">Planning Poker</A>, a procedure and a game created to help people overcome frequent problems and give accurate estimation together with their team.</P> <P>To learn more about estimation I highly suggest listening to <A href="" mce_href="">Agile Estimation podcast</A>.</P> 2007-05-08T17:41:00+00:00 Slava 0 Estimation 2007-05-02T15:33:00+00:00 Slava <P.</P> <P>So, software developers are often asked to estimate. We often miss and underestimate. Why? Here's my list of the possible reasons. There are many books written on the subject. I have hardly read any of them so I probably miss something.</P> <UL> <LI>We've never done it before, so we have no idea how long it will take. We just guess.</LI> <LI>We lie, because we wish we would have been better developers and could develop it quicker, or because we want to tell somebody what they want to hear, not our opinion.</LI> <LI>We fail to fully grasp the scope. We estimate what we see, but there are a lot of hidden additional work.</LI></UL> <P>In the first case it's just a matter of experience, but I don't think this is a big factor. In either case there's not much we can do about it. I'm stuck with whatever experience I have.</P> .</P> <P>We can actually do something about the last case. When we make mistakes in estimation we are consistent about it and we can compensate for it. That's exactly what an estimation point system and velocity are designed to do in <A href="" mce_href="">Agile Development</A>.</P> <P>While listening to <A href="" mce_href="">Agile Estimation podcast</A>.</P> <P>When estimating we don't know yet how long it will take us to complete each point, but we can say that 4 points task is twice as large and will probably take twice as long as 2 points task to complete.</P> <P.</P> <P>There's more I want to say about estimation and I will continue writing about it in my next post.</P> 2007-05-02T15:33:00+00:00 Slava 0 Understanding Sider 2007-04-20T19:49:00+00:00 Slava <P.</P> <P.</P> .</P> <P.</P> <P.</P> <P>In addition anybody can extend it. History shows that some users (power users I call them) will be interested in customizing it and adding new features. Most people will just want to use them, but extensions created by power users are important to Sider success.</P> <P. </P> 2007-04-20T19:49:00+00:00 Slava 0 Back to blogging and Sider 2007-04-16T16:58:00+00:00 Slava <p>I'm back to blogging. I'm gonna start by changing how I write posts, making them more un-official, like a journal. Not sure yet how that will work out.</p> <p>I'm also back to working on Sider. I decided to make its development process more transparent. I want to be open and honest about what I'm working on, what mistakes I make and how I fix them.</p> <p>I'm in the process of putting all project documentation in one place on the <a href="" mce_href="" title="Wiki">wiki</a> where it's available to anybody. I started to review and publish <a href="" mce_href="" title="Design documents">Sider design documents</a>. <a href="" mce_href="">Sider issues</a>.</p> <p> In addition I recently learned about <a href="" mce_href="" title="Scrum methodology">Scrum<.</p> 2007-04-16T16:58:00+00:00 Slava 0 Taking a break 2007-02-19T21:39:35+00:00 Slava <p>I haven't written at the blog in a while. I realized that my interest has faded. I've been trying to push myself to create new posts, and that's just no fun.</p> <p.</p> <p>Feel free to stick around if you're OK with waiting for a little bit for new posts.</p> <p>Thanks to all people who have being reading my posts for their time and support.</p> 2007-02-19T21:39:35+00:00 Slava 0 EH added to Mindjet Research Accelerator 2007-01-18T20:57:00+00:00 Slava <P>You can now use <A href="" mce_href="">Mindjet Research Accelerator</A> to search through EH forums and blogs. <A href="" mce_href="">Research Accelerator</A> is a plug-in to allow people search for information using different web services from inside of <A class="" href="" mce_href="">MindManager</A>, MS Office applications and IE. You will need to <A href="" mce_href="">download</A> and install plug-in, and then add <A href="" mce_href="">Community Server Research Service</A>.</P> <P>I'd like to thank Michael Scherotter from <A href="" mce_href="">Mindjet</A> for inviting and adding us to the list of supported websites.</P> <P>It's nice that <A href="" mce_href="">Mindjet</A> is working on providing wider support for finding and importing data. It can make you more effective at finding and integrating additional information with your documents.</P> <P.</P> <P. <A class="" href="" mce_href="">MindManager</A> is now one step closer to supporting such scenarios.</P> 2007-01-18T20:57:00+00:00 Slava 0 Blog changes 2007-01-17T02:51:00+00:00 Slava <P.</P> <P>My goal is to do 3-4 posts a week. Up to this point it was much less frequent because I turned blogging into a long and annoying experience.</P> <P.</P> <P.</P> 2007-01-17T02:51:00+00:00 Slava 0 Existing tools that work with information 2007-01-03T18:45:00+00:00 Slava <P>In the <A title="Information management tools" href="" mce_href="">last post</A> I divided existing information management tools (mentioning some in examples) into either open or strict-type categories. Today I continue by describing what I think is done right and what I would want to see improved.</P> <H2>Done right</H2> <H3>Open tools</H3> <P>I'm happy with open tools. Most of them have been in development for over a decade and are helpful with general problems. <A title=MicrosoftMicrosoft</A> has done a good job with its <A title="Microsoft Office" href="" mce_href="">Office</A> and there are several alternatives, such as <A title=OpenOfficeOpenOffice</A>. You can use Microsoft <A title="Microsoft Word" href="" mce_href="">Word</A> (or something similar) if you need to write anything (a report, an article, or a note). Other examples are <A href="" mce_href="">Adobe</A>, Macromedia (which is part of Adobe now) and other companies, all providing good tools to work with pictures and graphics.</P> <P.</P> <H3>Simpler design</H3> <P.</P> <H2>What can be improved</H2> <H3>Strict-type tools</H3> <P.</P> <H3>All tools have common problems</H3> <P>Almost all tools have very similar problems. Few tool supports substantial source control (saving history of changes to see and compare document modifications through its lifetime). Usually there's limited support for collaboration and security. The list goes on, but the whole situation is improving.</P> <H3>Strict-type vs. open</H3> <P.</P> <H2>What can be done</H2> <P.</P> <P.</P> <P>We also want to address a set of common problems I have mentioned previously. Since all tools will run on a single platform, it's possible to share horizontal features (like security or capturing document history) with all Sider-based tools.</P> 2007-01-03T18:45:00+00:00 Slava 0 Sider 0.5 Technology Preview release 2006-12-15T21:18:00+00:00 Slava <P>Whew, finally this version is finished and available for <A title="Sider 0.5 setup" href="" mce_href="">download</A>. It took a lot of effort and much longer than I ever imagined. I've made many mistakes, but also learned a lot.</P> <P>This is a technology preview release. It demonstrates the platform with most important ideas implemented. It's possible to define different types and views, but there are only few extensions available. Read <A href="" mce_href="">release notes</A> for details.</P> <H4>A little bit about us</H4> <P.</P> <H4>What's next?</H4> <P <A class="" href="" mce_href="">wiki roadmap</A> sometime soon.</P> <UL> <LI><STRONG>Move to .NET 2</STRONG> - At least evaluate the move, but most likely we will do it. It offers many improvements over .NET 1.1, not only in general but also to work with XML. Eventually Sider will move to it and the sooner the better. My only concern is possible delay it might introduce. Most likely, we will move to it in several stages.</LI> <LI><STRONG>Persistent user options</STRONG> - Right now, most customization is done through extensions. We want to add application-wide settings.</LI> <LI><STRONG>Support packages</STRONG> - A package is a collection of different extensions. Each package would focus on providing support for specific scenarios, like note management, project management, collections, etc.</LI></UL> <H4>Upcoming packages</H4> <P>These are just a few ideas of popular uses we want to support with Sider.</P> <UL> <LI><STRONG>Note management</STRONG> - There're many programs to work with notes, but none of them get it quite right. We want to have a flexible system that would support graphs (like wikis) of notes, tagging, filtering, etc.</LI> <LI><STRONG>Journal</STRONG> - People often use notes to track progress, to capture thoughts on the topic over time, instead of creating a system for referencing information. Journal will feature special notes, with views heavily oriented on dates and calendar.</LI> <LI><STRONG>Project management</STRONG> - Extensions to allow you put project plans, notes, documents in a single place. There will be support for several methodoliges, including agile (XP, Scrum, combinations), waterfall, etc. But main focus will be on making it possible to mix notes and other documents with tasks, issues, stories. There are often many ways to view project documentation: tasks and related notes, list of features and related tasks, etc. I believe some software (such as <A href="" mce_href="">Trac</A>) represent moves in the right direction, but they aren't quite getting everything right. Of course, they offer many options that won't be possible with Sider in the near future (online collaboration, source management integration, etc).</LI></UL> <P>I also want to go back to Xelog. I like the idea behind it, but I don't like how heavyweight it ended up. I will need to fix that before moving on.</P> <P>With the next post, I'll go back to discussing information management tools. I had some ideas and suggestions on how to improve my classification for them.</P> 2006-12-15T21:18:00+00:00 Slava 0 Sider roadmap 2006-12-13T21:28:00+00:00 Slava <P>I started working on <A title="Sider roadmap" href="" mce_href="">Sider roadmap</A>. It's helpful to have a good roadmap to maintain focus and work on projects. It's something I should have done it much earlier.</P> <P.</P> <P>My goal is to have full design doc online (preferably in wiki). I want for people interested in Sider to have an understanding of the platform and maybe share ideas on what can be improved.</P> <P.</P> <P.</P> <P [wikipedia:MindManager] instead of word processor. [wikipedia:Mindmap] helped to put all my ideas down in writing and quickly organize them, but I think wiki is actually more suited for reading the document with its support for free linking between different pages.</P> 2006-12-13T21:28:00+00:00 Slava 0 Information management tools 2006-12-08T20:06:00+00:00 Slava <p style="text-align: center"> <img src="" alt="" width="470" height="315" /> </p> <p> In our lives we constantly deal with information. I've <a href="" title="Information usage">talked about</a> what people try to do with it, but there are limits to both our physical and mental activities. To make everything easier we invent tools. There are many different kinds of tools to work with information, yet there're a lot of common aspects to their usage and design. </p> <p> <a href="" title="Information usage">my previous</a> post I assume people have two major goals when managing information, to understand it and to share it. </p> <p> Every information management tool does only one thing. It stores information and shows it back to us. There can perform a lot of different operations, but they simply extend our abilities, allowing us to work with more information simultaneously, more accurately and to visualize it differently. </p> <p>. </p> <p>. </p> <p>. </p> <p>. </p> <p>). </p> <p> There are two problems however: scalability and potential lack of features. It becomes harder to implement features for tools that support larger variety of information. For example operations to work with plain text will be simpler than operations to work with rich formated text. </p> <p>. </p> <p>. </p> <p>). </p> <p>. </p> 2006-12-08T20:06:00+00:00 Slava 0 1st Sider release is coming 2006-12-02T17:52:00+00:00 Slava <P <A class="" title="Sider documentation" href="" mce_href="">wiki documentation</A> a little and create website for Sider.</P> 2006-12-02T17:52:00+00:00 Slava 0 Information usage 2006-11-18T15:00:00+00:00 Slava <P>In my <A title="Taking a closer look at information" href="" mce_href="">last post</A> I talked about information and what it is. Today's post is about how people use it and work with it.</P> <P>We use information to decide what to do and to communicate. Let's try to see what we can learn from this description, even though it's pretty simple and abstract.</P> <P).</P> <P).</P> <P:</P> <UL> <LI><STRONG>Simplify</STRONG> - Like computers, people have limited memory and can process only so much information effectively. We want to reduce amount of data we work with to make it easier for us. To do that we can remove any duplication and irrelevant data, and enumerate similar data by assuming it is the same. The downside is that we can get less accurate picture as we eliminate data, so balance of how much information is simplified is important</LI> <LI><STRONG>Capture information</STRONG> - Store it on some media. This is important both to share it and to analyze it. It's important for analysis because we, again, have a limited memory problem and can often process only a portion of data. We need to store the rest of the data while we are working on a part of it to be able to come back to it later. </LI> <LI><STRONG>Capture relationships</STRONG> - Describe how smaller pieces of data relate to each other and how new information is related to existing information (where it fits in the larger picture).</LI> <LI><STRONG>Display</STRONG> - How we see the information determines what it means to us and how we work with it. We often choose the most suitable way to show it depending on what we want to do. For example people are much better at understanding pictures then numbers. Yet numbers are often much more accurate then pictures.</LI></UL> <P.</P> 2006-11-18T15:00:00+00:00 Slava 0 Taking a closer look at information 2006-10-31T19:45:00+00:00 Slava <p>Today I want to start a series of articles on information management. I want to look at what information is, how it relates to our lives, why it's important to think about it, how people work with it, etc. My goal with this and the following posts is to better understand the nature of the information to design better information management tools.</p><p>To understand what it is we need to take a look at data. Data is a description of an object, relationship between objects or a process. I couldn't come up with a better definition. Numbers, letters, pictures, sounds, smells are all data and they represent something to us.</p><p>Most of what we perceive in the world is gradual. There are no distinct borders between colors. On the spectrum one color changes into the other. Time is continuous as well. We created minutes and hours to measure it. We enumerate and simplify data naturally (often without thinking about it) to make it easier for us to work with it. Different pieces of data describe a small characteristic of an object, relationship, process. Looking at a brick we can figure out its size, material it is made from, weight, etc. All of these describe different aspects of the brick. We enumerated information on the brick. Without doing it it would be hard to calculate how many bricks we will need to build a house or how tall it can be before it will collapse. Use of correct tools can help us capture this information and use it more effectively.</p><p>Information is a collection of data organized into a pattern. Humans are very good at recognizing patterns and finding associated meaning. Keep in mind that data and information are objective, but their meaning is very subjective. A brick is a brick no matter who looks at it. Associated meaning (how we see it) can differ. One person might decide to use it for construction, another to use it as a weapon, while third uses it as a paperweight.</p><p>When looking at the information we might recognize it. In that case we automatically recall associated meaning. When we look at a red, rectangular stone we recognize it as a brick. Actually we like to recognize patterns and understand the information we are presented with.</p><p>Patterns we fail to recognize are noise and are very, very boring because we think they are useless. TV snow is a random pattern of black and white dots. We might recognize that something is wrong with TV, but we probably will not be able to understand all signals that force dots to be arranged in one pattern and not the other.</p><p>In the next post I want to talk more about how people work with information. This is directly related what kind of tools can help them do their job better.</p> 2006-10-31T19:45:00+00:00 Slava 0 Problems with native XMLHTTP in IE7 2006-10-22T00:44:00+00:00 Slava <p>Microsoft has finally <a href="" title="IE website">released IE7</a>. It offers <a href="" title="What's new in IE7">a lot of improvements</a> over IE6 for both users and developers. A lot of bugs related to layout, CSS and memory leaks were fixed. I got really excited when I installed it thinking that most of my problems are over, but life is never perfect. I spent almost a whole day trying to figure out how to work around a new problem that appeared with IE7.</p><p>New Internet Explorer introduces <a href="" title="Native XMLHTTP in IE7">native XMLHTTP</a> (used to communicate with server behind the scene without page refresh) support. Up to and including IE6 developers had to use ActiveX object that came with MSXML. Native support makes IE more compatible with other browsers (script is easier to reuse between browsers), but more importantly it is faster and allows XMLHTTP to work even when ActiveX is disabled.</p><p>This new feature became a source of frustration for me. Microsoft is tightening security screws and new XMLHTTP denies local files access. In general I think this is wise, but there are exceptions where access to the local files is needed.</p><p>When I'm developing JavaScript web controls I often test them by simply opening a file from hard drive. With the enhanced security DojoToolkit doesn't work locally since it uses <a href="" title="Native XMLHTTP in IE7">XMLHTTP</a> to load packages.</p><p>I know only one way around this - disable <a href="" title="Native XMLHTTP in IE7">native XMLHTTP</a> support in IE options. This forces DojoToolkit to use old ActiveX MSXML object.</p><p>Another problem is with Sider. It <a href="" title="Hosting and reusing IE">hosts WebBrowser control</a> to show document with HTML views. All files are on the hard drive and <a href="" title="Native XMLHTTP in IE7">native XMLHTTP</a> refuses to load them. This made the application pretty much unusable.</p><p>Again, the only solution I found was to disable <a href="" title="Native XMLHTTP in IE7">native XMLHTTP</a> and force script to use old ActiveX object. However, I can't force users to change IE options just for my application. Microsoft, fortunately, provided a way to customize them for a specific application and I can disable <a href="" title="Native XMLHTTP in IE7">native XMLHTTP</a> only for Sider.</p><p>To disable it for a specific program use this registry key: </p><div class="code">[HKEY_LOCAL_MACHINE\SOFTWARE\<br />Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_XMLHTTP]<br />"ProcessName.exe"=dword:00000000</div><p>I'm not too happy about having to disable new features only because there's no way to configure them. <a href="" title="Native XMLHTTP in IE7">Native XMLHTTP</a> is faster and I would like to have an option of testing it. It's not essential for me now, but at some point it might be more important. For now I can look for an alternative on the Internet from time to time, hoping that there will be a better solution to loading local files through <a href="" title="Native XMLHTTP in IE7">XMLHTTP</a> than simply disabling <a href="" title="Native XMLHTTP in IE7">native XMLHTTP</a> feature.</p> 2006-10-22T00:44:00+00:00 Slava 0 Xelog 0.1 released 2006-10-15T14:37:00+00:00 Slava <p>I have released the first Xelog version. You can look at <a href="" title="Xelog change log">Xelog change log</a> to see how it looks or <a href="" title="Xelog release archive">download it</a>. In this version I focused on implementing the most important things: schema for the change log XML, allow auto-start by opening Xelog XML file in the browser, and support for different views with ability to change them on the fly.</p><p>Current views are simple and static. I considered dynamic views to support on the fly sorting and such, but decided against it. I wanted to release as soon as I could and to have a working proof of concept, but I also wanted Xelog to be useful. I think it is and I'll use it with all my projects.</p><p>My goals for Xelog are to help users read and understand project changes and help developer to record those changes. Having different views and ability to switch them on the fly is a user-oriented feature and I will continue to add more of them in the next releases.</p><p>For the developers I want to provide views to allow change log editing on the fly. I will probably add it at least partially in the next release. For now you would need to edit XML file manually, but there's a Xelog schema to help you. If you are using a sophisticated XML editor it might be able to use it to supply auto-completion.</p><p>With the next release I also want to add support for different formats, such as text, PDF, RSS. I'm not sure yet how that will work and I have a feeling that RSS support might require a server-side solution.</p><p>Last, but not least, I want to allow developers to customize how to show the change log by generating different links to the XML file (or maybe HTML file that will launch Xelog). I'm thinking of using URL arguments to configure Xelog behavior.</p><p>So, check out <a href="" title="Xelog change log">Xelog</a>, play a little with it and I'd love to hear about your thoughts. Would you consider using it? Do you think there's something missing that would make it more useful for you? I'm open to suggestions and ideas.</p><p>I want to focus on Sider and release a technology preview version. I'm not really sure when I'll release next Xelog version, but I don't want to delay it for too long.</p> 2006-10-15T14:37:00+00:00 Slava 0 Impact of updates on the user 2006-10-12T13:08:00+00:00 Slava <p>I was working on Xelog and had an idea. A change log describes what has changed in anapplication. It lists new features and bug fixes. But I don't think it's really about logging project changes. Its main audience is users and they want to know how new updates affect their experience with the program. Most of them don't really care about changes deep inside the application, only about things that are visible on the outside. A user doesn't really care about things like code refactoring (and he shouldn't), unless he's using this code directly. He only cares the benefits it provides, for example refactored code can lead to improved performance (and this can be important if performance hindered program's use).</p><p>Many, many projects only talk about changes to the project, but don't really talk about what it means to the user. Often it's possible figure that out, but what user thinks in many cases is quite different from what developer thinks. This can lead to unintended confusion.</p><p>I added support to Xelog to document this aspect of the changes. Each entry in the change log needs to have an impact flag to indicate how much a user is affected by the change. It can be something minor, such as a spelling fix, or something that can break things, such as public interface change, document format change and so on.</p><p>In addition to the notes describing the change and impact flag, there's a new text field to allow developer describe how the new update affects the user. Its purpose is to allow developer explain what effect he thinks the change will have. It's a good place to describe how to adapt to the new data format or how to use new feature to its fullest.</p><p>I've updated old views to display impact information for each change. In addition, I'm going to add views focused at showing change log with emphasis on this user impact. I want to help anybody reading the change log to understand which changes are important and provide new, cool functionality, and which are minor and thus can be ignored.</p> 2006-10-12T13:08:00+00:00 Slava 0
http://feeds.feedburner.com/LiquidMaze
crawl-002
refinedweb
5,647
64.41
im new to python and i would like some help with super class. Im just doing a very simple little program to test. But i get a error i dont understand. Super class: - Code: Select all class chars: def __init__(self, name, health): self.name = name self.health = health Class: - Code: Select all from chars import chars class warrior(chars): def __init__(self, name, health, ad, crit): chars.__init__(self, name, health) self.ad = ad self.crit = crit and to call the warrior class i do - Code: Select all char1 = warrior("Peter", 50, 20, 5) <warrior.warrior instance at 0x02A97648> and thats the error i get :S
http://www.python-forum.org/viewtopic.php?p=10799
CC-MAIN-2016-40
refinedweb
107
87.11
08 March 2010 11:51 [Source: ICIS news] LONDON (ICIS news)--LyondellBasell has failed to restart its 210,000 tonne/year polypropylene (PP) plant at Carrington, UK, after it attempted to bring the unit back on line following a planned maintenance shutdown in February, a company source said on Monday. “We tried start-up over the weekend and will try again today,” said the source. “Even if we are successful today, we won’t have on-spec product before [10 March].” The plant had been initially due to start up on 1 March after its month-long outage. LyondellBasell has had a very tight stock position, as its 350,000 tonne/year PP unit at Berre, in southern ?xml:namespace> The company was also planning to bring down its unit at “We have a very, very tight inventory situation,” said the source. PP availability in “Seasonal demand is kicking in and we are seeing the strongest order intake since several months,” said the source, adding that the upturn in volumes was due to seasonality. March homopolymer injection PP prices had risen by a minimum of €35/tonne ($48/tonne) to around €1,100/tonne FD (free delivered) NWE (northwest Europe), covering the upstream propylene contract increase, but sellers were looking for more due to the tight availability situation. Several buyers acknowledged that sellers were likely to get more than the initial increase. PP producers in ($1 = €0
http://www.icis.com/Articles/2010/03/08/9340589/lyondellbasell-fails-to-restart-carrington-polypropylene.html
CC-MAIN-2014-41
refinedweb
237
57.4
At the heart of Vert.x is a set of Java APIs that we call Vert.x Core Vert.x core provides functionality for things like: Writing TCP clients and servers Writing HTTP clients and servers including support for WebSockets The Event bus Shared data - local maps and clustered distributed maps Periodic and delayed actions Deploying and undeploying Verticles Datagram Sockets DNS client File system access High availability Native transports Clustering The functionality in core is fairly low level - you won’t find stuff like database access, authorisation or high level web functionality here - that kind of stuff you’ll find in Vert.x ext (extensions). Vert.x core is small and lightweight. You just use the parts you want. It’s also entirely embeddable in your existing applications - we don’t force you to structure your applications in a special way just so you can use Vert.x. You can use core from any of the other languages that Vert.x supports. But here’a a cool bit - we don’t force you to use the Java API directly from, say, JavaScript or Ruby - after all, different languages have different conventions and idioms, and it would be odd to force Java idioms on Ruby developers (for example). Instead, we automatically generate an idiomatic equivalent of the core Java APIs for each language. From now on we’ll just use the word core to refer to Vert.x core. If you are using Maven or Gradle, add the following dependency to the dependencies section of your project descriptor to access the Vert.x Core API and enable the Groovy support: Maven (in your pom.xml): <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-core</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-lang-groovy</artifactId> <version>3.5.1</version> </dependency> Gradle (in your build.gradle file): compile "io.vertx:vertx-core:3.5.1" compile "io.vertx:vertx-lang-groovy:3.5.1" Let’s discuss the different concepts and features in core.: def vertx = Vertx.vertx() When creating a Vertx object you can also specify options if the defaults aren’t right for you: def vertx = Vertx.vertx([ workerPoolSize:40 ]) The VertxOptions object has many settings and allows you to configure things like clustering, high availability, pool sizes and various other settings. The Javadoc describes all the settings in detail.. You may have noticed that in the previous examples a fluent API was used. A fluent API is where multiple methods calls can be chained together. For example: request.response().putHeader("Content-Type", "text/plain").write("some text").end() This is a common pattern throughout Vert.x APIs, so get used to it. Chaining calls like this allows you to write code that’s a little bit less verbose. Of course, if you don’t like the fluent approach we don’t force you to do it that way, you can happily ignore it if you prefer and write your code like this: def response = request.response() response.putHeader("Content-Type", "text/plain") response.write("some text") response.end() The Vert.x APIs are largely event driven. This means that when things happen in Vert.x that you are interested in, Vert.x will call you by sending you events. Some example events are: a timer has fired some data has arrived on a socket, some data has been read from disk an exception has occurred an HTTP server has received a request You handle events by providing handlers to the Vert.x APIs. For example to receive a timer event every second you would do: vertx.setPeriodic(1000, { id -> // This handler will get called every second println("timer fired!") }) Or to receive an HTTP request: // Respond to each http request with "Hello World" server.requestHandler({ request -> // This handler will be called every time an HTTP request is received at the server request.response().end("hello world!") }) Some time later when Vert.x has an event to pass to your handler Vert.x will call it asynchronously. This leads us to some important concepts in Vert.x: With very few exceptions (i.e. some file system operations ending in 'Sync'), none of the APIs in Vert.x block the calling thread. If a result can be provided immediately, it will be returned immediately, otherwise you will usually provide a handler to receive events some time later. Because none of the Vert.x APIs block threads that means you can use Vert.x to handle a lot of concurrency using just a small number of threads. With a conventional blocking API the calling thread might block when: Reading data from a socket Writing data to disk Sending a message to a recipient and waiting for a reply. … Many other situations In all the above cases, when your thread is waiting for a result it can’t do anything else - it’s effectively useless. This means that if you want a lot of concurrency using blocking APIs then you need a lot of threads to prevent your application grinding to a halt. Threads have overhead in terms of the memory they require (e.g. for their stack) and in context switching. For the levels of concurrency required in many modern applications, a blocking approach just doesn’t scale. We mentioned before that Vert.x APIs are event driven - Vert.x passes events to handlers when they are available. In most cases Vert.x calls your handlers using a thread called an event loop. As nothing in Vert.x or your application blocks, the event loop can merrily run around delivering events to different handlers in succession as they arrive. Because nothing blocks, an event loop can potentially deliver huge amounts of events in a short amount of time. For example a single event loop can handle many thousands of HTTP requests very quickly. We call this the Reactor Pattern. You may have heard of this before - for example Node.js implements this pattern. In a standard reactor implementation there is a single event loop thread which runs around in a loop delivering all events to all handlers as they arrive. The trouble with a single thread is it can only run on a single core at any one time, so if you want your single threaded reactor application (e.g. your Node.js application) to scale over your multi-core server you have to start up and manage many different processes. Vert.x works differently here. Instead of a single event loop, each Vertx instance maintains several event loops. By default we choose the number based on the number of available cores on the machine, but this can be overridden. This means a single Vertx process can scale across your server, unlike Node.js. We call this pattern the Multi-Reactor Pattern to distinguish it from the single threaded reactor pattern. We already know that the Vert.x APIs are non blocking and won’t block the event loop, but that’s not much help if you block the event loop yourself in a handler. If you do that, then that event loop will not be able to do anything else while it’s blocked. If you block all of the event loops in Vertx instance then your application will grind to a complete halt! So don’t do it! You have been warned. Examples of blocking include: Thread.sleep() Waiting on a lock Waiting on a mutex or monitor (e.g. synchronized section) Doing a long lived database operation and waiting for a result Doing a complex calculation that takes some significant time. Spinning in a loop If any of the above stop the event loop from doing anything else for a significant amount of time then you should go immediately to the naughty step, and await further instructions. So… what is a significant amount of time? How long is a piece of string? It really depends on your application and the amount of concurrency you require. If you have a single event loop, and you want to handle 10000 http requests per second, then it’s clear that each request can’t take more than 0.1 ms to process, so you can’t block for any more time than that. The maths is not hard and shall be left as an exercise for the reader. If your application is not responsive it might be a sign that you are blocking an event loop somewhere. To help you diagnose such issues, Vert.x will automatically log warnings if it detects an event loop hasn’t returned for some time. If you see warnings like these in your logs, then you should investigate. Thread vertx-eventloop-thread-3 has been blocked for 20458 ms Vert.x will also provide stack traces to pinpoint exactly where the blocking is occurring. If you want to turn off these warnings or change the settings, you can do that in the VertxOptions object before creating the Vertx object. In a perfect world, there will be no war or hunger, all APIs will be written asynchronously and bunny rabbits will skip hand-in-hand with baby lambs across sunny green meadows. But… the real world is not like that. (Have you watched the news lately?) Fact is, many, if not most libraries, especially in the JVM ecosystem have synchronous APIs and many of the methods are likely to block. A good example is the JDBC API - it’s inherently synchronous, and no matter how hard it tries, Vert.x cannot sprinkle magic pixie dust on it to make it asynchronous. We’re not going to rewrite everything to be asynchronous overnight so we need to provide you a way to use "traditional" blocking APIs safely within a Vert.x application. As discussed before, you can’t call blocking operations directly from an event loop, as that would prevent it from doing any other useful work. So how can you do this? It’s done by calling executeBlocking specifying both the blocking code to execute and a result handler to be called back asynchronous when the blocking code has been executed. vertx.executeBlocking({ future -> // Call some blocking API that takes a significant amount of time to return def result = someAPI.blockingMethod("hello") future.complete(result) }, { res -> println("The result is: ${res.result()}") }) By default, if executeBlocking is called several times from the same context (e.g. the same verticle instance) then the different executeBlocking are executed serially (i.e. one after another). If you don’t care about ordering you can call executeBlocking specifying false as the argument to ordered. In this case any executeBlocking may be executed in parallel on the worker pool. An alternative way to run blocking code is to use a worker verticle A worker verticle is always executed with a thread from the worker pool. By default blocking code is executed on the Vert.x worker pool, configured with setWorkerPoolSize. Additional pools can be created for different purposes: def executor = vertx.createSharedWorkerExecutor("my-worker-pool") executor.executeBlocking({ future -> // Call some blocking API that takes a significant amount of time to return def result = someAPI.blockingMethod("hello") future.complete(result) }, { res -> println("The result is: ${res.result()}") }) The worker executor must be closed when it’s not necessary anymore: executor.close() When several workers are created with the same name, they will share the same pool. The worker pool is destroyed when all the worker executors using it are closed. When an executor is created in a Verticle, Vert.x will close it automatically for you when the Verticle is undeployed. Worker executors can be configured when created: // // 10 threads max def poolSize = 10 // 2 minutes def maxExecuteTime = 120000 def executor = vertx.createSharedWorkerExecutor("my-worker-pool", poolSize, maxExecuteTime)({ ar -> if (ar.succeeded()) { // All servers started } else { // At least one server failed } }) The operations run concurrently, the Handler attached to the returned future is invoked upon completion of the composition. When one of the operation fails (one of the passed future is marked as a failure), the resulting future is marked as failed too. When all the operations succeed, the resulting future is completed with a success. Alternatively, you can pass a list (potentially empty) of futures: CompositeFuture.all([future1, future2, future3]) While the all composition waits until all futures are successful (or one fails), the any composition waits for the first succeeded future. CompositeFuture.any takes several futures arguments (up to 6) and returns a future that is succeeded when one of the futures is, and failed when all the futures are failed: CompositeFuture.any(future1, future2).setHandler({ ar -> if (ar.succeeded()) { // At least one is succeeded } else { // All failed } }) A list of futures can be used also: CompositeFuture.any([f1, f2, f3]) The join composition waits until all futures are completed, either with a success or a failure. CompositeFuture.join takes several futures arguments (up to 6) and returns a future that is succeeded when all the futures are succeeded, and failed when all the futures are completed and at least one of them is failed: CompositeFuture.join(future1, future2, future3)). Vert.x comes with a simple, scalable, actor-like deployment and concurrency model out of the box that you can use to save you writing your own. This model is entirely optional and Vert.x does not force you to create your applications in this way if you don’t want to.. The model does not claim to be a strict actor-model implementation, but it does share similarities especially with respect to concurrency, scaling and deployment. To use this model, you write your code as set of verticles. Verticles are chunks of code that get deployed and run by Vert.x. A Vert.x instance maintains N event loop threads (where N by default is core*2) by default. Verticles can be written in any of the languages that Vert.x supports and a single application can include verticles written in multiple languages. You can think of a verticle as a bit like an actor in the Actor Model. An application would typically be composed of many verticle instances running in the same Vert.x instance at the same time. The different verticle instances communicate with each other by sending messages on the event") } } When Vert.x deploys the verticle it will call the start method, and when the method has completed the verticle will be considered started. You can also optionally override the stop method. This will be called by Vert.x when the verticle is undeployed and when the method has completed the verticle will be considered stopped.. Standard verticles are assigned an event loop thread when they are created and the start method is called with that event loop. When you call any other methods that takes a handler on a core API from an event loop then Vert.x will guarantee that those handlers, when called, will be executed on the same event loop. This means we can guarantee that all the code in your verticle instance is always executed on the same event loop (as long as you don’t create your own threads and call it!). This means you can write all the code in your application as single threaded and let Vert.x worry about the threading and scaling. No more worrying about synchronized and volatile any more, and you also avoid many other cases of race conditions and deadlock so prevalent when doing hand-rolled 'traditional' multi-threaded application development. A worker verticle is just like a standard verticle but it’s executed using a thread from the Vert.x worker thread pool, rather than using an event loop. Worker verticles are designed for calling blocking code, as they won’t block any event loops. If you don’t want to use a worker verticle to run blocking code, you can also run inline blocking code directly while on an event loop.. You can deploy a verticle using one of the deployVerticle method, specifying a verticle name or you can pass in a verticle instance you have already created yourself. def myVerticle = new examples.CoreExamples.MyVerticle() vertx.deployVerticle(myVerticle) You can also deploy verticles by specifying the verticle name. The verticle name is used to look up the specific VerticleFactory that will be used to instantiate the actual verticle instance(s). Different verticle factories are available for instantiating verticles in different languages and for various other reasons such as loading services and getting verticles from Maven at run-time. This allows you to deploy verticles written in any language from any other language that Vert.x supports. Here’s an example of deploying some different types of verticles: //") When deploying verticle(s) using a name, the name is used to select the actual verticle factory that will instantiate the verticle(s). Verticle names can have a prefix - which is a string followed by a colon, which if present will be used to look-up the factory, e.g. js:foo.js // Use the JavaScript verticle factory groovy:com.mycompany.SomeGroovyCompiledVerticle // Use the Groovy verticle factory service:com.mycompany:myorderservice // Uses the service verticle factory If no prefix is present, Vert.x will look for a suffix and use that to lookup the factory, e.g. foo.js // Will also use the JavaScript verticle factory SomeScript.groovy // Will use the Groovy verticle factory If no prefix or suffix is present, Vert.x will assume it’s a Java fully qualified class name (FQCN) and try and instantiate that. Most Verticle factories are loaded from the classpath and registered at Vert.x startup. You can also programmatically register and unregister verticle factories using registerVerticleFactory and unregisterVerticleFactory if you wish. Verticle deployment is asynchronous and may complete some time after the call to deploy has returned. If you want to be notified when deployment is complete you can deploy specifying a completion handler: vertx.deployVerticle("com.mycompany.MyOrderProcessorVerticle", { res -> if (res.succeeded()) {:16 ] vertx.deployVerticle("com.mycompany.MyOrderProcessorVerticle", options) This is useful for scaling easily across multiple cores. For example you might have a web-server verticle to deploy and multiple cores on your machine, so you want to deploy multiple instances to utilise all the cores.) Verticles can be deployed with High Availability (HA) enabled. In that context, when a verticle is deployed on a vert.x instance that dies abruptly, the verticle is redeployed on another vert.x instance from the cluster. To run an verticle with the high availability enabled, just append the -ha switch: vertx run my-verticle.js -ha When enabling high availability, no need to add -cluster. More details about the high availability feature and configuration in the High Availability and Fail-Over section. You can use Vert.x directly in your Maven or Gradle projects in the normal way by adding a dependency to the Vert.x core library and hacking from there. However you can also run Vert.x verticles directly from the command line if you wish. To do this you need to download and install a Vert.x distribution, and add the bin directory of the installation to your PATH environment variable. Also make sure you have a Java 8 JDK on your PATH. You can now run verticles by using the vertx run command. Here are some examples: # Run a JavaScript verticle vertx run my_verticle.js # Run a Ruby verticle vertx run a_n_other_verticle.rb # Run a Groovy script verticle, clustered vertx run FooVerticle.groovy -cluster You can even run Java source verticles without compiling them first! vertx run SomeJavaSourceFile.java Vert.x will compile the Java source file on the fly before running it. This is really useful for quickly prototyping verticles and great for demos. No need to set-up a Maven or Gradle build first to get going! For full information on the various options available when executing vertx on the command line, type vertx at the command line. Threads maintained by Vert.x instances are not daemon threads so they will prevent the JVM from exiting. This will shut-down all internal thread pools and close other resources, and will allow the JVM to exit. When Vert.x provides an event to a handler or calls the start or stop methods of a Verticle, the execution is associated with a Context. Usually a context is an event-loop context and is tied to a specific event loop thread. So executions for that context always occur on that exact same event loop thread. In the case of worker verticles and running inline blocking code a worker context will be associated with the execution which will use a thread from the worker thread pool. To retrieve the context, use the getOrCreateContext method:()) { println("Context not attached to a thread managed by vert.x") } When you have retrieved the context object, you can run code in this context asynchronously. In other words, you submit a task that will be eventually run in the same context, but later: vertx.getOrCreateContext().runOnContext({ v -> println("This will be executed asynchronously in the same context") }) When several handlers run in the same context, they may want to share data. The context object offers methods to store and retrieve data shared in the context. For instance, it lets you pass data to some action run with runOnContext:. You can also set a timer to fire periodically by using setPeriodic. There will be an initial delay equal to the period. The return value of setPeriodic is a unique timer id (long). This can be later used if the timer needs to be cancelled. The argument passed into the timer event handler is also the unique timer id: instance. It can even be bridged to allow client side JavaScript running in a browser to communicate on the same event bus.. First some theory: Messages are sent on the event bus to an address. Vert.x doesn’t bother with any fancy addressing schemes. In Vert.x an address is simply a string. Any string is valid. However it is wise to use some kind of scheme, e.g. using periods to demarcate a namespace. Some examples of valid addresses are europe.news.feed1, acme.games.pacman, sausages, and X. Messages are received. The event bus also supports point to point messaging. Messages are sent to an address. Vert.x will then route it to just one of the handlers registered at that address. If there is more than one handler registered at the address, one will be chosen using a non-strict round-robin algorithm. With point to point messaging, an optional reply handler can be specified when sending the message. When a message is received by a recipient, and has been handled, the recipient can optionally decide to reply to the message. If they do so the reply handler will be called. When the reply is received back at the sender, it too can be replied to. This can be repeated ad-infinitum, and allows a dialog to be set-up between two different verticles. This is a common messaging pattern called the request-response pattern. Vert.x does it’s. -> println("I have received a message: ${message.body()}") }) The object returned from call to consumer() is an instance of MessageConsumer This object can subsequently be used to unregister the handler, or use the handler as a stream. Alternatively you can use consumer to to return a MessageConsumer with no handler set, and then set the handler on that. For example: def eb = vertx.eventBus() def consumer = eb.consumer("news.uk.sport") consumer.handler({ message -> println("I have received a message: ${message.body()}") }) When registering a handler on a clustered event bus, it can take some time for the registration to reach all nodes of the cluster. If you want to be notified when this has completed, you can register a completion handler on the MessageConsumer object. consumer.completionHandler({ res -> if (res.succeeded()) {()) { println("Received reply: ${ar.result().body()}") } }) The reply can contain a message body which can contain useful information. What the "processing" actually means is application defined and depends entirely on what the message consumer does and is not something that the Vert.x event bus itself knows or cares about. Some examples: A simple message consumer which implements a service which returns the time of the day would acknowledge with a message containing the time of day in the reply body A message consumer which implements a persistent queue, might acknowledge with true. You can send any object you like across the event bus if you define and register a message codec for it. Message codecs have a name and you specify that name in the DeliveryOptions when sending or publishing the message: eventBus.registerCodec(myCodec) def options = [ codecName:myCodec.name() ] eventBus.send("orders", new docoverride.eventbus.Examples.MyPOJO(), options) If you always want the same codec to be used for a particular type then you can register a default codec for it, then you don’t have to specify the codec on each send in the delivery options: Code not translatable You unregister a message codec with unregisterCodec. Message codecs don’t always have to encode and decode as the same type. For example you can write a codec that allows a MyPOJO class to be sent, but when that message is sent to a handler it arrives as a MyOtherPOJO class. default HazelcastClusterManager. You can run Vert.x clustered on the command line with vertx run my-verticle.js -cluster If you’re registering event bus handlers from inside verticles, those handlers will be automatically unregistered when the verticle is undeployed. The event bus can be configured. It is particularly useful when the event bus is clustered. Under the hood the event bus uses TCP connections to send and receive message, so the EventBusOptions let you configure all aspects of these TCP connections. As the event bus acts as a server and client, the configuration is close to NetClientOptions and NetServerOptions. def options = [ eventBusOptions:[ ssl:true, keyStoreOptions:[ path:"keystore.jks", password:"wibble" ], trustStoreOptions:[ path:"keystore.jks", password:"wibble" ], clientAuth:"REQUIRED" ] ] Vertx.clusteredVertx(options, { res -> if (res.succeeded()) { def vertx = res.result() def eventBus = vertx.eventBus() println("We now have a clustered event bus: ${eventBus}") } else {, as you would do with setClustered, getClusterHost and getClusterPort. When used in containers, you can also configure the public host and port: def options = [ eventBusOptions:[ clusterPublicHost:"whatever", clusterPublicPort:1234 ] ] Vertx.clusteredVertx(options, { res -> if (res.succeeded()) { def vertx = res.result() def eventBus = vertx.eventBus() println("We now have a clustered event bus: ${eventBus}") } else { println("Failed: ${res.cause()}") } }) To manipulate JSON object, Vert.x proposes its own implementation of JsonObject and JsonArray.). Most data is shuffled around inside Vert.x using buffers. A buffer is a sequence of zero or more bytes that can read from or written to and which expands automatically as necessary to accommodate any bytes written to it. You can perhaps think of a buffer as smart byte array.) You can also write into the buffer at a specific index, by using the setXXX methods. Set methods exist for various different data types. All the set methods take an index as the first argument - this represents the position in the buffer where to start writing the data. The buffer will always expand as necessary to accommodate the data.)}") } Unsigned numbers can be read from or appended/set to a buffer with the getUnsignedXXX, appendUnsignedXXX and setUnsignedXXX methods. This is useful when implementing a codec for a network protocol optimized to minimize bandwidth consumption. In the following example, value 200 is set at specified position with just one byte: server = vertx.createNetServer() server.listen(1234, "localhost") The default host is 0.0.0.0 which means 'listen on all available addresses' and the default port is 0, which is a special value that instructs the server to find a random unused local port and use that. buffer = Buffer.buffer().appendFloat(12.34f).appendInt(123) socket.write(buffer) // Write a string in UTF-8 encoding socket.write("some data") // Write a string using the specified encoding socket.write("some data", "UTF-16") Write operations are asynchronous and may not occur until some time after the call to write has returned.. Files and classpath resources can be written to the socket directly using sendFile. This can be a very efficient way to send files, as it can be handled by the OS kernel directly where supported by the operating system. Please see the chapter about serving files from the classpath for restrictions of the classpath resolution or disabling it. socket.sendFile("myfile.dat") Instances of NetSocket are also ReadStream and WriteStream instances so they can be used to pump data to or from other read and write streams. See the chapter on streams and pumps for more information. A non SSL/TLS connection can be upgraded to SSL/TLS using upgradeToSsl. The server or client must be configured for SSL/TLS for this to work correctly. Please see the chapter on SSL/TLS for more information. Call close to close the server. Closing the server closes any open connections and releases all server resources. The close is actually asynchronous and might not complete until some time after the call has returned. If you want to be notified when the actual close has completed then you can pass in a handler. This handler will then be called when the close has fully completed. server.close({ res -> if (res.succeeded()) { println("Server is now closed") } else { println("close failed") } }) If you’re creating TCP servers and clients from inside verticles, those servers and clients will be automatically closed when the verticle is undeployed. The handlers of any TCP server are always executed on the same event loop thread. This means that if you are running on a server with a lot of cores, and you only have this one instance deployed then you will have at most one core utilised on your server. In order to utilise more cores of your server you will need to deploy more instances of the server. You can instantiate more instances programmatically in your code: // Create a few instances so we can utilise cores (0..<10).each { i -> def server = vertx.createNetServer() server.connectHandler({ socket -> socket.handler({ buffer -> // Just echo back the data socket.write(buffer) }) }) server.listen(1234, "localhost") } or, if you are using verticles you can simply deploy more instances of your server verticle by using the -instances option on the command line: vertx run com.mycompany.MyVerticle -instances 10 or when programmatically deploying your verticle def options = [ instances:10 ] vertx.deployVerticle("com.mycompany.MyVerticle", options) Once you do this you will find the echo server works functionally identically to before, but all your cores on your server can be utilised and more work can be handled. At this point you might be asking yourself 'How can you have more than one server listening on the same host and port? Surely you will get port conflicts as soon as you try and deploy more than one instance?' Vert.x does a little magic here.* When you deploy another server on the same host and port as an existing server it doesn’t actually try and create a new server listening on the same host/port. Instead it internally maintains just a single server, and, as incoming connections arrive it distributes them in a round-robin fashion to any of the connect handlers. Consequently Vert.x TCP servers can scale over available cores while each instance remains single threaded. client = vertx.createNetClient(options) Network activity is logged by Netty with the DEBUG level and with the io.netty.handler.logging.LoggingHandler name. When using network activity logging there are a few things to keep in mind: logging is not performed by Vert.x logging but by Netty this is not a production feature You should read the Netty logging section. TCP clients and servers can be configured to use Transport Layer Security - earlier versions of TLS were known as SSL. The APIs of the servers and clients are identical whether or not SSL/TLS is used, and it’s enabled by configuring the NetClientOptions or NetServerOptions instances used to create the servers or clients. SSL/TLS servers usually provide certificates to clients in order verify their identity to clients. Certificates/keys can be configured for servers in several ways: The first method is by specifying the location of a Java key-store which contains the certificate and private key. The password for the key store should also be provided:. If the trustALl is set to true on the client, then the client will trust all server certificates. The connection will still be encrypted but this mode is vulnerable to 'man in the middle' attacks. I.e. you can’t be sure who you are connecting to. Use this with caution. Default value is false. def options = [ ssl:true, trustAll:true ] def client = vertx.createNetClient(options) If trustAll is not set then a client trust store must be configured and should contain the certificates of the servers that the client trusts. By default, host verification is disabled on the client. To enable host verification, set the algorithm to use on your client (only HTTPS and LDAPS is currently supported): def options = [ ssl:true, hostnameVerificationAlgorithm:"HTTPS" ] def client = vertx.createNetClient(options) Likewise server configuration, the client trust can be configured in several ways: The first method is by specifying the location of a Java trust-store which contains the certificate authority. It is just a standard Java key store, the same as the key stores on the server side. The client trust store location is set by using the function path on the jks options. If a server presents a certificate during connection which is not in the client trust store, the connection attempt will not succeed.) If the server requires client authentication then the client must present its own certificate to the server when connecting. The client can be configured in several ways: The first method is by specifying the location of a Java key-store which contains the key and certificate. Again it’s just a regular Java key store. The client keystore location is set by using the function path on the jks. It is very often the case that self-signed certificates are required, be it for unit / integration tests or for running a development version of an application. SelfSignedCertificate can be used to provide self-signed PEM certificate helpers and give KeyCertOptions and TrustOptions configurations::[:] ] Server Name Indication (SNI) is a TLS extension by which a client specifies a hostname attempting to connect: during the TLS handshake the client gives a server name and the server can use it to respond with a specific certificate for this server name instead of the default deployed certificate. If the server requires client authentication the server can use a specific trusted CA certificate depending on the indicated server name. When SNI is active the server uses the certificate CN or SAN DNS (Subject Alternative Name with DNS) to do an exact match, e.g the certificate CN or SAN DNS certificate to match a wildcard name, e.g *.example.com otherwise the first certificate when the client does not present a server name or the presented server name cannot be matched When the server additionally requires client authentication: if JksOptions were used to set the trust options ( options) then an exact match with the trust store alias is done otherwise the available CA certificates are used in the same way as if no SNI is in place You can enable SNI on the server by setting setSni to true and configured the server with multiple key/certificate pairs. Java KeyStore files or PKCS12 files can store multiple key/cert pairs out of the box. Application-Layer Protocol Negotiation (ALPN) is a TLS extension for application layer protocol negotiation. It is used by HTTP/2: during the TLS handshake the client gives the list of application protocols it accepts and the server responds with a protocol it supports. If you are using Java 9, you are fine and you can use HTTP/2 out of the box without extra steps. Java 8 does not supports ALPN out of the box, so ALPN should be enabled by other means: OpenSSL support Jetty-ALPN support The engine options to use is the getSslEngineOptions options when it is set JdkSSLEngineOptions when ALPN is available for JDK OpenSSLEngineOptions when ALPN is available for OpenSSL otherwise it fails OpenSSL provides native ALPN support. OpenSSL requires to configure setOpenSslEngineOptions and use netty-tcnative jar on the classpath. Using tcnative may require OpenSSL to be installed on your OS depending on the tcnative implementation. Jetty-ALPN is a small jar that overrides a few classes of Java 8 distribution to support ALPN. The JVM must be started with the alpn-boot-${version}.jar in its bootclasspath: -Xbootclasspath/p:/path/to/alpn-boot${version}.jar where ${version} depends on the JVM version, e.g. 8.1.7.v20160121 for OpenJDK 1.8.0u74 . The complete list is available on the Jetty-ALPN page. The main drawback is that the version depends on the JVM. To solve this problem the Jetty ALPN agent can be use instead. The agent is a JVM agent that will chose the correct ALPN version for the JVM running it: -javaagent:/path/to/alpn/agent. Vert.x allows you to easily write non blocking HTTP clients and servers. Vert.x supports the HTTP/1.0, HTTP/1.1 and HTTP/2 protocols. The base API for HTTP is the same for HTTP/1.x and HTTP/2, specific API features are available for dealing with the HTTP/2 protocol. server = vertx.createHttpServer(options) ALPN is a TLS extension that negotiates the protocol before the client and the server start to exchange data. Clients that don’t support ALPN will still be able to do a classic SSL handshake. ALPN will usually agree on the h2 protocol, although http/1.1 can be used if the server or the client decides so. To handle h2c requests, TLS must be disabled, the server will upgrade to HTTP/2 any request HTTP/1.1 that wants to upgrade to HTTP/2. It will also accept a direct h2c connection beginning with the PRI * HTTP/2.0\r\nSM\r\n preface. When a server accepts an HTTP/2 connection, it sends to the client its initial settings. The settings define how the client can use the connection, the default initial settings for a server are: getMaxConcurrentStreams: 100 server = vertx.createHttpServer() server.listen(8080, "myhost.com") The default host is 0.0.0.0 which means 'listen on all available addresses' and the default port is 80. }) When a request arrives, the request handler is called passing in an instance of HttpServerRequest. This object represents the server side HTTP request. The handler is called when the headers of the request have been fully read. If the request contains a body, that body will arrive at the server some time after the request handler has been called. The server request object allows you to retrieve the uri, path, params and headers, amongst other things. Each server request object is associated with one server response object. You use response to get a reference to the HttpServerResponse object. Here’s a simple example of a server handling a request and replying with "hello world" to it. vertx.createHttpServer().requestHandler({ request -> request.response().end("Hello world") }).listen(8080). Just like headers this returns an instance of MultiMap as there can be more than one parameter with the same name. Request parameters are sent on the request URI, after the path. For example if the URI was: /page.html?param1=abc¶m2=xyz Then the parameters would contain the following: param1: 'abc' param2: 'xyz Note that these request parameters are retrieved from the URL of the request. If you have form attributes that have been sent as part of the submission of an HTML form submitted in the body of a multi-part/form-data request then they will not appear in the params here.. Often an HTTP request contains a body that we want to read. As previously mentioned the request handler is called when just the headers of the request have arrived so the request object does not have a body at that point. This is because the body may be very large (e.g. a file upload) and we don’t generally want to buffer the entire body in memory before handing it to you, as that could cause the server to exhaust available memory. To receive the body, you can use the handler on the request, this will get called every time a chunk of the request body arrives. Here’s an example: request.handler({ buffer -> println("I have received a chunk of the body of length ${buffer.length()}") }) The object passed into the handler is a Buffer, and the handler can be called multiple times as data arrives from the network, depending on the size of the body. In some cases (e.g. if the body is small) you will want to aggregate the entire body in memory, so you could do the aggregation yourself as follows: //. HTML forms can be submitted with either a content type of application/x-www-form-urlencoded or multipart/form-data. For url encoded forms, the form attributes are encoded in the url, just like normal query parameters. For multi-part forms they are encoded in the request body, and as such are not available until the entire body has been read from the wire. Multi-part forms can also contain file uploads. If you want to retrieve the attributes of a multi-part form you should tell Vert.x that you expect to receive such a form before any of the body is read by calling setExpectMultipart with true, and then you should retrieve the actual attributes using formAttributes once the entire body has been read: server.requestHandler({ request -> request.setExpectMultipart(true) request.endHandler({ v -> // The body has now been fully read, so retrieve the form attributes def formAttributes = request.formAttributes() }) }) Vert.x can also handle file uploads which are encoded in a multi-part request body. To receive file uploads you tell Vert.x to expect a multi-part form and set an uploadHandler on the request. This handler will be called once for every upload that arrives on the server. The object passed into the handler is a HttpServerFileUpload instance. server.requestHandler({ request -> request.setExpectMultipart(true) request.uploadHandler({ upload ->.: request.customFrameHandler({ frame ->. The default HTTP status code for a response is 200, representing OK. Use setStatusCode to set a different code. You can also specify a custom status message with setStatusMessage. If you don’t specify a status message, the default one corresponding to the status code will be used. write has been queued. If you are just writing a single string or buffer to the HTTP response you can write it and end the response in a single call to the end The first call to write results in the response header being being written to the response. Consequently, if you are not using HTTP chunking then you must set the Content-Length header before writing to the response, since it will be too late otherwise. If you are using HTTP chunking you do not have to worry. This can be done in several ways: With no arguments, the response is simply ended. def response = request.response() response.write("hello world!") response.end() It can also be called with a string or buffer in the same way write is called. In this case it’s just the same as calling write with a string or buffer followed by calling end with no arguments. For example: def response = request.response() response.end("hello world!") Non keep-alive connections will be automatically closed by Vert.x when the response is ended. Keep-alive connections are not automatically closed by Vert.x by default. If you want keep-alive connections to be closed after an idle time, then you configure setIdleTimeout. HTTP/2 connections send a GOAWAY frame before closing the response.. Vert.x supports HTTP Chunked Transfer Encoding. This allows the HTTP response body to be written in chunks, and is normally used when a large response body is being streamed to a client and the total size is not known in advance. You put the HTTP response into chunked mode as follows: def response = request.response() response.setChunked(true) Default is non-chunked. When in chunked mode, each call to one of the write methods will result in a new HTTP chunk being written out. When in chunked mode you can also write HTTP response trailers to the response. These are actually written in the final chunk of the response. it to the HTTP response. Alternatively, Vert.x provides a method which allows you to serve a file from disk or the filesystem to an HTTP response in one operation. Where supported by the underlying operating system this may result in the OS directly transferring bytes from the file to the socket without being copied through user-space at all. This is done by using sendFile, and is usually more efficient for large files, but may be slower for small files. Here’s a very simple web server that serves files from the file system using sendFile: vertx.createHttpServer().requestHandler({ request -> you can use sendFile Please see the chapter about serving files from the classpath for restrictions about the classpath resolution or disabling it. When there is a need to serve just a segment of a file, say starting from a given byte, you can achieve this by doing: vertx.createHttpServer().requestHandler({ request -> def offset = 0 try { offset = java.lang.Long.parseLong(request.getParam("start")) } catch(Exception e) { // error handling... } def end = java.lang.Long.MAX_VALUE try { end = java.lang.Long.parseLong(request.getParam("end")) } catch(Exception e) { // error handling... } request.response().sendFile("web/mybigfile.txt", offset, end) }).listen(8080) You are not required to supply the length if you want to send a file starting from an offset until the end, in this case you can just do: vertx.createHttpServer().requestHandler({ request -> { println("Could not push client resource ${ar.cause()}") } }) // Send the requested resource response.sendFile("<html><head><script src=\"/main.js\"></script></head><body></body></html>") When the server is ready to push the response, the push response handler is called and the handler can send the response. The push response handler may receive a failure, for instance the client may cancel the push because it already has main.js in its cache and does not want it anymore. You can set an exceptionHandler to receive any exceptions that happens before the connection is passed to the requestHandler or to the websocketHandler, e.g during the TLS handshake. Vert.x comes with support for HTTP Compression out of the box. This means you are able to automatically compress the body of the responses before they are sent back to the client. If the client does not support HTTP compression the responses are sent back without compressing the body. This allows to handle Client that support HTTP Compression and those that not support it at the same time. To enable compression use can configure it with setCompressionSupported. By default compression is not enabled. When HTTP compression is enabled the server will check if the client includes an Accept-Encoding header which includes the supported compressions. Commonly used are deflate and gzip. Both are supported by Vert.x. If such a header is found the server will automatically compress the body of the response with one of the supported compressions and send it back to the client. Whenever the response needs to be sent without compression you can set the header content-encoding to identity: // Disable compression and send an image request.response().putHeader(io.vertx.core.http.HttpHeaders.CONTENT_ENCODING, io.vertx.core.http.HttpHeaders.IDENTITY).sendFile("/path/to/image.jpg") Be aware that compression may be able to reduce network traffic but is more CPU-intensive. To address this latter issue Vert.x allows you to tune the 'compression level' parameter that is native of the gzip/deflate compression algorithms. Compression level allows to configure gizp/deflate algorithms in terms of the compression ratio of the resulting data and the computational cost of the compress/decompress operation. The compression level is an integer value ranged from '1' to '9', where '1' means lower compression ratio but fastest algorithm and '9' means maximum compression ratio available but a slower algorithm. Using compression levels higher that 1-2 usually allows to save just some bytes in size - the gain is not linear, and depends on the specific data to be compressed - but it comports a non-trascurable cost in term of CPU cycles required to the server while generating the compressed response data ( Note that at moment Vert.x doesn’t support any form caching of compressed response data, even for static files, so the compression is done on-the-fly at every request body generation ) and in the same way it affects client(s) while decoding (inflating) received responses, operation that becomes more CPU-intensive the more the level increases. By default - if compression is enabled via setCompressionSupported - Vert.x will use '6' as compression level, but the parameter can be configured to address any case with setCompressionLevel. You create an HttpClient instance with default options as follows: def client = vertx.createHttpClient() If you want to configure options for the client, you create it as follows: def options = [ keepAlive:false ] def client = vertx.createHttpClient(options) Vert.x supports HTTP/2 over TLS h2 and over TCP h2c. By default the http client performs HTTP/1.1 requests, to perform HTTP/2 requests the setProtocolVersion must be set to HTTP_2. For h2 requests, TLS must be enabled with Application-Layer Protocol Negotiation: client = vertx.createHttpClient(options) h2c connections can also be established directly, i.e connection started with a prior knowledge, when setHttp2ClearTextUpgrade options is set to false: after the connection is established, the client will send the HTTP/2 connection preface and expect to receive the same preface from the server. The http server may not support HTTP/2, the actual version can be checked with version when the response arrives. When a clients connects to an HTTP/2 server, it sends to the server its initial settings. The settings define how the server can use the connection, the default initial settings for a client are the default values defined by the HTTP/2 RFC. pref buffer = Buffer.buffer().appendDouble(12.34d).appendLong(432L) request.end(buffer) When you’re writing to a request, the first call to write will result in the request headers being written out to the wire. The actual write is asynchronous and might not occur until some time after the call has returned. Non-chunked HTTP requests with a request body require a Content-Length header to be provided. Consequently, if you are not using chunked HTTP then you must set the Content-Length header before writing to the request, as it will be too late otherwise. If you are calling one of the end methods that take a string or buffer then Vert.x will automatically calculate and set the Content-Length header before writing the request body. If you are using HTTP chunking a. Ending a request causes any headers to be written, if they have not already been written and the request to be marked as complete. Requests can be ended in several ways. With no arguments the request is simply ended: request.end() Or a string or buffer can be provided in the call to end. This is like calling write with the string or buffer before calling end with no arguments // End the request with a string request.end("some-data") // End it with a buffer def buffer = Buffer.buffer().appendFloat(12.3f).appendInt(321) request.end(buffer) Vert.x supports HTTP Chunked Transfer Encoding for requests. This allows the HTTP request body to be written in chunks, and is normally used when a large request body is being streamed to the server, whose size is not known in advance. You put the HTTP request into chunked mode using setChunked. In chunked mode each call to write will cause a new chunk to be written to the wire. In chunked mode there is no need to set the Content-Length of the request up-front. request.setChunked(true) // Write some chunks ): request.reset() By default the NO_ERROR (0) error code is sent, another code can sent instead: request.reset(8) The HTTP/2 specification defines the list of error codes one can use. The request handler are notified of stream reset events with the request handler and response handler: request.exceptionHandler({ err -> if (err instanceof io.vertx.core.http.StreamResetException) { def reset = err println("Stream reset ${reset.getCode()}") } }) You receive an instance of HttpClientResponse into the handler that you specify in of the request methods or by setting a handler directly on the HttpClientRequest object. You can query the status code and the status message of the response with statusCode and statusMessage. body. The response handler is called when the headers of the response have been read from the wire. If the response has a body this might arrive in several pieces some time after the headers have been read. We don’t wait for all the body to arrive before calling the response handler as the response could be very large and we might be waiting a long time, or run out of memory for large responses. As parts of the response body arrive, the handler is called with a Buffer representing the piece of the body: client() One size does not fit all and the default redirection policy may not be adapted to your needs. The default redirection policy can changed with a custom implementation: client.redirectHandler({ response -> // Only follow 301 code if (response.statusCode() == 301 && response.getHeader("Location") != null) { // Compute the redirect URI is returned, the original response is processed when a future is returned, the request will be sent on its successful completion when a future is returned, the exception handler set on the request is called on its failure The returned request must be unsent so the original request handlers can be sent and the client can send it after. Most of the original request settings will be propagated to the new request: According to the HTTP 1.1 specification a client can set a header Expect: 100-Continue and send the request header before sending the rest of the request body. The server can then respond with an interim response status Status: 100 (Continue) to signify to the client that it is ok to send the rest of the body. The idea here is it allows the server to authorise and accept/reject the request before large amounts of data are sent. Sending large amounts of data if the request might not be accepted is a waste of bandwidth and ties up the server in reading data that it will just discard. Vert.x allows you to set a continueHandler on the client request object This will be called if the server sends back a Status: 100 (Continue) response to signify that it is ok to send the rest of the request. Here’s an example: def request = client.put("some-uri", { response -> println("Received response with status code ${response.statusCode()}") }) request.putHeader("Expect", "100-Continue") request.continueHandler({ v -> // OK to send rest of body request.write("Some data") request.write("Some more data") request.end() }) On the server side a Vert.x http server can be configured to automatically send back 100 Continue interim responses when it receives an Expect: 100-Continue header. This is done by setting the option setHandle100ContinueAutomatically. If you’d prefer to decide whether to send back continue responses manually, then this property should be set to false (the default), then you can inspect the headers and call writeContinue to have the client continue sending the body: httpServer.requestHandler({ request -> if (request.getHeader("Expect").equalsIgnoreCase("100-Continue")) { // Send a 100 continue response request.response().writeContinue() // The client should send the body when it receives the 100 response request.bodyHandler({ body -> // Do something with body }) request.endHandler({ v -> request.response().end() }) } }) You can also reject the request by sending back a failure status code directly: in this case the body should either be ignored or the connection should be closed (100-Continue is a performance hint and cannot be a logical protocol constraint): httpServer.requestHandler({ request -> if (request.getHeader("Expect").equalsIgnoreCase("100-Continue")) { // def rejectAndClose = true if (rejectAndClose) { // Reject with a failure code and close the connection // this is probably best with persistent connection request.response().setStatusCode(405).putHeader("Connection", "close").end() } else { // Reject with a failure code and ignore the body // this may be appropriate if the body is small request.response().setStatusCode(405)).: response.customFrameHandler({ frame -> println("Received a frame type=${frame.type()} payload${frame.payload().toString()}") }) The http client comes with support for HTTP Compression out of the box. This means the client can let the remote http server know that it supports compression, and will be able to handle compressed response bodies. An http server is free to either compress with one of the supported compression algorithms or to send the body back without compressing it at all. So this is only a hint for the Http server which it may ignore at will. To tell the http server which compression is supported by the client it will include an Accept-Encoding header with the supported compression algorithm as value. Multiple compression algorithms are supported. In case of Vert.x this will result in the following header added: Accept-Encoding: gzip, deflate The server will choose then from one of these. You can detect if a server ompressed the body by checking for the Content-Encoding header in the response sent back from it. If the body of the response was compressed via gzip it will include for example the following header: Content-Encoding: gzip To enable compression set setTryUseCompression on the options used when creating the client. By default compression is disabled. Http keep alive allows http connections to be used for more than one request. This can be a more efficient use of connections when you’re making multiple requests to the same server. For HTTP/1.x versions, the http client supports pooling of connections, allowing you to reuse connections between requests. For pooling to work, keep alive must be true using setKeepAlive on the options used when configuring the client. The default value is true. When keep alive is enabled. Vert.x will add a Connection: Keep-Alive header to each HTTP/1.0 request sent. When keep alive is disabled. Vert.x will add a Connection: Close header to each HTTP/1.1 request sent to signal that the connection will be closed after completion of the response. The maximum number of connections to pool for each server is configured using setMaxPoolSize When making a request with pooling enabled, Vert.x will create a new connection if there are less than the maximum number of connections already created for that server, otherwise it will add the request to a queue. Keep alive connections will not be closed by the client automatically. To close them you can close the client instance. Alternatively you can set idle timeout using setIdleTimeout - any connections not used within this timeout will be closed. Please note the idle timeout value is in seconds not milliseconds. The client also supports pipe-lining of requests on a connection. Pipe-lining means another request is sent on the same connection before the response from the preceding one has returned. Pipe-lining is not appropriate for all requests. To enable pipe-lining, it must be enabled using setPipelining. By default pipe-lining is disabled. When pipe-lining is enabled requests will be written to connections without waiting for previous responses to return. The number of pipe-lined requests over a single connection is limited by setPipeliningLimit. This option defines the maximum number of http requests sent to the server awaiting for a response. This limit ensures the fairness of the distribution of the client requests over the connections to the same server. HTTP/2 advocates to use a single connection to a server, by default the http client uses a single connection for each server, all the streams to the same server are multiplexed over the same connection. When the clients needs to use more than a single connection and use pooling, the setHttp2MaxPoolSize shall be used. When it is desirable to limit the number of multiplexed streams per connection and use a connection pool instead of a single connection, setHttp2MultiplexingLimit can be used. def clientOptions = [ http2MultiplexingLimit:10, http2MaxPoolSize:3 ] // Uses up to 3 connections and up to 10 streams per connection def client = vertx.createHttpClient(clientOptions) The multiplexing limit for a connection is a setting set on the client that limits the number of streams of a single connection. The effective value can be even lower if the server sets a lower limit with the SETTINGS_MAX_CONCURRENT_STREAMS setting. HTTP/2 connections will not be closed by the client automatically. To close them you can call or close the client instance. Alternatively you can set idle timeout using setIdleTimeout - any connections not used within this timeout will be closed. Please note the idle timeout value is in seconds not milliseconds. The HttpConnection offers the API for dealing with HTTP connection events, lifecycle and settings. HTTP/2 implements fully the HttpConnection API. HTTP/1.x implements partially the HttpConnection API: only the close operation, the close handler and exception handler are implemented. This protocol does not provide semantics for the other operations.") }) The configuration of an HTTP/2 is configured by the Http2Settings data object. Each endpoint must respect the settings sent by the other side of the connection. When a connection is established, the client and the server exchange initial settings. Initial settings are configured by setInitialSettings on the client and setInitialSettings on the server. The settings can be changed at any time after the connection is established: connection.updateSettings([ PING frame to the remote endpoint: def data = Buffer.buffer() (0..<8).each { i -> data.appendByte(i) } connection.ping(data, { pong -> println("Remote side replied") }) Vert.x will send automatically an acknowledgement when a PING frame is received, an handler can be set to be notified for each ping received: connection.pingHandler({ ping -> println("Got pinged by remote side") }) The handler is just notified, the acknowledgement is sent whatsoever. Such feature is aimed for implementing protocols on top of HTTP/2. Calling shutdown will send a GOAWAY frame to the remote side of the connection, asking it to stop creating streams: a client will stop doing new requests and a server will stop pushing responses. After the GOAWAY frame is sent, the connection waits some time (30 seconds by default) until all current streams closed and close the connection: connection.shutdown() The shutdownHandler notifies when all streams have been closed, the connection is not yet closed. It’s possible to just send a GOAWAY frame, the main difference with a shutdown is that it will just tell the remote side of the connection to stop creating new streams without scheduling a connection connection.goAway(0) Conversely, it is also possible to be notified when GOAWAY are received: connection.goAwayHandler({ goAway -> println("Received a go away frame") }) The shutdownHandler will be called when all current streams have been closed and the connection can be closed: connection.goAway(0) connection.shutdownHandler({ v -> // All streams are closed, close the connection connection.close() }) This applies also when a GOAWAY is received. it closes the socket for HTTP/1.x a shutdown with no delay for HTTP/2, the GOAWAY frame will still be sent before the connection is closed. * The closeHandler notifies when a connection is closed. The HttpClient can be used in a Verticle or embedded. When used in a Verticle, the Verticle should use its own client instance. More generally a client should not be shared between different Vert.x contexts as it can lead to unexpected behavior. For example a keep-alive connection will call the client handlers on the context of the request that opened the connection, subsequent requests will use the same context. When this happen Vert.x detects it and log a warn: Reusing a connection with a different context: an HttpClient is probably shared between different Verticles The HttpClient can be embedded in a non Vert.x thread like a unit test or a plain java main: the client handlers will be called by different Vert.x threads and contexts, such contexts are created as needed. For production this usage is not recommended. When several HTTP servers listen on the same port, vert.x orchestrates the request handling using a round-robin strategy. Let’s take a verticle creating a HTTP server such as: vertx.createHttpServer().requestHandler({ request -> request.response().end("Hello from server ${this}") }).listen(8080) This service is listening on the port 8080. So, when this verticle is instantiated multiple times as with: vertx run io.vertx.examples.http.sharing.HttpServerVerticle -instances 2, what’s happening ? If both verticles would bind to the same port, you would receive a socket exception. Fortunately, vert.x is handling this case for you. When you deploy another server on the same host and port as an existing server it doesn’t actually try and create a new server listening on the same host/port. It binds only once to the socket. When receiving a request it calls the server handlers following a round robin strategy. Let’s now imagine a client such as: vertx.setPeriodic(100, { l -> vertx.createHttpClient().getNow(8080, "localhost", "/", { resp -> resp.bodyHandler({ body -> println(body.toString("ISO-8859-1")) }) }) }) Vert.x delegates the requests to one of the server sequentially: Hello from i.v.e.h.s.HttpServerVerticle@1 Hello from i.v.e.h.s.HttpServerVerticle@2 Hello from i.v.e.h.s.HttpServerVerticle@1 Hello from i.v.e.h.s.HttpServerVerticle@2 ... Consequently the servers can scale over available cores while each Vert.x verticle instance remains strictly single threaded, and you don’t have to do any special tricks like writing load-balancers in order to scale your server on your multi-core machine. Vert.x http servers and clients can be configured to use HTTPS in exactly the same way as net servers. Please see configuring net servers to use SSL for more information. SSL can also be enabled/disabled per request with RequestOptions or when specifying a scheme with net.adoc. message = "hello" websocket.writeTextMessage(message) If the WebSocket message is larger than the maximum websocket frame size as configured with setMaxWebsocketFrameSize then Vert.x will split it into multiple WebSocket frames before sending it on the wire. A WebSocket message can be composed of multiple frames. In this case the first frame is either a binary or text frame followed by zero or more continuation frames. The last frame in the message is marked as final. To send a message consisting of multiple frames you create frames using WebSocketFrame.binaryFrame , WebSocketFrame.textFrame or WebSocketFrame.continuationFrame and write them to the WebSocket using writeFrame. Here’s an example for binary frames: def frame1 = WebSocketFrame.binaryFrame(buffer1, false) websocket.writeFrame(frame1) def frame2 = WebSocketFrame.continuationFrame(buffer2, false) websocket.writeFrame(frame2) // Write the final frame def frame3 = WebSocketFrame.continuationFrame(buffer2, true) websocket.writeFrame(frame3) In many cases you just want to send a websocket message that consists of a single final frame, so we provide a couple of shortcut methods to do that with writeFinalBinaryFrame and writeFinalTextFrame. Here’s an example: //. The http client supports accessing http/https URLs via a HTTP proxy (e.g. Squid) or SOCKS4a or SOCKS5 proxy. The CONNECT protocol uses HTTP/1.x but can connect to HTTP/1.x and HTTP/2 servers. Connecting to h2c (unencrypted HTTP/2 servers) is likely not supported by http proxies since they will support HTTP/1.1 only. The proxy can be configured in the HttpClientOptions by setting a ProxyOptions object containing proxy type, hostname, port and optionally username and password. Here’s an example of using an HTTP proxy: def options = [ proxyOptions:[ type:"HTTP", host:"localhost", port:3128, username:"username", password:"secret" ] ] def client = vertx.createHttpClient(options) When the client connects to an http URL, it connects to the proxy server and provides the full URL in the HTTP request ("GET HTTP/1.1"). When the client connects to an https URL, it asks the proxy to create a tunnel to the remote host with the CONNECT method. For a SOCKS5 proxy:! } }) Asynchronous locks allow you to obtain exclusive locks locally or across the cluster - this is useful when you want to do something or access a resource on only one node of a cluster at any one time. Asynchronous locks have an asynchronous API unlike most lock APIs which block the calling thread until the lock is obtained. lock = res.result() // 5 seconds later we release the lock so someone else can get it vertx.setTimer(5000, { tid -> lock.release() }) } else { // Something went wrong } }) You can also get a lock with a timeout. If it fails to obtain the lock within the timeout the handler will be called with a failure:. The Vert.x FileSystem object provides many operations for manipulating the file system. There is one file system object per Vert.x instance, and you obtain it with fileSystem. A blocking and a non blocking version of each operation is provided. The non blocking versions take a handler which is called when the operation completes or an error occurs. Here’s an example of an asynchronous copy of a file: def fs = vertx.fileSystem() // Copy file from foo.txt to bar.txt fs.copy("foo.txt", "bar.txt", { res -> if (res.succeeded()) { // Copied ok! } else { // Something went wrong } }) The blocking versions are named xxxBlocking and return the results or throw exceptions directly. In many cases, depending on the operating system and file system, some of the potentially blocking operations can return quickly, which is why we provide them, but it’s highly recommended that you test how long they take to return in your particular application before using them from an event loop, so as not to break the Golden Rule. Here’s the copy using the blocking API: def fs = vertx.fileSystem() // Copy file from foo.txt to bar.txt synchronously fs.copyBlocking("foo.txt", "bar.txt") Many operations exist to copy, move, truncate, chmod and many other file operations. We won’t list them all here, please consult the API docs for the full list. Let’s see a couple of examples using asynchronous methods: def vertx = Vertx.vertx() //. The parameters to the method are: buffer: the buffer to write. position: an integer position in the file where to write the buffer. If the position is greater or equal to the size of the file, the file will be enlarged to accommodate the offset. handler: the result handler Here is an example of random access writes: def vertx = Vertx.vertx() vertx.fileSystem().open("target/classes/hello.txt", [:], { result -> if (result.succeeded()) { def file = result.result() def buff = Buffer.buffer("foo") (0..<5).each { i -> file.write(buff, buff.length() * i, { ar -> if (ar.succeeded()) { println("Written ok!") // etc } else { System.err.println("Failed to write: ${ar.cause()}") } }) } } else { System.err.println("Cannot open file ${result.cause()}") } }) The parameters to the method are: buffer: the buffer into which the data will be read. offset: an integer offset into the buffer where the read data will be placed. position: the position in the file where to read data from. length: the number of bytes of data to read handler: the result handler Here’s an example of random access reads: def vertx = Vertx.vertx() vertx.fileSystem().open("target/classes/les_miserables.txt", [:], {()}") } }) When opening an AsyncFile, you pass an OpenOptions instance. These options describe the behavior of the file access. For instance, you can configure the file permissions with the setRead, setWrite and setPerms methods. You can also configure the behavior if the open file already exists with setCreateNew and setTruncateExisting. You can also mark the file to be deleted on close or when the JVM is shutdown with setDeleteOnClose. vertx = Vertx.vertx(). When vert.x cannot find the file on the filesystem it tries to resolve the file from the class path. Note that classpath resource paths never start with a /. Due to the fact that Java does not offer async access to classpath resources, the file is copied to the filesystem in a worker thread when the classpath resource is accessed the very first time and served from there asynchrously. When the same resource is accessed a second time, the file from the filesystem is served directly from the filesystem. The original content is served even if the classpath resource changes (e.g. in a development system). This caching behaviour can be set on the setFileResolverCachingEnabled option. The default value of this option is true unless the system property vertx.disableFileCaching is defined. The path where the files are cached is .vertx by default and can be customized by setting the system property vertx.cacheDirBase. The whole classpath resolving feature can be disabled by setting the system property vertx.disableFileCPResolving to true. Using User Datagram Protocol (UDP) with Vert.x is a piece of cake. UDP is a connection-less transport which basically means you have no persistent connection to a remote peer. Instead you can send and receive packages and the remote address is contained in each of them. Beside this UDP is not as safe as TCP to use, which means there are no guarantees that a send Datagram packet will receive it’s endpoint at all. The only guarantee is that it will either receive complete or not at all. Also you usually can’t send data which is bigger then the MTU size of your network interface, this is because each packet will be send as one packet. But be aware even if the packet size is smaller then the MTU it may still fail. At which size it will fail depends on the Operating System etc. So rule of thumb is to try to send small packets. Because of the nature of UDP it is best fit for Applications where you are allowed to drop packets (like for example a monitoring application). The benefits are that it has a lot less overhead compared to TCP, which can be handled by the NetServer and NetClient (see above).()}") }) If you want to receive packets you need to bind the DatagramSocket by calling listen(…)} on it. This way you will be able to receive DatagramPacket`s that were sent to the address and port on which the `DatagramSocket listens. you would do something like shown here: def socket = vertx.createDatagramSocket([:]) socket.listen(1234, "0.0.0.0", { asyncResult -> if (asyncResult.succeeded()) { socket.handler({ packet -> // Do something with the packet }) } else { println("Listen failed${asyncResult.cause()}") } }) Be aware that even if the {code AsyncResult} is successed it only means it might be written on the network stack, but gives no guarantee that it ever reached or will reach the remote peer at all. If you need such a guarantee then you want to use TCP with some handshaking logic build on top. Multicast allows multiple sockets to receive the same packets. This works by having the sockets join the same multicast group to which you can then send packets. We will look at how you can join a Multicast Group and receive packets in the next section. Sending multicast packets is not different. If you want to receive packets for specific Multicast group you need to bind the DatagramSocket by calling listen(…) on it to join the Multicast group. This way you will receive DatagramPackets that were sent to the address and port on which the DatagramSocket listens and also to those sent to the Multicast group. and also receive packets for the Multicast group 230.0.0.1 you would do something like -> -> if (asyncResult2.succeeded()) { // will now receive packets for group // do some work socket.unlistenMulticastGroup("230.0.0.1", { asyncResult3 -> println("Unlisten succeeded? ${asyncResult3.succeeded()}") }) } else { println("Listen failed${asyncResult2.cause()}") } }) } else { println("Listen failed${asyncResult.cause()}") } }) Beside unlisten a Multicast address it’s also possible to just block multicast for a specific sender address. Be aware this only work on some Operating Systems and kernel versions. So please check the Operating System documentation if it’s supported. This an expert feature. To block multicast from a specific address you can call blockMulticastGroup(…) on the DatagramSocket like shown here:. You can find out the local address of the socket (i.e. the address of this side of the UDP Socket) by calling localAddress. This will only return an InetSocketAddress if you bound the DatagramSocket with listen(…) before, otherwise it will return null. Often you will find yourself in situations where you need to obtain DNS informations in an asynchronous fashion. Unfortunally this is not possible with the API that is shipped with the Java Virtual Machine itself. Because of this Vert.x offers it’s own API for DNS resolution which is fully asynchronous. To obtain a DnsClient instance you will create a new via the Vertx instance. ]) Try to lookup the A (ipv4) or AAAA (ipv6) record for a given name. The first which is returned will be used, so it behaves the same way as you may be used from when using "nslookup" on your operation system. To lookup the A / AAAA record for "vertx.io" you would typically use it like: def client = vertx.createDnsClient(53, "9.9.9.9") client.lookup("vertx.io", { ar -> if (ar.succeeded()) { println(ar.result()) } else { println("Failed to resolve entry${ar.cause()}") } }) Try to lookup the A (ipv4("vertx.io", { ar -> if (ar.succeeded()) { println(ar.result()) } else { println("Failed to resolve entry${ar.cause()}") } }) Try to lookup the AAAA (ipv6( { println("Failed to resolve entry${ar.cause()}") } }) Be aware that the List will contain the MxRecord sorted by the priority of them, which means MX records with smaller priority coming first in the List. The MxRecord allows you to access the priority and the name of the MX record by offer methods for it like: record.priority() record.name() { println("Failed to resolve entry${ar.cause()}") } }) Be aware that the List will contain the SrvRecords sorted by the priority of them, which means SrvRecords with smaller priority coming first in the List. record.priority() record.name() record.weight() record.port() record.protocol() record.service() record.target() Please refer to the API docs for the exact details.()}") } }) Try to do a reverse lookup for an ipaddress. This is basically the same as resolve a PTR record, but allows you to just pass in the ipaddress and not a valid PTR query string. To do a reverse lookup for the ipaddress 10.0.0.1 do something similar like this: def client = vertx.createDnsClient(53, "9.9.9.9") client.reverseLookup("10.0.0.1", { ar -> if (ar.succeeded()) { def record = ar.result() println(record) } else { println("Failed to resolve entry${ar.cause()}") } }) As you saw in previous sections the DnsClient allows you to pass in a Handler which will be notified with an AsyncResult once the query was complete. In case of an error it will be notified with a DnsException which will hole a DnsResponseCode that indicate why the resolution failed. This DnsResponseCode can be used to inspect the cause in more detail. Possible DnsResponseCodes are: streams.adoc package was manipulating Buffer objects exclusively. From now, streams are not coupled to buffers anymore and they work with any kind of objects. In Vert.x, write calls return immediately, and writes are queued internally. It’s not hard to see that if you write to an object faster than it can actually write the data to its underlying resource, then the write queue can grow unbounded - eventually resulting in memory exhaustion. To solve this problem a simple flow control (back-pressure) capability is provided by some objects in the Vert.x API. Any flow control aware object that can be written-to implements WriteStream, while any flow control object that can be read-from is said to implement ReadStream. Let’s take an example where we want to read from a ReadStream then write the data to a WriteStream. A very simple example would be reading from a NetSocket then writing back to the same NetSocket - since NetSocket implements both ReadStream and WriteStream. Note that this works between any ReadStream and WriteStream compliant object, including HTTP requests, HTTP responses, async files I/O, WebSockets, etc. A naive way to do this would be to directly take the data that has been read and immediately write it to the NetSocket: def server = vertx.createNetServer([ port:1234, host:"localhost" ]) server.connectHandler({ sock -> sock.handler({ buffer -> // Write the data straight back sock.write(buffer) }) }).listen() There is a problem with the example above: if data is read from the socket faster than it can be written back to the socket, it will build up in the write queue of the NetSocket, eventually running out of RAM. This might happen, for example if the client at the other end of the socket wasn’t reading fast enough, effectively putting back-pressure on the connection. Since NetSocket implements WriteStream, we can check if the WriteStream is full before writing to it: def server = vertx.createNetServer([ port:1234, host:"localhost" ]) server.connectHandler({ sock -> sock.handler({ buffer -> if (!sock.writeQueueFull()) { sock.write(buffer) } }) }).listen() This example won’t run out of RAM but we’ll end up losing data if the write queue gets full. What we really want to do is pause the NetSocket when the write queue is full: def server = vertx.createNetServer([ port:1234, host:"localhost" ]) server.connectHandler({ sock -> sock.handler({ buffer -> sock.write(buffer) if (sock.writeQueueFull()) { sock.pause() } }) }).listen() We’re almost there, but not quite. The NetSocket now gets paused when the file is full, but we also need to unpause it when the write queue has processed its backlog: def server = vertx.createNetServer([ port:1234, host:"localhost" ]) server.connectHandler({ sock -> sock.handler({ buffer -> sock.write(buffer) if (sock.writeQueueFull()) { sock.pause() sock.drainHandler({ done -> sock.resume() }) } }) }).listen() And there we have it. The drainHandler event handler will get called when the write queue is ready to accept more data, this resumes the NetSocket that allows more data to be read. Wanting to do this is quite common while writing Vert.x applications, so we Functions: write: write an object to the WriteStream. This method will never block. Writes are queued internally and asynchronously written to the underlying resource. setWriteQueueMaxSize: set the number of object at which the write queue is considered full, and the method writeQueueFull. The record parser allows you to easily parse protocols which are delimited by a sequence of bytes, or fixed size records. It transforms a sequence of input buffer to a sequence of buffer structured as configured (either fixed size or separated records). For example, if you have a simple ASCII text protocol delimited by '\n' and the input is the following: buffer1:HELLO\nHOW ARE Y buffer2:OU?\nI AM buffer3: DOING OK buffer4:\n The record parser would produce buffer1:HELLO buffer2:HOW ARE YOU? buffer3:I AM DOING OK Let’s see the associated code:. You can easily parse JSON structures but that requires to provide the JSON content at once, but it may not be convenient when you need to parse very large structures. The non-blocking JSON parser is an event driven parser able to deal with very large structures. It transforms a sequence of input buffer to a sequence of JSON parse events. Code not translatable The parser is non-blocking and emitted events are driven by the input buffers. def parser = JsonParser.newParser() // start array event // start object event // "firstName":"Bob" event parser.handle(Buffer.buffer("[{\"firstName\":\"Bob\",")) // "lastName":"Morane" event // end object event parser.handle(Buffer.buffer("\"lastName\":\"Morane\"},")) // start object event // "firstName":"Luke" event // "lastName":"Lucky" event // end object event parser.handle(Buffer.buffer("{\"firstName\":\"Luke\",\"lastName\":\"Lucky\"}")) // end array event parser.handle(Buffer.buffer("]")) // Always call end parser.end() Event driven parsing provides more control but comes at the price of dealing with fine grained events, which can be inconvenient sometimes. The JSON parser allows you to handle JSON structures as values when it is desired: parser = JsonParser.newParser() parser.exceptionHandler({ err -> // Catch any parsing or decoding error }) The parser also parses json streams: concatenated json streams: {"temperature":30}{"temperature":50} line delimited json streams: {"an":"object"}\r\n3\r\n"a string"\r\nnull For more details, check out the JsonParser class. Most Vert.x objects are safe to access from different threads. However performance is optimised when they are accessed from the same context they were created from. For example if you have deployed a verticle which creates a NetServer which provides NetSocket instances in it’s handler, then it’s best to always access that socket instance from the event loop of the verticle. If you stick to the standard Vert.x verticle deployment model and avoid sharing objects between verticles then this should be the case without you having to think about it. By default Vert.x does not record any metrics. Instead it provides an SPI for others to implement which can be added to the classpath. The metrics SPI is an advanced feature which allows implementers to capture events from Vert.x in order to gather metrics. For more information on this, please consult the API Documentation. You can also specify a metrics factory programmatically if embedding Vert.x using setFactory. The vertx command is used to interact with Vert.x from the command line. It’s main use is to run Vert.x verticles. To do this you need to download and install a Vert.x distribution, and add the bin directory of the installation to your PATH environment variable. Also make sure you have a Java 8 JDK on your PATH. You can run raw Vert.x verticles directly from the command line using vertx run. Here is a couple of examples of the run command: vertx run my-verticle.js (1) vertx run my-verticle.groovy (2) vertx run my-verticle.rb (3) vertx run io.vertx.example.MyVerticle (4) vertx run io.vertx.example.MVerticle -cp my-verticle.jar (5) vertx run MyVerticle.java (6) Deploys a JavaScript verticle Deploys a Groovy verticle Deploys a Ruby verticle Deploys an already compiled Java verticle. Classpath root is the current directory Deploys a verticle packaged in a Jar, the jar need to be in the classpath Compiles the Java source and deploys it As you can see in the case of Java, the name can either be the fully qualified class name of the verticle, or you can specify the Java Source file directly and Vert.x compiles it for you. You can also prefix the verticle with the name of the language implementation to use. For example if the verticle is a compiled Groovy class, you prefix it with groovy: so that Vert.x knows it’s a Groovy class not a Java class. vertx run groovy:io.vertx.example.MyGroovyVerticle The vertx run command can take a few optional parameters, they are: -conf <config_file> - Provides some configuration to the verticle. config_file is the name of a text file containing a JSON object that represents the configuration for the verticle. This is optional. -cp <path> - The path on which to search for the verticle and any other resources used by the verticle. This defaults to . (current directory). If your verticle references other scripts, classes or other resources (e.g. jar files) then make sure these are on this path. The path can contain multiple path entries separated by : (colon) or ; (semi-colon) depending on the operating system. Each path entry can be an absolute or relative path to a directory containing scripts, or absolute or relative filenames for jar or zip files. An example path might be -cp classes:lib/otherscripts:jars/myjar.jar:jars/otherjar.jar. Always use the path to reference any resources that your verticle requires. Do not put them on the system classpath as this can cause isolation issues between deployed verticles. -instances <instances> - The number of instances of the verticle to instantiate. Each verticle instance is strictly single threaded so to scale your application across available cores you might want to deploy more than one instance. If omitted a single instance will be deployed. -worker - This option determines whether the verticle is a worker verticle or not. -cluster - This option determines whether the Vert.x instance will attempt to form a cluster with other Vert.x instances on the network. Clustering Vert.x instances allows Vert.x to form a distributed event bus with other nodes. Default is false (not clustered). -cluster-port - If the cluster option has also been specified then this determines which port will be used for cluster communication with other Vert.x instances. Default is 0 - which means 'choose a free random port'. You don’t usually need to specify this parameter unless you really need to bind to a specific port. -cluster-host - If the cluster option has also been specified then this determines which host address will be used for cluster communication with other Vert.x instances. By default it will try and pick one from the available interfaces. If you have more than one interface and you want to use a specific one, specify it here. -ha - if specified the verticle will be deployed as high availability (HA) deployment. See related section for more details -quorum - used in conjunction with -ha. It specifies the minimum number of nodes in the cluster for any HA deploymentIDs to be active. Defaults to 0. -hagroup - used in conjunction with -ha. It specifies the HA group this node will join. There can be multiple HA groups in a cluster. Nodes will only failover to other nodes in the same group. The default value is ` __DEFAULT__` You can also set system properties using: -Dkey=value. Here are some more examples: Run a JavaScript verticle server.js with default settings vertx run server.js Run 10 instances of a pre-compiled Java verticle specifying classpath vertx run com.acme.MyVerticle -cp "classes:lib/myjar.jar" -instances 10 Run 10 instances of a Java verticle by source file vertx run MyVerticle.java -instances 10 Run 20 instances of a ruby worker verticle vertx run order_worker.rb -instances 20 -worker Run two JavaScript verticles on the same machine and let them cluster together with each other and any other servers on the network vertx run handler.js -cluster vertx run sender.js -cluster Run a Ruby verticle passing it some config vertx run my_verticle.rb -conf my_verticle.conf Where my_verticle.conf might contain something like: { "name": "foo", "num_widgets": 46 } The config will be available inside the verticle via the core API. When using the high-availability feature of vert.x you may want to create a bare instance of vert.x. This instance does not deploy any verticles when launched, but will receive a verticle if another node of the cluster dies. To create a bare instance, launch: vertx bare Depending on your cluster configuration, you may have to append the cluster-host and cluster-port parameters. A fat jar is an executable jar embedding its dependencies. This means you don’t have to have Vert.x pre-installed on the machine on which you execute the jar. Like any executable Java jar it can be executed with. java -jar my-application-fat.jar There is nothing really Vert.x specific about this, you could do this with any Java application You can either create your own main class and specify that in the manifest, but it’s recommended that you write your code as verticles and use the Vert.x Launcher class ( io.vertx.core.Launcher) as your main class. This is the same main class used when running Vert.x at the command line and therefore allows you to specify command line arguments, such as -instances in order to scale your application more easily. To deploy your verticle in a fatjar like this you must have a manifest with: Main-Class set to io.vertx.core.Launcher Main-Verticle specifying the main verticle (fully qualified class name or script file name) You can also provide the usual command line arguments that you would pass to vertx run: java -jar my-verticle-fat.jar -cluster -conf myconf.json java -jar my-verticle-fat.jar -cluster -conf myconf.json -cp path/to/dir/conf/cluster_xml A fat jar executes the run command, by default. To display the vert.x version, just launch: vertx version The vertx command line and the Launcher also provide other commands in addition to run and version: You can create a bare instance using: vertx bare # or java -jar my-verticle-fat.jar bare You can also start an application in background using: java -jar my-verticle-fat.jar start -Dvertx-id=my-app-name If my-app-name is not set, a random id will be generated, and printed on the command prompt. You can pass run options to the start command: java -jar my-verticle-fat.jar start -Dvertx-id=my-app-name -cluster Once launched in background, you can stop it with the stop command: java -jar my-verticle-fat.jar stop my-app-name You can also list the vert.x application launched in background using: java -jar my-verticle-fat.jar list The start, stop and list command are also available from the vertx tool. The start` command supports a couple of options: vertx-id : the application id, uses a random UUID if not set java-opts : the Java Virtual Machine options, uses the JAVA_OPTS environment variable if not set. redirect-output : redirect the spawned process output and error streams to the parent process streams. If option values contain spaces, don't forget to wrap the value between `""` (double-quotes). As the `start` command spawns a new process, the java options passed to the JVM are not propagated, so you **must** use `java-opts` to configure the JVM (`-X`, `-D`...). If you use the `CLASSPATH` environment variable, be sure it contains all the required jars (vertx-core, your jars and all the dependencies). The set of commands is extensible, refer to the Extending the vert.x Launcher section. When developing it may be convenient to automatically redeploy your application upon file changes. The vertx command line tool and more generally the Launcher class offers this feature. Here are some examples: vertx run MyVerticle.groovy --redeploy="**/*.groovy" --launcher-class=io.vertx.core.Launcher vertx run MyVerticle.groovy --redeploy="**/*.groovy,**/*.rb" --launcher-class=io.vertx.core.Launcher java io.vertx.core.Launcher run org.acme.MyVerticle --redeploy="**/*.class" --launcher-class=io.vertx.core .Launcher -cp ... The redeployment process is implemented as follows. First your application is launched as a background application (with the start command). On matching file changes, the process is stopped and the application is restarted. This avoids leaks, as the process is restarted. To enable the live redeploy, pass the --redeploy option to the run command. The --redeploy indicates the set of file to watch. This set can use Ant-style patterns (with **, * and ?). You can specify several sets by separating them using a comma ( ,). Patterns are relative to the current working directory. Parameters passed to the run command are passed to the application. Java Virtual Machine options can be configured using --java-opts. For instance, to pass the the conf parameter or a system property, you need to use: --java-opts="-conf=my-conf.json -Dkey=value" The --launcher-class option determine with with main class the application is launcher. It’s generally Launcher, but you have use you own main. The redeploy feature can be used in your IDE: Eclipse - create a Run configuration, using the io.vertx.core.Launcher class a main class. In the Program arguments area (in the Arguments tab), write run your-verticle-fully-qualified-name --redeploy=**/*.java --launcher-class=io.vertx.core.Launcher. You can also add other parameters. The redeployment works smoothly as Eclipse incrementally compiles your files on save. IntelliJ - create a Run configuration (Application), set the Main class to io.vertx.core.Launcher. In the Program arguments write: run your-verticle-fully-qualified-name --redeploy=**/*.class --launcher-class=io.vertx.core.Launcher. To trigger the redeployment, you need to make the project or the module explicitly (Build menu → Make project). To debug your application, create your run configuration as a remote application and configure the debugger using --java-opts. However, don’t forget to re-plug the debugger after every redeployment as a new process is created every time. You can also hook your build process in the redeploy cycle: java -jar target/my-fat-jar.jar --redeploy="**/*.java" --on-redeploy="mvn package" java -jar build/libs/my-fat-jar.jar --redeploy="src/**/*.java" --on-redeploy='./gradlew shadowJar' The "on-redeploy" option specifies a command invoked after the shutdown of the application and before the restart. So you can hook your build tool if it updates some runtime artifacts. For instance, you can launch gulp or grunt to update your resources. Don’t forget that passing parameters to your application requires the --java-opts param: java -jar target/my-fat-jar.jar --redeploy="**/*.java" --on-redeploy="mvn package" --java-opts="-Dkey=val" java -jar build/libs/my-fat-jar.jar --redeploy="src/**/*.java" --on-redeploy='./gradlew shadowJar' --java-opts="-Dkey=val" The redeploy feature also supports the following settings: redeploy-scan-period : the file system check period (in milliseconds), 250ms by default redeploy-grace-period : the amount of time (in milliseconds) to wait between 2 re-deployments, 1000ms by default redeploy-termination-period : the amount of time to wait after having stopped the application (before launching user command). This is useful on Windows, where the process is not killed immediately. The time is given in milliseconds. 0 ms by default. In Vert.x a cluster manager is used for various functions including: Discovery and group membership of Vert.x nodes in a cluster Maintaining cluster wide topic subscriber lists (so we know which nodes are interested in which event bus addresses) Distributed Map support Distributed Locks Distributed Counters Cluster managers do not handle the event bus inter-node transport, this is done directly by Vert.x with TCP connections. The default cluster manager used in the Vert.x distributions is one that uses Hazelcast but this can be easily replaced by a different implementation as Vert.x cluster managers are pluggable. A cluster manager must implement the interface ClusterManager. Vert.x locates cluster managers at run-time by using the Java Service Loader functionality to locate instances of ClusterManager on the classpath. If you are using Vert.x at the command line and you want to use clustering you should make sure the lib directory of the Vert.x installation contains your cluster manager jar. If you are using Vert.x from a Maven or Gradle project just add the cluster manager jar as a dependency of your project. You can also specify cluster managers programmatically if embedding Vert.x using setClusterManager. logging documentation. Vert.x also provides a slightly more convenient way to specify a configuration file without having to set a system property. Just provide a JUL config file with the name vertx-default-jul-logging.properties on your classpath (e.g. inside your fatjar) and Vert.x will use that to configure); If, when you start your application, you see the following message: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See for further details. It means that you have SLF4J-API in your classpath but no actual binding. Messages logged with SLF4J will be dropped. You should add a binding to your classpath. Check to pick a binding and configure it. Be aware that Netty looks for the SLF4-API jar and uses it by default. If your logs show a bunch of: io.vertx.core.net.impl.ConnectionBase SEVERE: java.io.IOException: Connection reset by peer It means that the client is resetting the HTTP connection instead of closing it. This message also indicates that you may have not consumed the complete payload (the connection was cut before you were able to).". def vertx = Vertx.vertx([ addressResolverOptions:[ servers:[ "192.168.0.1", "192.168.0.2:40000" ] ] ]) The default port of a DNS server is 53, when a server uses a different port, this port can be set using a colon delimiter: 192.168.0.2:4. The hosts file of the operating system is used to perform an hostname lookup for an ipaddress. An alternative hosts file can be used instead: def vertx = Vertx.vertx([ addressResolverOptions:[ hostsPath:"/path/to/hosts" ] ]) By default the resolver will use the system DNS search domains from the environment. Alternatively an explicit search domain list can be provided: def vertx = Vertx.vertx([ addressResolverOptions:[ searchDomains:[ "foo.com", "bar.com" ] ] ]) Vert.x allows you to run your verticles with high availability (HA) support. In that case, when a vert.x instance running a verticle dies abruptly, the verticle is migrated to another vertx instance. The vert.x instances must be in the same cluster. When vert.x runs with HA enabled, if a vert.x instance where a verticle runs fails or dies, the verticle is redeployed automatically on another vert.x instance of the cluster. We call this verticle fail-over. To run vert.x with the HA enabled, just add the -ha flag to the command line: vertx run my-verticle.js -ha Now for HA to work, you need more than one Vert.x instances in the cluster, so let’s say you have another Vert.x instance that you have already started, for example: vertx run my-other-verticle.js -ha If the Vert.x instance that is running my-verticle.js now dies (you can test this by killing the process with kill -9), the Vert.x instance that is running my-other-verticle.js will automatic deploy my-verticle .js so now that Vert.x instance is running both verticles. You can also start bare Vert.x instances - i.e. instances that are not initially running any verticles, they will also failover for nodes in the cluster. To start a bare instance you simply do: vertx run -ha When using the -ha switch you do not need to provide the -cluster switch, as a cluster is assumed if you want HA. When running a Vert.x instance with HA you can also optional specify a HA group. A HA group denotes a logical group of nodes in the cluster. Only nodes with the same HA group will failover onto one another. If you don’t specify a HA group the default group __DEFAULT__ is used. To specify an HA group you use the -hagroup switch when running the verticle, e.g. vertx run my-verticle.js -ha -hagroup my-group Let’s look at an example: In a first terminal: vertx run my-verticle.js -ha -hagroup g1 In a second terminal, let’s run another verticle using the same group: vertx run my-other-verticle.js -ha -hagroup g1 Finally, in a third terminal, launch another verticle using a different group: vertx run yet-another-verticle.js -ha -hagroup g2 If we kill the instance in terminal 1, it will fail over to the instance in terminal 2, not the instance in terminal 3 as that has a different group. If we kill the instance in terminal 3, it won’t get failed over as there is no other vert.x instance in that group. The HA implementation also supports quora. A quorum is the minimum number of votes that a distributed transaction has to obtain in order to be allowed to perform an operation in a distributed system. When starting a Vert.x instance you can instruct it that it requires a quorum before any HA deployments will be deployed. In this context, a quorum is a minimum number of nodes for a particular group in the cluster. Typically you chose your quorum size to Q = 1 + N/2 where N is the number of nodes in the group. If there are less than Q nodes in the cluster the HA deployments will undeploy. They will redeploy again if/when a quorum is re-attained. By doing this you can prevent against network partitions, a.k.a. split brain. To run vert.x instances with a quorum you specify -quorum on the command line, e.g. In a first terminal: vertx run my-verticle.js -ha -quorum 3 At this point the Vert.x instance will start but not deploy the module (yet) because there is only one node in the cluster, not 3. In a second terminal: vertx run my-other-verticle.js -ha -quorum 3 At this point the Vert.x instance will start but not deploy the module (yet) because there are only two nodes in the cluster, not 3. In a third console, you can start another instance of vert.x: vertx run yet-another-verticle.js -ha -quorum 3 Yay! - we have three nodes, that’s a quorum. At this point the modules will automatically deploy on all instances. If we now close or kill one of the nodes the modules will automatically undeploy on the other nodes, as there is no longer a quorum. Quora can also be used in conjunction with ha groups. In that case, quora are resolved for each particular group. Vert.x can run with native transports (when available) on BSD (OSX) and Linux: def vertx = Vertx.vertx([ preferNativeTransport:true ]) // True when native is available def usingNative = vertx.isNativeTransportEnabled() println("Running with native: ${usingNative}") support domain sockets for NetServer: // Only available on BSD and Linux vertx.createNetServer().connectHandler({ so -> // Handle application }).listen(SocketAddress.domainSocketAddress("/var/tmp/myservice.sock")) As well as NetClient: def netClient = vertx.createNetClient() // Only available on BSD and Linux netClient.connect(SocketAddress.domainSocketAddress("/var/tmp/myservice.sock"), { ar -> if (ar.succeeded()) { // Connected } else { ar.cause().printStackTrace() } }) Vert.x is a toolkit, not an opinionated framework where we force you to do things in a certain way. This gives you great power as a developer but with that comes great responsibility. As with any toolkit, it’s possible to write insecure applications, so you should always be careful when developing your application especially if it’s exposed to the public (e.g. over the internet). If writing a web application it’s highly recommended that you use Vert.x-Web instead of Vert.x core directly for serving resources and handling file uploads. Vert.x-Web normalises the path in requests to prevent malicious clients from crafting URLs to access resources outside of the web root. Similarly for file uploads Vert.x-Web provides functionality for uploading to a known place on disk and does not rely on the filename provided by the client in the upload which could be crafted to upload to a different place on disk. Vert.x core itself does not provide such checks so it would be up to you as a developer to implement them yourself. When clustering the event bus between different Vert.x nodes on a network, the traffic is sent un-encrypted across the wire, so do not use this if you have confidential data to send and your Vert.x nodes are not on a trusted network. Any service can have potentially vulnerabilities whether it’s written using Vert.x or any other toolkit so always follow security best practice, especially if your service is public facing. For example you should always run them in a DMZ and with an user account that has limited rights in order to limit the extent of damage in case the service was compromised. Vert.x Core provides an API for parsing command line arguments passed to programs. It’s also able to print help messages detailing the options available for a command line tool. Even if such features are far from the Vert.x core topics, this API is used in the Launcher class that you can use in fat-jar and in the vertx command line tools. In addition, it’s polyglot (can be used from any supported language) and is used in Vert.x Shell. Vert.x CLI provides a model to describe your command line interface, but also a parser. This parser supports different types of syntax:) Using the CLI api is a 3-steps process: The definition of the command line interface The parsing of the user command line The query / interrogationName:"target" ]) As you can see, you can create a new CLI using CLI.create. The passed string is the name of the CLI. Once created you can set the summary and description. The summary is intended to be short (one line), while the description can contain more details. Each option and argument are also added on the CLI object using the addArgument and addOption methods. An Option is a command line parameter identified by a key present in the user command line. Options must have at least a long name or a short name. Long name are generally used using a -- prefix, while short names are used with a single -. Options can get a description displayed in the usage (see below). Options can receive 0, 1 or several values. An option receiving 0 values is a flag, and must be declared using setFlag. By default, options receive a single value, however, you can configure the option to receive several values using setMultiValued:. Unlike options, arguments do not have a key and are identified by their index. For example, in java com.acme.Foo, com.acme.Foo is an argument. Arguments do not have a name, there are identified using a 0-based index. The first parameter has the index 0:Name:"arg2" ]) The argName is optional and used in the usage message. be hidden using setHidden be mandatory using setRequired have a default value using setDefaultValue receive several values using setMultiValued - only the last argument can be multi-valued. Arguments can also be instantiated from their JSON form. commandLine = cli.parse(userCommandLineArguments) The parse method returns a CommandLine object containing the values. By default, it validates the user command line and checks that each mandatory options and arguments have been set as well as the number of values received by each option. You can disable the validation by passing false as second parameter of parse. This is useful if you want to check an argument or option is present even if the parsed command line is invalid. You can check whether or not the CommandLine is valid using isValid. public void run() throws CLIException { System.out.println("Hello " + name); } } You also need an implementation of CommandFactory: public class HelloCommandFactory extends DefaultCommandFactory<HelloCommand> { public HelloCommandFactory() { super(HelloCommand.class); } } Then, create the src/main/resources/META-INF/services/io.vertx.core.spi.launcher.CommandFactory and add a line indicating the fully qualified name of the factory: io.vertx.core.launcher.example.HelloCommandFactory Builds the jar containing the command. Be sure to includes the SPI file ( META-INF/services/io.vertx.core.spi.launcher.CommandFactory). Then, place the jar containing the command into the classpath of your fat-jar (or include it inside) or in the lib directory of your vert.x distribution, and you would be able to execute: vertx hello vert.x java -jar my-fat-jar.jar hello vert.x To use the Launcher class in a fat-jar just set the Main-Class of the MANIFEST to io.vertx.core.Launcher. In addition, set the Main-Verticle MANIFEST entry to the name of your main verticle. By default, it executed the run command. However, you can configure the default command by setting the Main-Command MANIFEST entry. The default command is used if the fat jar is launched without a command. You can also create a sub-class of Launcher to start your application. The class has been designed to be easily extensible. customize the vert.x configuration in beforeStartingVertx retrieve the vert.x instance created by the "run" or "bare" command by overriding afterStartingVertx configure the default verticle and command with getMainVerticle When Vert.x needs to read a file from the classpath (embedded in a fat jar, in a jar form the classpath or a file that is on the classpath), it copies it to a cache directory. The reason behind this is simple: reading a file from a jar or from an input stream is blocking. So to avoid to pay the price every time, Vert.x copies the file to its cache directory and reads it from there every subsequent read. This behavior can be configured. First, by default, Vert.x uses $CWD/.vertx as cache directory. It creates a unique directory inside this one to avoid conflicts. This location can be configured by using the vertx.cacheDirBase system property. For instance if the current working directory is not writable (such as in an immutable container context), launch your application with: vertx run my.Verticle -Dvertx.cacheDirBase=/tmp/vertx-cache # or java -jar my-fat.jar vertx.cacheDirBase=/tmp/vertx-cache When you are editing resources such as HTML, CSS or JavaScript, this cache mechanism can be annoying as it serves only the first version of the file (and so you won’t see your edits if you reload your page). To avoid this behavior, launch your application with -Dvertx.disableFileCaching=true. With this setting, Vert.x still uses the cache, but always refresh the version stored in the cache with the original source. So if you edit a file served from the classpath and refresh your browser, Vert.x reads it from the classpath, copies it to the cache directory and serves it from there. Do not use this setting in production, it can kill your performances. Finally, you can disable completely the cache by using -Dvertx.disableFileCPResolving=true. This setting is not without consequences. Vert.x would be unable to read any files from the classpath (only from the file system). Be very careful when using this settings.
http://vertx.io/docs/vertx-core/groovy/
CC-MAIN-2018-09
refinedweb
19,167
57.57
Working With Arrays in Thymeleaf Last modified: November 6, 2018 1. Overview In this quick tutorial, we’re going to see how we can use arrays in Thymeleaf. For easy setup, we’re going to use a spring-boot initializer to bootstrap our application. The basics of Spring MVC and Thymeleaf can be found here. 2. Thymeleaf Dependency In our pom.xml file, the only dependencies we need to add are SpringMVC and Thymeleaf: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> 3. The Controller For simplicity, let’s use a controller with only one method which handles GET requests. This responds by passing an array to the model object which will make it accessible to the view: @Controller public class ThymeleafArrayController { @GetMapping("/arrays") public String arrayController(Model model) { String[] continents = { "Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "Sourth America" }; model.addAttribute("continents", continents); return "continents"; } } 4. The View In the view page, we’re going to access the array continents by the name we pass it with (continents) from our controller above. 4.1. Properties and Indexes One of the first property we’re going to inspect is the length of the array. This is how we can check it: <p>...<span th:</span>...</p> And looking at the snippet of code above, which is from the view page, we should notice the use of the keyword th:text. We used it to print the value of the variable inside the curly braces, in this case, the length of the array. Consequently, we access the value of each element of the array continents by its index just like we use to do within our normal Java code: <ol> <li th:</li> <li th:</li> <li th:</li> <li th:</li> <li th:</li> <li th:</li> <li th:</li> </ol> As we’ve seen in the above code fragment, each element is accessible through its index. We can go here to learn more about expressions in Thymeleaf. 4.2. Iteration Similarly, we can iterate over the elements the array sequentially. In Thymeleaf, here’s how we can achieve that: <ul th: <li th:</li> </ul> When using th:each keyword to iterate over the element of an array, we’re not restricted to using list tags only. We can use any HTML tag capable of displaying text on the page. For example: <h4 th:</h4> In the above code snippet, each element is going to be displayed on its own separate <h4></h4> tag. 4.3. Utility Functions Finally, we’re going to employ the use of utility class functions to examine some other properties of the array. Let’s take a look at this: <p>The greatest <span th:</span> continents.</p> <p>Europe is a continent: <span th:</span>.</p> <p>Array of continents is empty <span th:</span>.</p> We query the length of the array first, and then check whether Europe is an element of the array continents. Lastly, we check that the array continents is empty or not. 5. Conclusion In this article, we’ve learned how to work with an array in Thymeleaf by checking its length and accessing its elements using an index. We have also learned how to iterate over its elements within Thymeleaf. Lastly, we have seen the use of utility functions to inspect other properties of an array. And, as always, the complete source code of this article can be found over on Github.
https://www.baeldung.com/thymeleaf-arrays
CC-MAIN-2019-22
refinedweb
593
63.09
26 September 2012 16:33 [Source: ICIS news] By Heng Hui ?xml:namespace> The The import market swung from backwardation to contango. Spot methanol prices in northeast and southeast Asia snapped more than four months of downtrend, rising to $355-370/tonne (€273-285/tonne) CFR (cost and freight) on 14 September, up by $5-9/tonne from the previous week, according to ICIS. Prices were around $360-370/tonne In the key China market, import prices of methanol were at $356-364/tonne CFR China last week, rebounding from $350-355/tonne in the previous week, but about 14% lower from the year’s high recorded on 4 May, ICIS data showed. Speculative trades in the In August, the country imported nearly 420,000 tonnes of methanol, representing a 21% increase from July, industry sources said. Official statistics from China Customs on August methanol imports are due for release at the end of September. A decision by some Chinese oil majors not to import Iranian methanol might lead to a supply crunch in the country, since With Prices in the Indian market have been stable to weak because producers are saddled with inventory. In the week ended 14 September, Indian methanol prices were assessed at $305-325/tonne CFR (cost of freight) Offers were as low as $300/tonne CFR India on 21 September. Buyers said their bids were at $295/tonne CFR India, based on a recalculation of what they can sell for in their domestic markets. The 8.5% customs duty and charges of storage, customs clearance, surveying fees and the 3.5% contractual premium from the published spot prices are deducted from the local domestic prices to arrive at this figure. But regional sellers are not under pressure to cut prices since they could divert cargoes to other regions where the netbacks are higher, market players said. Methanol demand picked up in August, in line with increased production of downstream formaldehyde, acetic acid, dimethyl formamide, monomethyl acrylate, dimethyl ether in The country is expected to beef up local production to make up for the shortfall of imports, market observers said. In July 2012, Methanol prices in the region had been weakening since May, weighed down by the off-peak season demand, until recently when the Chinese methanol futures took the cue from the buoyant energy prices. Buyers are inclined to lock in and conclude deals at fixed prices, but sellers preferred formula-based pricing on transactions seeing that the market is on an uptrend. But the expected continuous increase in methanol spot prices may not mean higher real demand, according to some market participants. Notwithstanding recent gains, methanol trades in southeast Asia have remained thin even after market players in Market players said most buyers have been waiting on the sidelines for a clearer price direction to
http://www.icis.com/Articles/2012/09/26/9598545/insight-asia-methanol-likely-to-trend-up-on-bullish-sentiment.html
CC-MAIN-2014-42
refinedweb
471
53.24
john levon sun com wrote: > Avoid passing NULL to printf %s specifier This looks fine. Thanks! > diff --git a/src/internal.h b/src/internal.h > --- a/src/internal.h > +++ b/src/internal.h > @@ -115,6 +115,8 @@ > #define ATTRIBUTE_RETURN_CHECK > #endif /* __GNUC__ */ > > +#define NULLSTR(a) ((a) ? (a) : "(null)") However, to prevent overzealous developers from accidentally applying NULLSTR to a non-char*, how about using an inline function instead? e.g., static inline const char *nullstr(const char *s) { return s ? s : "(null)"; } Then if I accidentally use "nullstr(some_int_var)", the compiler will catch it, rather than masking the real error at run time. Some macro abuses would result in warnings, but at least NULLSTR(0) would mistakenly hide a real error. Whoops. the static inline function also masks the problem with a literal "0". A little experimentation shows that using something like this does most of what I want: #define NULLSTR(s) \ ((void)verify_true(sizeof *(s) == sizeof (char)), \ (s) ? (s) : "(null)") That verify_true use ensures (at compile time) that "s" is a pointer to something "char"-sized. verify_true is defined in gnulib's #include <verify.h>, which is already used by libvirt. Then, even NULLSTR(0) is diagnosed at compile time. For the record, note that this usage does *not* trigger a failure: char i[10] = "abcdef"; printf ("%s", NULLSTR(i)); However, gcc -Wall does print a warning: warning: the address of 'i' will always evaluate as 'true' but that's moot, because there's no reason ever to use NULLSTR on such a variable.
http://www.redhat.com/archives/libvir-list/2009-January/msg00268.html
CC-MAIN-2014-10
refinedweb
255
55.24
A small experiment with a C compiler I’m still somewhat baffled by the performance of my checkers program. I keep pondering that perhaps it would be a good idea to take all the lessons I’ve learned, burn it down, and try again with Milhouse2. After all, in the words of Tom Duff (who may not have said this, but should have) “any program worth writing is worth rewriting”. Toward that end, I was reconsidering the data representation that I used, and revisited this nifty page on Bitboards: Checker Bitboard Tutorial. I basically use bitboards already, but at the very end of the page, you’ll see mention of a novel if somewhat unobvious representation credited to Thotsaphon Thanatipanonda, which simplifies move and jump generation. My own code for this was laboriously constructed using a python program, so it would be nice if we could shrink that code a bit and make it more straightforward. One key that Ed mentions is that it requires machine language rotate instructions, since C does not have a rotate instruction. I thought I’d try to see what gcc does with the obvious implementation. So, I quickly wrote the following function: inline uint32_t rol7(uint32_t val) { return (val << 7) | (val >> 25) ; } (This function uses uint32_t to make sure we have 32 bit values. You can find the defines in stdint.h.) As perhaps we should expect, gcc is smart enough to turn this into a single machine language rorl. This means that we can write a move generator without any difference in handling the even or odd rows, which currently doubles at least the size of my own move generator. Pretty nifty. Recent Comments
http://brainwagon.org/2010/03/31/a-small-experiment-with-a-c-compiler/
CC-MAIN-2014-52
refinedweb
281
56.69
Components and supplies Apps and online services About this project The Arduino IDE and environment has many drivers and libraries available within an arms reach, but the Arduino environment is limited to just setup() and loop() and doesn't support multi-tasking effectively. This article describes the use of mutex semaphores, within an easy to use and robust FreeRTOS implementation that is included in the Arduino IDE as a Library and allows the use of the best parts of both environments.Background.. When two or more Tasks are sharing a single hardware resource, such as a Serial Port the situation can arise that the scheduler will swap one Task out before it has completed its Serial output, and another Task will commence and may provide some Serial output, effectively scribbling over the output of the first Task. This situation can be avoided by using a Semaphore (also called a Flag) to protect the hardware resource, and prevent it being used until it is released by the Task using it. Mutex semaphores are binary semaphores that include a priority inheritance mechanism. Whereas binary semaphores are the better choice for implementing synchronisation (between tasks or between tasks and an interrupt), mutex semaphores are the better choice for implementing simple mutual exclusion (hence 'MUT'ual 'EX'clusion). In this example we will use a mutex Semaphore to protect our Serial port. When used for mutual exclusion the mutex acts like a token that is used to guard a resource. When a Task wishes to access the resource it must first obtain or 'Take' the token. When it has finished with the resource it must 'Give' the token back, allowing other Tasks an opportunity to access the same resource.Let's Get Started In a previous ProTip we have described how to install the FreeRTOS Library for the Arduino IDE, and to test that it is working properly. If you haven't already done this step, please do so now. Now either load the AnalogRead_DigitalRead.ino file into your Arduino IDE, or copy and paste it into a new file, which you should name and save appropriately. Within the sketch there are several steps to creating and using the mutex Semaphore to protect the Serial port. Firstly, a Handle for the mutex Semaphore needs to be declared, as a Global Variable. We do this as a Global so that all Tasks can refer to the Semaphore, and check its availability to be 'Taken'. In the setup() function we check that the Semaphore has not already been created, by checking whether the Handle is NULL. We then go ahead to create the Semaphore, confirm that it has been properly created by checking the Handle contents again, and then finally 'Give' it free to be used, once the Scheduler is running. Now, whenever a Task desires to use the Serial port Serial.println() functions, it should ensure that it has 'Taken' the Serial port Semaphore beforehand. Once a Task has finished with the Serial port, then it must 'Give' the Semaphore to allow other Tasks access to the port. Now that you've created a sketch with multiple Tasks writing to the protected Serial port, try what happens if there is no Semaphore, by commenting out the code for 'Taking' and 'Giving' the Semaphore within each Task. Try printing long lines of text within two, three or more Tasks, and see what happens with, and with-out a protective Semaphore. Read the FreeRTOS detailed description on Queues, Mutexes, and Semaphores. There are many additional types of Semaphore available, and it is important to understand where each type should be used to best effect. Code AnalogRead_DigitalRead.inoArduino #include <Arduino_FreeRTOS.h> #include <semphr.h> // add the FreeRTOS functions for Semaphores (or Flags). // Declare a mutex Semaphore Handle which we will use to manage the Serial Port. // It will be used to ensure only only one Task is accessing this resource at any time. SemaphoreHandle_t xSerialSemaphore; // define two Tasks for DigitalRead & AnalogRead void TaskDigitalRead( void *pvParameters ); void TaskAnalogRead( void *pvParameters ); // the setup function runs once when you press reset or power the board void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // Semaphores are useful to stop a Task proceeding, where it should be paused to wait, // because it is sharing a resource, such as the Serial port. // Semaphores should only be used whilst the scheduler is running, but we can set it up here. if ( xSerialSemaphore == NULL ) // Check to confirm that the Serial Semaphore has not already been created. { xSerialSemaphore = xSemaphoreCreateMutex(); // Create a mutex semaphore we will use to manage the Serial Port if ( ( xSerialSemaphore ) != NULL ) xSemaphoreGive( ( xSerialSemaphore ) ); // Make the Serial Port available for use, by "Giving" the Semaphore. } // Now set up two Tasks to run independently. xTaskCreate( TaskDigitalRead , (const portCHAR *)"DigitalRead" // A name just for humans , 128 // This stack size can be checked & adjusted by reading the Stack Highwater , NULL , 2 // Priority, with 1 being the highest, and 4 being the lowest. , NULL ); xTaskCreate( TaskAnalogRead , (const portCHAR *) "AnalogRead" , 128 // Stack size , NULL , 1 // Priority , NULL ); // Now the Task scheduler, which takes over control of scheduling individual Tasks, is automatically started. } void loop() { // Empty. Things are done in Tasks. } /*--------------------------------------------------*/ /*---------------------- Tasks ---------------------*/ /*--------------------------------------------------*/ void TaskDigitalRead( void *pvParameters __attribute__((unused)) ) // This is a Task. { /* DigitalReadSerial Reads a digital input on pin 2, prints the result to the serial monitor This example code is in the public domain. */ // digital pin 2 has a pushbutton attached to it. Give it a name: uint8_t pushButton = 2; // make the pushbutton's pin an input: pinMode(pushButton, INPUT); for (;;) // A Task shall never return or exit. { // read the input pin: int buttonState = digitalRead(pushButton); // state of the button: Serial.println(buttonState); xSemaphoreGive( xSerialSemaphore ); // Now free or "Give" the Serial Port for others. } vTaskDelay(1); // one tick delay (15ms) in between reads for stability } } void TaskAnalogRead( void *pvParameters __attribute__((unused)) ) // This is a Task. { for (;;) { // read the input on analog pin 0: int sensorValue = analogRead(A0); // value you read: Serial.println(sensorValue); xSemaphoreGive( xSerialSemaphore ); // Now free or "Give" the Serial Port for others. } vTaskDelay(1); // one tick delay (15ms) in between reads for stability } } Schematics Author Phillip Stevens - 4 projects - 101 followers Additional contributors - Wrote freertos by Richard Berry Published onMarch 13, 2016 Members who respect this project you might like
https://create.arduino.cc/projecthub/feilipu/using-freertos-semaphores-in-arduino-ide-b3cd6c
CC-MAIN-2021-49
refinedweb
1,047
51.58
> Visual Studio solution of my Unity project consist of 4 Visual Studio projects** : myApp myApp.Editor myApp.Editor.Plugins myApp.Plugins These VS-projects have such dependencies between: (You could see them in "References" of VS-project in Solution Explorer (to be able to see them, you probably should enable an access to project properties in VS (see here how to do it) myApp: to 4 myApp.Editor: to all (1, 3, 4) myApp.Editor.Plugins: to 1, 4 myApp.Plugins: to none I put a cs-file, which I want to use in projects 1 & 3 to folder of 1: ...\myApp\Assets\Scripts, 'cos 3 has 1 among its references. And it's ok with VS - build succeed. BUT Unity generates such error in its console: Assets/Plugins/Editor/myEditor/myEditor.cs(15,7): error CS0246: The type or namespace name `HelperFunctions' could not be found. Are you missing an assembly reference? What's the trick with VS-projects dependencies? What I miss? **) don't get confused - VS-solution corresponds to a Unity project, but VS-projects are components of VS-solution. PS: If I put this cs-file into folder of 4 project - Unity becomes. VS Solution contains strange projects 1 Answer error CS0246: The type or namespace name 'Google' could not be found not be found (are you missing a using directive or an assembly reference?) 0 Answers Visual Studio Solution has 3 projects. Is it normal? 0 Answers How do I check if inspector variable has a value? 1 Answer Need some help on how to start my project (important) 1 Answer
https://answers.unity.com/questions/1319659/what-is-the-trick-with-vs-projects-references.html
CC-MAIN-2019-22
refinedweb
266
67.25
HTML and CSS Reference In-Depth Information Safe iFrames As mentioned briefly above, busting out of an iFrame is something that may need to happen to ensure an ad provides a rich experience across a network's or publisher's page. However, rendering the ad onto the publisher's document could produce namespace conflicts and reference variables. For example, if the ad has an element called photo-gallery and so does the web page, any manipulations done to that element could pass to the ad experience or even break the page contents. This wasn't an issue back in the Flash (SWF) days of ad creatives as the SWF element was inherently sandboxed from the publisher's page. There has to be a better way to serve rich experiences with HTML that can be sandboxed from the publisher's content, right? If you think that wrapping the ad content in an iFrame will solve all this mess, you'd be absolutely correct. However, an iFrame limits the richness of the experience, as it confines the ad to a specific area on the page; also, it's a bit of a memory hog for pages, as it creates a new instance of the document, one that may not be wanted or needed. (Think of what happens if multiple iFrames are on the page or even nested within each other.) Traditionally, using a publisher side script, the ad can check to see whether this script is in place and bust out of the publisher's designated iFrame. This is absolutely necessary, as most rich ad experiences require expanding and closing functionality. However, once the ad is busted out and written to the main document of the publisher's page, the same rules apply to CSS inheritance and JavaScript variable scoping. Thus confliction and styling issues could arise—indeed, they most certainly will. Building on the knowledge that iFrames can sandbox you from publisher content, how can a common API, one that allows this iFrame to expand and contract as well as gather valuable metrics into the ad experience, be provided? Well the IAB and various working group members are working on an initiative called Safe iFrames, which is intended to be a protocol between the publisher and ad and be a common API that allows “rich” ads to be sandboxed inside of iFrames and still access specific expanding and contracting commands, among others. The publisher will effectively add some code to the iFrame to allow the ad to call pub-side functions for expand and collapse. While the approach needs standardization and adoption to be a scalable method, it holds some promise for dealing with page content and ad confliction. (I've mocked up a simple example to show that you can expand or collapse the actual iFrame at jsbin.com/omodus/5 .) Keep in mind that this would involve special code on the publisher's end; it would control the functionality and animation of the iFrame on the page, not the third-party ad server tag. ■ there is even the possibility of publishers' using the Mraid api to serve ad tags through. Look for more information on the Mraid spec in Chapter 9. Note Many more features of HTML5 as it relates to advertising are discussed later in the topic. HTML5 is about updating and pushing the Web as a whole forward; advertising is a key part of that process. Anything that is updated in the browser will have an impact on advertising. Advertising with CSS3 As you've just learned with HTML5, many enhancements to the overall structure of the page have been added, deleted, or modified. Along with the markup structure, of course, goes style. CSS has long been the backbone for styling within the browser, and as modern browsers adopt CSS3 features, a lot of manufacturers, including Google, Apple, and Mozilla, are leveraging the latest CSS3 additions to handle web animations and presentations as never before. Because CSS3 is such a powerful design toolset, designers can now leverage it for creating rich, print-worthy graphics directly within the browser. They no longer need to rely on Flash or use images to create the design they're after. Search WWH :: Custom Search
http://what-when-how.com/Tutorial/topic-424kltl/HTML5-Advertising-46.html
CC-MAIN-2017-47
refinedweb
703
56.18
As with previous Pangu releases, the jailbreak is offered in the form of a simple click-to-install Windows tool downloadable from Pangu’s website. As tempting as it is to just jump in and run the installer, I like to know how things work before I let them run 0-day kernel exploits on my test device. With that thought in mind I decided that it was time to break out IDA Pro and take a look at the PPJailbreakCarrier application that is installed on the device. This application is responsible for executing the kernel exploit and applying the relevant patches to jailbreak the device. The goal during my initial analysis was to answer the following questions, without installing the application: 1. Has the binary been obfuscated? 2. Are any URLs contained within the application? 3. Does the application contain any encrypted content, and if so can it be decrypted? Binary Obfuscation After loading the binary into IDA Pro it quickly becomes apparent that Pangu have chosen to obfuscate large portions of the binary. This is not a surprise, as previous Pangu releases have also used obfuscation to protect the inner workings of the jailbreak. A quick review of the functions window shows a number of functions with names that have clearly been obfuscated: Below is the IDA graph overview of the function _____________bn. The impact of the obfuscation is immediately apparent. String Encryption A quick search of the functions window for ‘encryption’ identified the function +[PPJBEncryption adjlDKlfjeodlskjflak]. Strangely the method name has been obfuscated but the class name hasn’t; Pangu’s loss is our gain. A quick check of the callers of this function identified the function -[adDKknelkdkfeknkdnfldls aEOdlksjldkfa9990ksf:], which is partially shown below: This function retrieves Base64-encoded encrypted strings and passes them to the decryption function. We will get to the strings later, but for now we need to work out how the encryption has been implemented. As we are happy that our decryption function takes a string as a parameter we rename it -[PPJBEncryption decryptString:]. Where be the keys? Looking at our newly-renamed decryption function we quickly find it accessing the _JB_TOOLS_AES_KEY and _JB_TOOLS_AES_IV values that are located in the __const section of the binary Taking a look at the _kv_hash_arithmetic function we quickly determine that it is a bit of a monster, containing 768 instructions. What’s more, we see that it makes calls to nine more _kv_hash_arithmetic_n functions. In total over 6500 instructions are executed before the function returns - more on this later! The start of the first _kv_hash_arithmetic function can be seen below: Continuing through the decryption function, we see that the Base64-encoded string that was passed into the function is decoded, copied into a new buffer and passed into a function that I have named xor_buffer_withLength_keyByte (named _dxdjlkjdkfjlkwfknwlkefnkweddfdfef in the original disassembly). In addition there are several calls to a benchmark function that are not relevant for our understanding of the decryption process and can be ignored. This process can be seen in the annotated disassembly below: We can see that the XOR routine is being passed the decoded string and a key value of 0x5. Let’s take a look at the function to see how it’s implemented: This is a fairly simple XOR routine that XORs the first byte of the buffer with the key value 0x5, and then iterates over the remainder of the buffer, XORing the current byte with the previous byte. Now that we know how the input data, key and IV are prepared (apart from the small issue of the _kv_hash_arithmetic functions) we can continue through the decryption function to see how they are used. There are no surprises here: after converting the buffers into the required types a standard AES-128 decryption routine is called. Below is the annotated disassembly of this process: The astute reader may notice that the branch to the location I have named free_buffers happens if decrypted_data is NULL. So what happens if we have successfully decrypted the data? Have the developers left us one final gift? Let’s take a look at the disassembly if the branch is not taken. After a quick length check that I have excluded we find the following: Ahh our old friend xor_buffer_withLength_keyByte makes one final return, this time operating on the decrypted data with an initial keyByte value of 0x3. After this final round of XORing we finally construct our NSStrring object that will be returned as the result. At this stage we have a pretty good idea of how the string encryption has been implemented. However, we are left with those pesky _kv_hash_arithmetic functions to reverse before we can implement our decryption script. Whilst it would be possible to work through each of the routines manually reversing the functionality that seemed like a remarkably tedious exercise. Instead I decided to go for a more dynamic approach while respecting my original goal not to run the application on an iOS device. This raised the question of how can I emulate part of a binary from within IDA? Everyone loves Unicorns After a bit of online research I found the mythical creature that offered everything I needed to run my static IDA code. The creature in question was the excellent Unicorn framework. Unicorn is a multi-platform, multi-architecture CPU emulator framework based on QEMU. The project focuses on emulating CPU operation, and allows the emulation of raw assembly instructions without emulating a full runtime environment. After a brief review of the project documentation, I decided that the Unicorn-Python bindings looked like a perfect candidate to integrate into an IDA python script. Setup Setting up Unicorn to work with IDA is relatively simple, the only slight annoyance is that you need to compile a 32-bit version of the library, as for some reason IDA is still 32-bit only. Why IDA, why???? In order to do this I grabbed the source and added the following two lines to the Makefile to tell the compiler to build a universal (32 and 64-bit) binary: $(LIBNAME)_LDFLAGS += -m32 -arch i386 -m64 -arch x86_64 UNICORN_CFLAGS += -m32 -arch i386 -m64 -arch x86_64 After this it was just a case of following the normal compilation and installation instructions. Once you have a working setup you should be able to import from unicorn and unicorn.arm64_const from within IDA. IdaPython Emulator In order to emulate the instructions within Unicorn, we need to create a Unicorn instance and then prepare the process memory. This can be achieved easily from an IDA Python script shown in the example below: #Create the Unicorn instance uc = Uc(UC_ARCH_ARM64, UC_MODE_ARM) # Find the end address of the last segment for s in idautils.Segments(): end = idaapi.getseg(s).endEA start = idaapi.get_imagebase() # Unicorn address ranges must be aligned aligned_size = end - start + (0x1000 - end % 0x1000) # Map enough memory to hold all segments uc.mem_map(start, aligned_size) # Iterate over each segment of the binary and copy the contents into the # mapped memory. Note the image should be rebased to 0x10000000 in order for Unicorn to # successfully allocate the address ranges. for seg in idautils.Segments(): cur_seg = idaapi.getseg(seg) size = cur_seg.endEA - cur_seg.startEA seg_data = idc.GetManyBytes(cur_seg.startEA, size) if seg_data is None: continue uc.mem_write(cur_seg.startEA, seg_data) Once our binary is mapped into memory we need to prepare some memory for a stack that will be used during execution. This can be achieved by mapping another block of memory and setting the stack pointer register to a location in this range. stack_base = 0xC0000000 uc.mem_map(stack_base, 0x10000) uc.reg_write(UC_ARM64_REG_SP, stack_base + 0x1000) Now we are almost ready to run, we first need to decide where to start our execution. Our goal here is to run the minimum amount of instructions to get the output we require, avoiding any library calls as these are not going to be mapped into our process address space. If we take a look at the key derivation component of the decryption function we can see that running from the point that the stack variables are stored to the NOP following the second call to the _kv_hash_arithmetic function should suffice. We start the execution using the following Unicorn API call: uc.emu_start(start_address, end_address, count=0, timeout=100000) If we run these instructions and read the values at SP+0x90+kv_arithmetic_iv and SP+0x90+kv_artithmetic_aes_key from our fake stack we obtain the derived key and IV values: IV = f597e12da172fcdf1d426664d418a888 key = 512351fb893d24fb6e4bc199025d4daf At this stage we could just write a decryption script, but where is the fun in that? After all, we are playing with Unicorn. Instead, let’s take things a bit further and call the XOR function. But how do we do this without calling library functions I hear you say? The answer is to use our IDA python script to Base64-decode the desired input string, allocate some memory within our emulated process and store the decoded string. Unicorn then allows us to set the emulated CPU registers using the function, so we can set X0 to point to the decoded string and X1 to be the xor-key. Now we can simply call the XOR function in the same way that we called _kv_hash_arithmetic. While this is not really required for such a trivial XOR routine it shows how Unicorn can be used to manipulate memory and register values to allow many types of function to be called with arbitrary arguments. Okay, so that’s enough playing around with Unicorn, let’s get to the actual decryption script. I chose to write this in Python, for simplicity. The decryption script can be seen below. Note all error checking has been omitted for brevity. from base64 import b64decode from Crypto.Cipher import AES from sys import argv class PanguDecryptor: def __init__( self): self.iv = "f597e12da172fcdf1d426664d418a888".decode('hex') self.key = "512351fb893d24fb6e4bc199025d4daf".decode('hex') def xor(self, data, key): data = bytearray(data) for i in range(len(data)): previous = data<i> data<i> = data<i> ^ key key = previous return str(data) def unpad(self, s): length = ord(s[-1]) return s[:-length] def decrypt( self, enc ): enc = b64decode(enc) enc = self.xor(enc, 0x5) cipher = AES.new(self.key, AES.MODE_CBC, self.iv ) decrypted = self.unpad(cipher.decrypt(enc)) return self.xor(decrypted, 0x3) aes = PanguDecryptor() print(aes.decrypt(argv[1])) Putting it all together Before embarking on this little reverse engineering voyage of discovery I set out to answer three questions. Whilst I did not initially expect to be extending IDA functionality in the way I ended up doing, it’s always fun to try out a new technique. So back to the initial questions: Has the binary been obfuscated? Yes, we can clearly see that function names have been obfuscated; in addition a number of key functions have had their control flow obfuscated to make reverse engineering more difficult. Are any URLs contained within the application? Yes - I didn't get round to covering it in this blog, but a simple string search for “http” identifies the following URLs:? Does the application contain any encrypted content, if so can it be decrypted? Yes & Yes. Throughout this blog we have identified the encrypted data, the key derivation and additional XOR routines. We’ve produced a dynamic IDA decryption plugin and a standalone Python decryption script. I will leave it as an exercise to the reader to find out how these strings are used within the jailbreak process. Below are the decrypted strings extracted from the binary: 0x1000c0aed - com.apple.iokit.hid.displayStatus 0x1000c0b35 - /tmp/.pangu93loaded 0x1000c0b70 - 6d35d6298fd6ef4fd6af920e852c497b 0x1000c0bba - 8a960ff9b4603ca56110e28bac827f3b 0x1000c0c47 - /bin/launchctl unload /Library/LaunchDaemons/com.teiron.PPHelperLaunchd.plist 0x1000c0cb4 - /bin/launchctl load /Library/LaunchDaemons/com.teiron.PPHelperLaunchd.plist 0x1000c0d21 - /bin/launchctl unload /Library/LaunchDaemons/com.terion.jbnvwa.sprite.plist 0x1000c0d8e - /bin/launchctl load /Library/LaunchDaemons/com.terion.jbnvwa.sprite.plist 0x1000c0e01 - /bin/launchctl load /Library/LaunchDaemons/io.pangu93.loader.plist 0x1000c216a - /Library/LaunchDaemons/com.apple.softwareupdateservicesd.plist 0x1000c21c3 - /var/mobile/Library/ConfigurationProfiles/PublicInfo/PublicEffectiveUserSettings.plist 0x1000c2244 - /etc/hosts 0x1000c225d - 127.0.0.1 oscp.apple.com 0x1000c228a - 127.0.0.1.+oscp.apple.com 0x1000c22b7 - 127.0.0.1 ppq.apple.com 0x1000c22e4 - 127.0.0.1.+ppq.apple.com 0x1000c2311 - /private/var/Keychains/ocspcache.sqlite3 0x1000c2352 - delete from ocsp; 0x1000c237f - delete from responses; 0x1000c23ac - /var/mobile/Library/UserConfigurationProfiles/EffectiveUserSettings.plist 0x1000c2419 - /var/mobile/Library/UserConfigurationProfiles/PublicInfo/PublicEffectiveUserSettings.plist 0x1000c249a - union 0x1000c24b3 - trustedCodeSigningIdentities 0x1000c24e0 - values Update (2016/08/04) Thanks to @planetbeing for highlighting that the binary contains a second set of strings that have been obfuscated using an different technique than the one covered in this blog. For those that are interested he has published a handy tool to decode the strings. Contact & Follow-Up Rob works in our Research team from our London office. He has a keen interest in reverse engineering and mobile device security. See the contact page for ways to get in touch.
https://www.contextis.com/us/blog/obfuscation-encryption-unicorns-reversing-string-encryption-pangu-93-jailbreak
CC-MAIN-2020-34
refinedweb
2,155
54.52
SQL. When you include the FOR XML clause in your query, you must specify one of the four supported modes- RAW, AUTO, EXPLICIT, or PATH. The options available to each mode vary according to that mode; however, many of the options are shared among the modes. In this article, I explain how to use each of these modes to retrieve data as XML and provide examples that demonstrate how they use the various options. The RAW Mode The RAW mode generates a single XML element for each row in the result set returned by the query. To use the FOR XML clause in RAW mode, you simply append the clause and RAW keyword to your SELECT statement, as shown in the following example: Notice that the SELECT statement itself is a very basic query. (The statement pulls data from the AdventureWorks sample database.) Without the FOR XML clause, the statement would return the following results: With the addition of the FOR XML clause, the statement returns the data as the following XML: As you can see, each <row> element maps to a row that is returned by the SELECT statement, and each column, by default, is treated as an attribute of that element. Note: You can include a FOR XML clause only in SELECT statements, if those statements define the outer, or top-level, query. However, you can also include the clause in INSERT, UPDATE, and DELETE statements that are part of a subquery. In the preceding example, each element in the XML is named <row> by default. However, you can override the default behavior by providing a name for the element, as the following example shows: Now the element associated with each row returned by the query will be named <Employee>, rather than the default <row>: In addition to being able to provide a name for the row element, you can also specify that a root element be created to wrap all other elements. To create a root element, add the ROOT keyword to your FOR XML clause: Notice that you must include a comma when adding an option such as ROOT in order to separate the elements. As the following results show, a <root> element is now included in the XML: As with the row element, you can also provide a specific name for the root element: In this case, I’ve named the root element <Employees>, as shown in the following results: Up to this point, the examples I’ve shown you have added column values as attributes to each row element. This is the default behavior of the RAW mode. However, you can instead specify that the column values be added as child elements to the row element by including the ELEMENTS option in the FOR XML clause: Once again, I’ve added a comma to separate the options. As you can see in the following results, each <Employee> element now includes a set of child elements that correspond to the columns returned by the query: Now the <Employee> elements no longer include any attributes and all data is rendered through individual child elements. If you refer back to the XML returned by the previous example, you’ll notice that the data for employee 4 (Rob Walters) does not include a middle name. This is because that MiddleName value is null in the source data, and by default, no elements are created for a column whose value is null. However, you can override this behavior by adding the XSINIL keyword to the ELEMENTS option: Now the results will include an element for the MiddleName column and will include the xsi:nil attribute with a value of true when a value is null, as shown in the following XML: Notice that the xmlns:xsi attribute has also been added to the root node and provides the name of the default schema instance. Another important option that is supported by the RAW node is XMLSCHEMA, which specifies that an inline W3C XML Schema (XSD) be included in the XML data. You add the XMLSCHEMA option in the same way you add other options: As you can see in the following results, the schema is fully defined and is incorporated in the XML results: When you specify that a schema be created, you can also specify the name of the target namespace. For example, the following FOR XML clause includes the XMLSCHEMA option, followed by the name of the target namespace (urn:schema_example.com): The statement will return the same results as the previous example, except that the XML will now include the new name of the target namespace. The SELECT statements shown in the preceding examples have retrieved data from non-XML columns (in this case, integer and string columns). However, your queries might also retrieve data from XML columns. In such cases, the FOR XML clause will incorporate the data retrieved from an XML column into the XML result set. For example, the following SELECT statement uses the XML query() method to retrieve education-related data from the Resume column in the JobCandidate table: The query() method itself retrieves the following data from the Resume column: This data is incorporated into the rest of the result set when you use the FOR XML clause, as shown in the following results: As you can see, the <ns:Education> element and its child elements have been added to the XML data. The namespace defined on the source data in the XML column is also included. The AUTO Mode The AUTO mode in a FOR XML clause is slightly different from the RAW mode in the way that it generates the XML result set. The AUTO mode generates the XML by using heuristics based on how the SELECT statement is defined. The best way to understand how this works is to look at an example. The following SELECT statement, as in the previous examples, retrieves employee data from the AdventureWorks database: Notice that I’ve provided meaningful alias names to the tables (Employee and Contact info). These names are used in defining the XML element names, so you’ll want to construct your SELECT statements accordingly. Now take a look at the results returned by this query: As you can see, the <Employee> element has been named automatically based on the table alias name. Notice too that the <ContactInfo> element is a child element of <Employee>. The structure of the elements is based on the order in which the columns are defined in the SELECT list and the tables that are specified in the FROM clause. In this case, because EmployeeID is the first column in the SELECT list and the Employee table is included in the FROM clause, the first element is <Employee>. And because the remaining columns, which are associated with the ContactInfo table, appear next in the SELECT list, they are added as a child element. If an additional table and its columns were included in the SELECT list, after the other columns, they would appear as a child element of <ContactInfo>. In addition, the columns and their values are added as attributes to the table-related elements. This structure is similar to what you saw in the RAW mode examples. And in the same way, you can override the default behavior by using the ELEMENTS option: As you can see in the following XML result set, the column values are now included as child elements, rather than attributes: Notice that the <ContactInfo> element also contains child elements, one for each column. If you want to include an element for columns with null values, you can use the XSINIL option, as you saw when using the RAW mode: Now the results will include all elements. That means, if a value is null, the xsi:nil attribute is included: As you’ve seen in these examples, the XML is based on how the columns are listed in the SELECT list. However, as I mentioned earlier, the XML is also based on the tables listed in the FROM clause. In the preceding examples, the SELECT list contained only columns that are referenced in the FROM clause. If a column is not directly associated with a table in the FROM clause (as in a computed or aggregate column), the column is nested at the deepest level wherever it appears. For example, the following SELECT statement includes the FullName computed column, which concatenates the first and last names: Because the FullName column appears in the SELECT list after the EmployeeID column, the FullName column is added as a child element of <Employee>, as shown in the following XML: As I’ve mentioned, the placement of columns in the SELECT list impacts the resulting XML. This is also the case with computed columns. For example, in the following SELECT statement, I’ve added the FullName column after the EmailAddress column: Now the FullName column will be added as a child element to the <ContactInfo> element, as the following XML demonstrates. As these results show, you must be aware of the order you place columns when you define your SELECT list. Now let’s take a look at another aspect of the AUTO mode. One of the limitations of this mode (as well as the RAW mode) is that the column data is added as either attributes or child elements, depending on whether you specify the ELEMENTS option. However, there might be times when you want to return some of the data as attributes and some as child elements. One method you can use with the AUTO mode is to return some of the data in a subquery. For example, the following SELECT statement includes a subquery that returns the employee’s first and last names: Notice that the subquery includes a FOR XML clause that uses AUTO mode and includes the ELEMENTS option. The FOR XML clause also includes the TYPE option, which specifies that the data returned by the subquery be returned as the XML type. You must include the TYPE option to preserve the data as XML in the outer SELECT statement. The outer SELECT statement also includes a FOR XML clause, but the ELEMENTS option is not included. As a result, only the first and last names will be returned as child elements, but the employee ID and login ID will be returned as attributes, as shown in the following XML: As you can see, subqueries let you maintain some control over the output. However, the AUTO mode (and the RAW mode, for that matter) provides little control over the XML returned by your query. For greater control, you’ll want to use the EXPLICIT mode or the PATH mode. The EXPLICIT Mode The EXPLICIT mode provides very specific control over your XML, but this mode is much more complex to use than the RAW or AUTO modes. To use this mode, you must build your SELECT statements in such as way as to define the XML hierarchy and structure. In addition, you must create a SELECT statement for each level of that hierarchy and use UNION ALL clauses to join those statements. There are a number of rules that describe how to define your SELECT statements when using the EXPLICIT mode, and it is beyond the scope of this article to review all those rules, so be sure to refer to the topic “Using EXPLICIT Mode” in SQL Server Books Online for the details about how to construct your SELECT statements. In the meantime, let’s take a look at a few examples that help demonstrate some of the basic elements of the EXPLICIT mode. When constructing your SELECT statement, you must include two columns in your SELECT list that describe the XML hierarchy. The first column, Tag, is assigned a numerical value for each level of the hierarchy. For instance, the first SELECT statement should include a Tag column with a value of 1. This is the top level of the hierarchy. The second SELECT statement should include a Tag column with a value of 2, and so on. The second column that you should include in your SELECT statement is Parent. Again, this is a numerical value that identifies the parent of the hierarchy based on the Tag values you’ve assigned. In the first SELECT statement, the Parent value should be null to indicate that this is a top level hierarchy. Your first SELECT statement should also include a reference to all the columns that will make up the XML structure. The columns must also include aliases that define that structure. Let’s look at an example to help understand how this all works. The following SELECT statements return results similar to what you’ve seen in previous examples; however, the SELECT statements themselves are more detailed: In the first SELECT statement, I begin by defining the Tag column and assigning a value of 1 to that column. Next I define the Parent column and assign a null value. I then define the EmployeeID column and assign an alias to that column. Notice that I use a very specific structure to define the alias name: As the syntax shows, the first three components are required, and the last is optional: <ElementName> :The name of the element that the value should be assigned to. <TagNumber> :The tag number associated with the hierarchy that the value should be assigned to, as defined in the Tag column. <AttributeName>:The name of the attribute associated with the column value, unless an optional directive is specified. For example, if the ELEMENT directive is specified, <AttributeName> is the name of the child element. <OptionalDirective> :Additional information for how to construct the XML. For example, based on the alias name assigned to the EmployeeID column, you can see that the EmployeeID attribute will be associated with the <Employee> element on the first level of the hierarchy. Because the next three columns in the SELECT list are associated with the second level of the XML hierarchy, which is defined in the second SELECT statement, null values are assigned to the alias names for the column. This will provide the XML structure necessary to join the two SELECT statements. The second SELECT statement is much simpler, but it still includes the Tag and Parent columns in the SELECT list. The remaining columns in the SELECT list are defined as you would normally define columns in your query. The result set for the two SELECT statements is then ordered by the EmployeeID and FirstName columns. This is necessary so that null values appear first in the result set to ensure that the XML is properly formatted. The FOR XML clause is then appended to the end of the SELECT statement in order to generate the following XML: The EmployeeID column has now been added as an attribute to the <Employee> element. However, you can change the EmployeeID column to a child element simply by adding the ELEMENT directive, as I did with the other columns: Now the EmployeeID value will be displayed as a child element of <Employee>,the first level element: You can also ensure that columns with null values will still display the element by changing the ELEMENTS directive to ELEMENTSXSINIL, as shown in the following SELECT statement: Now the results will include the xsi:nil attribute where values are null in the MiddleName column, as shown in the following XML: As you can see from these examples, the EXPLICIT mode can cause your SELECT statements to become quite complex, especially if you want to add more levels to the hierarchy or want to create more intricate SELECT statements. Fortunately, most of what you can do with the EXPLICIT mode, you can do with the PATH mode, and do it in a much simpler way.. We’ll begin with the PATH mode’s default behavior. The following example includes a FOR XML clause that specifies only the PATH option: Because no specific attributes or hierarchies have been defined, the query will return the following XML: As you can see, each column is added as a child element to the <row> element. You do not have to specify the ELEMENTS directive because individual elements are returned by default, based on the column names. You can also rename the row element and define a root element, as you’ve seen in earlier examples: As the following results show, the XML now includes the <Employees> root element and the individual <Employee> row elements: Suppose, now, that you want to include the EmployeeID value as an attribute of <Employee>.You can easily do this by adding an alias to the EmployeeID column in the SELECT clause and preceding the alias name with @, as shown in the following example: Now the <Employee>elements contain the EmpID attribute, along with the employee ID: You can see how easy it is to return both attributes and child elements by using the PATH mode. And if you want to include elements with null values, you simply include the ELEMENTS XSINIL option in your FOR XML clause: Now your results include the xsi:nil attribute for those fields that contain null values: As you can see, the xsi:nil attribute in the <MiddleName> element has been set to true. Note: Because the PATH mode automatically returns values as individual child elements, the ELEMENTS directive has no effect when used by itself in a FOR XML clause. It is only when the XSINIL option is also specified that the ELEMENTS directive adds value to the clause. In addition to defining attributes within your column aliases in the SELECT list, you can also define hierarchies. You define hierarchies by using the forward slash and specifying the element names. For example, the following SELECT defines the <EmployeeName> element and its three child elements: <FirstName>, <MiddleName>, and The statement returns the following XML result set: Notice that each <Employee>element now includes an <EmployeeName> element, and each of those elements includes the individual parts of the name. Suppose that you now want to add an email address to your result set. You can simply add the column to the SELECT list after the other columns, as shown in the following example: Because the column name is EmailAddress and no alias has been defined on that column, your XML results will now include the <Employee>,right after <EmployeeName>: You must be careful on how you order your columns in the SELECT list. For example, in the following SELECT statement, I added the EmailAddress column after MiddleName, but before LastName: Because I do not list the parts of the employee names consecutively, they are separated in the XML results: As the XML shows, there are now two instances of the <EmployeeName> child element in each <Employee> element. The way to address this issue is to make certain you list the columns in your SELECT list in the order you want the XML rendered. In an earlier example, I demonstrated how to include an XML column in your query. You can also include an XML column when using the PATH mode. The XML data returned by the column is incorporated into the XML that is returned by the query. For instance, the following SELECT statement adds education data to the result set: The <Education> element and child elements are now included the XML result set: As these preceding examples demonstrate, the PATH mode provides a relatively easy way to define elements and attributes in your XML result set. However, the PATH mode, like the other FOR XML modes, supports additional options. For that reason, be sure to check out SQL Server Books Online for more information about each mode and about the FOR XML clause in general. Despite how basic the clause itself might seem, it provides numerous options for returning exactly the type of XML data you need. Load comments
https://www.red-gate.com/simple-talk/sql/learn-sql-server/using-the-for-xml-clause-to-return-query-results-as-xml/?article=720
CC-MAIN-2020-29
refinedweb
3,312
51.82
Node to define beveling properties. More... #include <Inventor/nodes/SoBevelProperty.h> This node defines the current beveling properties (used by SoBevelAction) for all subsequent shapes. You can use it to specify a beveling radius (absolute or relative) and an angle between adjacent faces (like a crease angle) that determines if the edge between those faces will be beveled. SoBevelAction, SoEdgeFlag, SoVertexFlag Test. Constructor. Indicates the angle (in radians, between 0 and pi) between two adjacent face normals above which the edge will be beveled. (If the edge has been unmarked by the current SoEdgeFlag it will not be beveled, regardless of the value of angle). This defines the bevel radius (the size of the rounded edge or corner). This value will be interpreted as absolute or relative depending on the absoluteRadius flag (below). Which tests should be performed in order to "clean up" the shape before it is beveled.
https://developer.openinventor.com/refmans/latest/RefManCpp/class_so_bevel_property.html
CC-MAIN-2021-04
refinedweb
149
63.49
Based on the original Euler Rotation article, it’s time to revisit the 3D graphics GDI+ world. In the last article, we discussed the fundamentals for drawing a simple cube shape on a two-dimensional bitmap surface. Now, it’s time to take it up a notch. We are going to draw a cube with shaded sides, and we are going to find a way around the pesky Gimbal Lock problem. First things first, Gimbal Lock. In the last article, we encountered a strange problem when rotating the cube around separate axes. Due to the fact that matrix multiplication is not cumulative, rotating around different axes in different order produced results that were not always the same. A way to avoid that problem is to step up to more advanced mathematics such as quaternions. However, a more simple solution is to restructure the way the Cube class handles rotations. Cube Let’s compare the original structure and the new improved one. The way rotations were handled originally was to: Can you spot the problem? Whenever a rotation is applied, the cube starts from scratch and reapplies all the rotations. Thus, certain rotations can seem to be going the wrong way. The answer is simple: Basically, instead of starting from scratch every time, we rotate what we already have. Before going on to shading the cube, we have to restructure another part of the project. Instead of handling all the cube’s points separately, it is better to group them into cube faces. The advantages of doing things this way is we can avoid writing manually which points should connect to which when drawing the cube. All we have to do is tell how each face will be drawn. Also, when it comes to shading the cube, we’ll have to know the order in which to draw the faces. The faces class will only need some basic properties: We’ll also need to include a CompareTo function where the z value of the center points are compared. CompareTo z public int CompareTo(Face otherFace) { return (int)(this.Center.z - otherFace.Center.z); } One last thing to fix before shading the cube: the 3D projection. When I first started writing the shading routine, I discovered that the 2D plotting from the Euler Rotation article was flawed. It was drawing everything backwards! After much simplification and review, this is the new function: private PointF Get2D(Vector3D vec) { PointF returnPoint = new PointF(); float zoom = (float)Screen.PrimaryScreen.Bounds.Width / 1.5f; Camera tempCam = new Camera(); tempCam.position.x = cubeOrigin.x; tempCam.position.y = cubeOrigin.y; tempCam.position.z = (cubeOrigin.x * zoom) / cubeOrigin.x; float zValue = -vec.z - tempCam.position.z; returnPoint.X = (tempCam.position.x - vec.x) / zValue * zoom; returnPoint.Y = (tempCam.position.y - vec.y) / zValue * zoom; return returnPoint; } Let’s go over the code. The truth is this is the most basic form of 3D projection. The X and Y values are simply x/z and y/z of the 3D point. Only, we are factoring in the position of the perspective, or camera, which we placed at the center of the cube. The last key factor is the zoom variable. When projecting 3D points into a 2D surface, we have to factor in the area. In a smaller area, the cube would be more squished and vice versa. In this case, we use the width of the entire screen to keep straight lines in the cube parallel/perpendicular to the entire screen. At last, time to shade in the cube. Believe it or not, it will be very simple, thanks to all the time we spent creating a solid foundation. Fittingly, a cube face will be shaded based on the 2D points already projected. Since the four corners could create any random quadrilateral, it is best to use the FillPolygon function: FillPolygon g.FillPolygon(Brushes.Gray, GetTopFace()); where g is the Graphics object drawing to whatever surface is appropriate. Also, don’t worry about the GetTopFace() call, it’s in the source code, and all it does is it finds the 2D corner points of the cube face (the top face in this example). g Graphics GetTopFace() Now, a bit of reasoning will reveal that shading the faces at a specific order will not always display correctly. The order in which we want to fill in the cube’s faces depends on which way the cube is facing. Luckily, that’s what the CompareTo function in the Face class is for. We can add all the faces into an array, sort the array, and then iterate through it. Remember that the faces are sorted based on the z value of their center. That means the closest ones to the screen will be first. These are actually the last ones that should be filled. Thus, we iterate through the array backwards, starting from the end. Face The result is impressive considering that it is all done with GDI+. A further improvement will be to create shading based on lighting. That, however, is beyond the scope of this article. For now, the sides are shaded based on a color
http://www.codeproject.com/Articles/27608/3D-Graphics-Cube-with-Shading
CC-MAIN-2014-10
refinedweb
857
65.01
SciChart® the market leader in Fast WPF Charts, WPF 3D Charts, and iOS Chart & Android Chart Components Hi, I have a question concerning multithreaded access to the DataSeries: We implemented an overview for our chart as described here. This works fine when we load data, add it to the series and then display it. Now, for a certain use case we need to display live data. We implemented this in a background thread. We noticed that after some time the application freezes when the update frequency rises. In the documentation I found this: NOTE: Considerations when a DataSeries is shared across multiple chart surfaces. Currently only a single parent chart is tracked, so DataSeries.SuspendUpdates() where the DataSeries is shared may have unexpected results. I guess this is what is happening here…so what is the recommended approach to achieve something like this? Do we have to add the data on the UI thread if we want to have the Overview? Here it says: When appending Data in a background thread, you cannot share a DataSeries between more than one SciChartSurface. You can still share a DataSeries between more than one RenderableSeries. Does that mean we should create more different RenderableSeries for the main chart surface and the overview surface that are based on the same DataSeries? Any help would be appreciated! I am trying to implement the Custom Overview control but the above namespace cannot be resolved. I tried adding the required classes to my project but cannot find a way to reference them from Xaml. The required classes are the following – DoubleToGridLengthConverter ActualSizePropertyProxy Without these classes the Overview scrollbar cannot be resized and stays fully expanded. Any help please? In your custom overview example the width of the grid column used as padding is linked to the width of the y axis. <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <!-- Hosts overview control --> <ColumnDefinition Width="{Binding ActualWidthValue, ElementName=proxy, Mode=OneWay, Converter={StaticResource DoubleToGridLengthConverter}}" /> <!-- Used to bind to parent surface YAxis --> </Grid.ColumnDefinitions> <!-- This class is in the Examples Source Code, under your install directory --> <helpers:ActualSizePropertyProxy x: What do you use for the Path if you have multiple y axes. I have tried objects like AxisAreaLeft with no success.
https://www.scichart.com/questions/tags/overview
CC-MAIN-2019-09
refinedweb
368
56.25
Usage During my time with the MacBook, I've made a number of observations about the changes and updates that I think would be useful to cover in this review. This is basically the section for my subjective opinion of certain aspects of the machine, and shouldn't be taken as any sort of absolute statement. What I like and observe might not necessarily be the same as you or the next person who uses a MacBook, so please keep that in mind. I don't feel the need to spend too much time on the MagSafe connector. Jacqui covered that very thoroughly in her review of the MacBook Pro, and my experience with the MacBook has been the same. The connector itself is the same as that on the MacBook Pro, although the power adapter is smaller—60W instead of 85W. Aside from the difference in the adapter, the MagSafe on the MacBook provides the same advantages and drawbacks as it does on the MacBook Pro. Next up is the already (in)famous glossy screen. What can I say that hasn't already been said? If you wondered whether or not the glossy screen was too reflective, it really depends on the environment. For the first few hours of usage, I was in a typical office building. fluorescent lighting fixtures everywhere played havoc with trying to find a suitable viewing angle. Every time I rotated in my chair I'd have to readjust everything to get rid of the glares. That being said, in proper lighting (like in my apartment), the screen really does seem to be crisper and the colors do seem to be richer and brighter. Compared side-by-side to my iBook G4, I could see the difference. Unfortunately, this observation is difficult to get on camera due to the nature of the subject, but hopefully the image at the beginning of the review will give you an idea of how the glossy display looks. If you're concerned, you'd be well-served by taking your current laptop (if you own one) down to the nearest Apple retailer and compare them side-by-side for yourself. Temperature I'm sure everyone up till this point has been wondering about two specific issues: is the machine still ludicrously hot and does the machine whine like its big brother? First up, let me address the heat issues. Yes, the machine still runs hot. Individuals with access to the MacBook's service manual indicate that it—like the MacBook Pro manual—suggests applying piles of thermal compound. My analysis of the temperatures seem to bear this out. To test out the temperatures, I loaded up an application called CoreDuoTemp that loads a kernel extension and then monitors the machine's temperature, processor speed, and CPU loading. I then put together a python script that looked like the following: import math while 1: for x in range(10000): y = math.cos(x) I then ran two instances of this script in order to peg both processor cores. The system would step the speed of the processor up to 1.833GHz until the processor crossed a threshold of approximately 82°C at which point it would step the processor down to 1.667GHz. When the processor dropped below 80°C it would speed step back up to 1.833GHz and the cycle would continue. As expected, this would cause the system's fans to rev up to their full speed and overall, the machine was very noisy at this point. Running hot as usual I think that most people would agree that a machine running over 80°C is not operating properly. This is especially true when there are several examples of users applying the thermal paste properly, resulting in maximum temperatures of 64°C. 63°C is the idle temperature of the 2.0GHz MacBook in my possession. That should say a lot about whether or not Apple has remedied the error in their manufacturing process. Second is "the whine." I was never able to hear a well defined "whine" from the MacBook Pro in the first place. If I could hear anything, it was a very, very, very faint buzz when I held my head very near to the machine. As you might have expected, I hear no whine noises from the MacBook. In addition, I don't hear any noise from the machine while it's idle, except for the standard laptop noise generated by the hard drive. Latch The MacBook lacks a mechanical latch. On the MacBook Pro, iBook, and PowerBooks there are one and sometimes two latches that are magnetically activated and function to hold the screen shut when the machine is not in use. In the new MacBook, there is no such latch. Instead, the MacBook uses magnets to stay closed. In the lid of the machine, there are two metal plates on each end (use your MagSafe connector to verify). When the lid is closed, these attract to what I presume are magnets in the frame and the machine is held very securely shut. It makes for a very slick looking form factor, and the lack of latches and keyholes really tightens up the already sleek design. The new magnetic latch makes for a sleek profile. The IR port is at right. One game that I've been dying to try out for a while is an MMORPG called EVE Online. I've run across several people online who were concerned about whether or not the MacBook would be able to play this game efficiently. I downloaded the client from the EVE website and signed up for a 14-day trial and got started. Having never played the game on a souped-up PC, I can't really give a comparative analysis of the speed of the game. However, I did play through the entire tutorial and ran a few "missions" and I'm confident when I say that playing EVE online with the default settings looks beautiful and turned out to be pretty darn awesome. I notice no stuttering and only a few delays which I believe could be attributed to the game downloading content from servers as I progressed through the game. I found the game pretty enjoyable—it reminded me of a little of playing TradeWars 2002 on a BBS back in the day—and I think that casual gamers will find that the MacBook will be able to adequately run somewhat new and enjoyable 3D Windows-only games. From discussions with people more knowledgable, and you'd be better off waiting for Apple's Intel workstation offerings or just buying a dedicated gaming machine. You must login or create an account to comment.
http://arstechnica.com/gadgets/2006/05/macbook/4/
CC-MAIN-2015-06
refinedweb
1,124
69.52
import "github.com/go-kit/kit/sd/dnssrv" Package dnssrv provides an Instancer implementation for DNS SRV records. doc.go instancer.go lookup.go Instancer yields instances from the named DNS SRV record. The name is resolved on a fixed schedule. Priorities and weights are ignored. NewInstancer returns a DNS SRV instancer. func NewInstancerDetailed( name string, refresh *time.Ticker, lookup Lookup, logger log.Logger, ) *Instancer NewInstancerDetailed is the same as NewInstancer, but allows users to provide an explicit lookup refresh ticker instead of a TTL, and specify the lookup function instead of using net.LookupSRV. Deregister implements Instancer. Register implements Instancer. Stop terminates the Instancer. Lookup is a function that resolves a DNS SRV record to multiple addresses. It has the same signature as net.LookupSRV. Package dnssrv imports 6 packages (graph). Updated 2017-09-18. Refresh now. Tools for package owners.
https://godoc.org/github.com/go-kit/kit/sd/dnssrv
CC-MAIN-2017-51
refinedweb
142
54.39
Today’s objective was to override Bootstrap variables to permit some theme customization. Overall the process had a few pitfalls and I found that many references to this combination of tools were now out of date, presumably the result of changes to Aurelia’s project structure since they were written. Sass Preprocessor I started with a default Aurelia setup. This supports CSS and doesn’t include a preprocessor for Sass. To help, I generated an Aurelia project using au new with the Sass preprocessor selected. This highlighted the first change needed which was to replace the cssProcessor in the aurelia.json file: "cssProcessor": { "id": "sass", "displayName": "Sass", "fileExtension": ".scss", "source": "src/**/*.scss" }, To pre-process Sass a pre-processor is required. I used gulp-sass, obtained via npm install gulp-sass --save-dev. save-dev is used because this is a build tool and not required at runtime. To introduce this into the build process, I changed tasks/process-css.ts import * as gulp from 'gulp'; import * as changedInPlace from 'gulp-changed-in-place';(build.bundle()); }; Then I added an .scss file and referenced it from the app.html with a .css extension: . At this point doing au run and opening the browser showed the scss styles applied. Adding Bootstrap Aurelia doesn’t create a physical CSS file, instead the build.bundle() call in tasks/process-css.ts adds it to the app-bundle.js. As the goal was to customize Bootstrap before the CSS is generated, then the generated CSS, and therefore Bootstrap, must be included in the app-bundle rather than the vendor-bundle (where the contact manager tutorial puts it). This meant removing jquery and Bootstrap from the vendor-bundle section of the aurelia.json and putting it in the app-bundle section as follows: "bundles": [ { "name": "app-bundle.js", "source": [ "[**/*.js]", "**/*.{css,html}" ], "dependencies": [ "jquery", "bootstrap-sass" ] }, { "name": "vendor-bundle.js", ... The json above is slightly out of order because it references bootstrap-sass, the Sass version of bootstrap. This was obtained using the command npm install bootstrap-sass --save. I also had to clear out the original Bootstrap by deleting it from the package.json and running npm prune, and then doing similar steps for Typings. At this point the scss file was as follows: $navbar-default-bg: #800; @import '../node_modules/bootstrap-sass/assets/stylesheets/bootstrap'; div { border: 1px solid green; } Building this with au build resulted in fairly verbose and non-illuminating errors because in order to work Bootstrap depends on gulp-autoprefixer which needed to be added to the process-css.ts as follows: import * as gulp from 'gulp'; import * as changedInPlace from 'gulp-changed-in-place'; import * as autoprefixer from 'gulp-autoprefixer';(autoprefixer()) .pipe(build.bundle()); }; With that, I successfully overwrote a Bootstrap variable.
https://winterlimelight.com/2017/01/23/aurelia-bootstrap-and-sass/
CC-MAIN-2020-29
refinedweb
462
50.23
C# 6.0 Features Series - How to try C# 6.0 and Rosyln? - Getter-only (Read Only) Auto Properties in C# 6.0 - Lambda and Getter Only Auto-Properties in C# 6.0 - Initializers for Read-Only Auto Properties in C# 6.0 - Initializers via Expression Auto Properties in C# 6.0 - C# 6.0 – A field initializer cannot reference the non-static field, method, or property - Lambda Expression for Function Members in C# 6.0 - Dictionary Initializers (Index Initializers) in C# 6.0 - Expression Bodies on Methods returning void in C# 6.0 - using keyword for static class in C# 6.0 - Unused namespaces in Different Color in Visual Studio 2015 - Null-Conditional Operator in C# 6.0 - Null-Conditional Operator and Delegates - nameof Operator in C# 6.0 - Contextual Keywords in C# - String Interpolation in C# 6.0 - Exception Filters in C# 6.0 - Await in Catch and finally block in C# 6.0 In one of the previous blog post , we explored one of the feature of C# called Lambda Expression for Function Members in C# 6.0 where the example method used there had a return type of integer. In this blog post , let see the usage of the expression bodies on the methods returning void. Expression Bodies on Methods returning void in C# 6.0 The Expression bodies can still be used on the methods returning void or Task (async methods) . In this case , it is necessary that expression immediately after the lambda expression syntax (arrow) to be a statement expression. Below is a sample code snippet demonstrating the usage of the Expression Bodies on Methods returning void in C# 6.0 using System; using System.Collections.Generic; using System.Linq; namespace MobileOSGeekApp { class Program { public static void Display() => Console.WriteLine("Welcome to developerpublish.com .NET Tutorials Section"); static void Main(string[] args) { Display(); Console.ReadLine(); } } }
https://developerpublish.com/expression-bodies-on-methods-returning-void-in-c-6-0/
CC-MAIN-2020-34
refinedweb
311
52.97
Java File class represents the path of directories and files. It provides the methods for renaming, deleting, and obtaining the properties of a file or directory. The File class is the wrapper class for the file name and its directory path. Java File Class The File class is Java’s representation of the file or directory pathname. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. A File class contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the contents of an index, and determining several common attributes of files and directories. - It is an abstract representation of file and directory pathnames. - The pathname, whether abstract or in the string form can be either absolute or relative. The parent of the abstract pathname may be obtained by invoking a getParent() method of this class. - First of all, we should create a File class object by passing a filename or directory name to it. The file system may implement restrictions to certain operations on the actual file-system object, such as the reading, writing, and executing. These restrictions are collectively known as access permissions. - Instances of a File class are immutable; that is, once created, the abstract pathname represented by the File object will never change. The pathname can be absolute or relative. #Absolute name It contains the full path and drives letter, i.e., it is the full name of the path. For example, C:\Documents\TextFiles\sample.txt #Relative name It is the file name/path concerning the current working directory. For example, TextFiles\sample.txt (C:\Documents being the current working directory) See the following image. #How to create a File Object in Java A File object is created by passing in a string that represents the name of a file, or a String or another File object. For example, File f = new File("/usr/local/bin/hello"); It defines an abstract file name for the hello file in directory /usr/local/bin. This is an absolute abstract file name. #Creating objects for files and directories The File class objects can be created by passing the file name or directory name in the string format. - new File(“C:\\Documents\\TextFiles\\sample.txt”) – This creates the object for the file sample.txt - new File(“C:\\Documents”) – This creates the File object for the directory C:\Documents The File class does not provide the methods for reading and writing the file contents. Instances of the File class are immutable, which means the path names represented cannot be changed once created. #Constructors of File Class #File(String pathname) It creates a File object for the specified pathname for a file or directory. #File(File parentpath, String childpath) It creates a File object from an existing file object with its child file/directories pathname. #File(String parentpath, String childpath) It creates a File object with the specified parent directory’s pathname and child file/directory pathname. #File(URI uri) It creates a File object from a Uniform Resource Identifier. #Methods of File Class boolean isFile(): Returns true if the object represents the path of a file. boolean isDirectory(): Returns true if the object represents the path of a directory. boolean isHidden() Returns true if a file or directory is hidden. boolean exists(): Returns true if such a file/ directory exists. boolean canRead(): Returns true if the read permission of the file is on. boolean canWrite(): Returns true if the write permission of the file is on. boolean canExecute(): Tells whether the file is executable or not. String getName(): Returns the name of the file or directory. String getPath(): Returns the formatted string path of the file or directory. String getAbsolutePath(): It returns the absolute path of the file/directory. long lastModified(): Returns the date when the file was last modified (in milliseconds), this value can be converted into dd-MM-yyyy HH:mm:sss format using SimpleDateFormat class. long length(): It will give the length of the file. boolean delete(): Deletes the file or directory. boolean renameTo(File f): Renames the file with the given abstract pathname. File [] listFiles(): Returns the array of File objects of all files contained in the directory specified. int compareTo(File pathname): It compares the pathnames of two files. boolean createNewFile(): It creates a new and empty file having the pathname specified in the constructor. boolean equals(Object obj): Tests whether the specified abstract pathname and the object are equal or not. long getFreeSpace(): It returns the number of unallocated bytes, i.e. the free space in the specified partition. String getParent(): It returns the parent directory pathname (string formatted) of the specified file/directory. File getParentFile(): It creates the File object of the parent directory of the specified file/directory. String[] list(): Returns the array of strings containing the name of the files and directories in the specified directory. boolean mkdir(): Creates the new directory with the specified pathname. boolean setExecutable(boolean exe): Changes the permission of the file to executable and set it true for the owner. boolean setReadable(boolean read): Changes the read permission of the file and set it true for owner. boolean setReadable(boolean read, boolean own): Sets the read permission for either owner or everyone. boolean setReadOnly(): Sets only the read permissions, disabling all other operations. String toString(): Returns the formatted string path of the abstract pathname of the specified file/directory. boolean setWritable(boolean canWriteIt): Sets the write permission for the owner. URI toURI(): It will return a file URI representing the file/directory abstract pathname. The following program checks whether a file exists or not, whether it is a file or a directory and also checks all the permissions the file has. import java.io.File; class Example1 { public static void main(String [] args) { File sample=new File("Demofile.txt"); if(sample.exists()==true) { System.out.println("The file: 'Demofile.txt' exists."); //checking whether it is a file or directory System.out.print("Is it a file or directory: "); if(sample.isFile()==true) System.out.println("It is a file."); else if(sample.isDirectory()==true) System.out.println("It is a directory."); //checking different kinds of permissions System.out.println("The file is readable: " + sample.canRead()); System.out.println("The file is writable: " + sample.canWrite()); System.out.println("The file is executable: " + sample.canExecute()); } else System.out.println("The file: 'Demofile.txt' does not exist"); } } See the output. Here’s another program as an example. The following program lists all the files and directories in a certain directory along with the length of the file and whether it is a file or directory. import java.io.File; class Example2 { public static void main(String [] args) { //creating the File object for directory Books File dir=new File("Books"); if(dir.exists()) { if(dir.isFile()) System.out.println("The given is a file"); else { System.out.println("The given is a directory"); //creating an array of File objects for files and directories in the given directory File[] listOfFiles=dir.listFiles(); //traversing the array of files for(int i=0;i<listOfFiles.length;i++) { String fileOrDir=""; //checking if it is file or directory if(listOfFiles[i].isFile()) fileOrDir="file"; else if(listOfFiles[i].isDirectory()) fileOrDir="directory"; //finding the size of the file long len=listOfFiles[i].length(); System.out.println("name: "+listOfFiles[i].getName()+"\nfile or directory: "+fileOrDir+"\nsize (bytes): "+len+"\n"); } } } } } See the following output. The following program creates a new file that does not exist in memory and setting the readable permission of the file. import java.io.File; class Example3 { public static void main(String [] args) { File sample=new File("Demofile3.txt"); //checking if the file exists if(sample.exists()) System.out.println("THE FILE ALREADY EXISTS."); else { System.out.println("THE FILE DOES NOT EXIST."); //creating the non existing file System.out.println("creating new file..."); try { sample.createNewFile(); Thread.sleep(1000); System.out.println("File created..."); } catch(Exception e) { System.out.println("Exception..."); } //set only readable permission sample.setReadOnly(); //checking all permission System.out.println("Permissions of the file:"); System.out.println("The file is readable: " + sample.canRead()); System.out.println("The file is writable: " + sample.canWrite()); } } } See the following output. Finally, Java File Class Tutorial is over.
https://appdividend.com/2019/06/28/java-file-class-tutorial-java-io-file-class-in-java-example/
CC-MAIN-2020-29
refinedweb
1,379
50.94
Introduction Using Maps URLs, you can build a universal, cross-platform URL to launch Google Maps and perform searches, get directions and navigation, and display map views and panoramic images. The URL syntax is the same regardless of the platform in use. You don't need a Google API key to use Maps URLs. Universal cross-platform syntax As a developer of an Android app, an iOS app, or a website, you can construct a common URL, and it will open Google Maps and perform the requested action, no matter the platform in use when the map is opened. - On an Android device: - If Google Maps app for Android is installed and active, the URL launches Google Maps in the Maps app and performs the requested action. - If the Google Maps app is not installed or is disabled, the URL launches Google Maps in a browser and performs the requested action. - On an iOS device: - If Google Maps app for iOS is installed, the URL launches Google Maps in the Maps app and performs the requested action. - If the Google Maps app is not installed, the URL launches Google Maps in a browser and performs the requested action. - On any other device, the URL launches Google Maps in a browser and performs the requested action. It is recommended that you use a cross-platform URL to launch Google Maps from your app or website, since these universal URLs allow for broader handling of the maps requests no matter the platform in use. For features that may only be functional on a mobile platform (for example, turn-by-turn navigation), you may prefer to use a platform-specific option for Android or iOS. See the following documentation: - Google Maps Intents for Android — specifically to launch the Google Maps app for Android - Google Maps URL Scheme for iOS — specifically to launch the Google Maps app for iOS Launch Google Maps and perform a specific action To launch Google Maps and optionally perform one of the supported functions, use a URL scheme of one of the following forms, depending on the action requested: - Search — launch a Google Map that displays a pin for a specific place, or perform a general search and launch a map to display the results:¶meters - Directions — request directions and launch Google Maps with the results:¶meters - Display a map — launch Google Maps with no markers or directions:¶meters - Display a Street View panorama — launch an interactive panorama image:¶meters Important: The parameter api=1 identifies the version of Maps URLs this URL is intended for. This parameter is required in every request. The only valid value is 1. If api=1 is NOT present in the URL, all parameters are ignored and the default Google Maps app will launch, either in a browser or the Google Maps mobile app, depending on the platform in use (for example,). Constructing valid URLs You must properly encode URLs. For example, some parameters use a pipe character ( |) as a separator, which you must encode as %7C in the final URL. Other parameters use comma-separated values, such as latitude/longitude coordinates or City, State. You must encode the comma as %2C. Encode spaces with %20, or replace them with a plus sign ( +). Additionally, URLs are limited to 2,048 characters for each request. Be aware of this limit when constructing your URLs. Map actions The map actions available are: search, directions, display a map, and display a Street View panorama. You specify the action in the request URL, along with required and optional parameters. As is standard in URLs, you separate parameters using the ampersand ( &) character. For each action, the list of parameters and their possible values are enumerated below. Search The search action displays results for a search across the visible map region. When searching for a specific place, the resulting map puts a pin in the specified location and displays available place details. Forming the Search URL¶meters Parameters query(required): Defines the place(s) to highlight on the map. The query parameter is required for all search requests. - Specify locations as either a place name, address, or comma-separated latitude/longitude coordinates. Strings should be URL-escaped, so an address such as "City Hall, New York, NY" should be converted to City+Hall%2C+New+York%2C+NY. - Specify general search terms as a URL-escaped string, such as grocery+storesor restaurants+in+seattle+wa. query_place_id(optional): A place ID is a textual identifier that uniquely identifies a place. For the searchaction, you must specify a query, but you may also specify a query_place_id. If you specify both parameters, the queryis only used if Google Maps cannot find the place ID. If you are trying to definitively link to a specific establishment, the place ID is the best guarantee that you will link to the right place. It is also recommended to submit a query_place_idwhen you query for a specific location using latitude/longitude coordinates. Search examples Location search In a location search, you search for a specific location using a place name, address, or comma-separated latitude/longitude coordinates, and the resulting map displays a pin at that location. The examples below illustrate searches for the same location, CenturyLink Field (a sports stadium in Seattle, WA), using different location values. Example 1: Searching for the place name "CenturyLink Field" results in the following map: Example 2: Searching for CenturyLink Field using latitude/longitude coordinates as well as the place ID results in the following map: Example 3: Searching for CenturyLink Field using only latitude/longitude coordinates results in the following map. Notice that there is a pin in the map, but no additional place information is provided on the map or in the side panel: Categorical search In a categorical search, you pass a general search term, and Google Maps attempts to find listings that match your criteria near the location you specify. If no location is specified, Google Maps attempts to find listings nearby your current location. If you prefer to provide a location for a categorical search, include the location in the general search string (for example, pizza+seattle+wa). In the example below, a search for pizza restaurants in Seattle, WA, results in the following map: Directions Directions action displays the path between two or more specified points on the map, as well as the distance and travel time. Forming the Directions URL¶meters Parameters origin: Defines the starting point from which to display directions. Defaults to most relevant starting location, such as user location, if available. If none, the resulting map may provide a blank form to allow a user to enter the origin. an origin_place_idin your URL. If you choose to specify an origin_place_id, you must also include an originin the URL. origin_place_id(optional): A place ID is a textual identifier that uniquely identifies a place. If you are trying to definitively specify an establishment, using a place ID is the best guarantee that you will link to the right place. URLs that use this parameter must also include an origin. destination: Defines the endpoint of the directions. If none, the resulting map may provide a blank form to allow the user to enter the destination. a destination_place_idin your URL. If you choose to specify a destination_place_id, you must also include a destinationin the URL. destination_place_id(optional): A place ID is a textual identifier that uniquely identifies a place. If you are trying to definitively specify an establishment, using a place ID is the best guarantee that you will link to the right place. URLs that use this parameter must also include a destination. travelmode(optional): Defines the method of travel. Options are driving, walking(which prefers pedestrian paths and sidewalks, where available), bicycling(which routes via bike paths and preferred streets where available), or transit. If no travelmodeis specified, the Google Map shows one or more of the most relevant modes for the specified route and/or user preferences. dir_action=navigate(optional): Launches either turn-by-turn navigation or route preview to the specified destination, based on whether the origin is available. If the user specifies an origin and it is not close to the user's current location, or the user's current location is unavailable, the map launches a route preview. If the user does not specify an origin (in which case the origin defaults to the user's current location), or the origin is close to the user's current location, the map launches turn-by-turn navigation. Note that navigation is not available on all Google Maps products and/or between all destinations; in those cases this parameter will be ignored. waypoints: Specifies one or more intermediary places to route directions through between the originand destination. Multiple waypoints can be specified by using the pipe character ( |) to separate places (for example, Berlin,Germany|Paris,France). The number of waypoints allowed varies by the platform where the link opens, with up to three waypoints supported on mobile browsers, and a maximum of nine waypoints supported otherwise. Waypoints are displayed on the map in the same order they are listed in the URL. Each waypoint can be either a place name, address, or comma-separated latitude/longitude coordinates. Strings should be URL-escaped, so waypoints such as "Berlin,Germany|Paris,France" should be converted to Berlin%2CGermany%7CParis%2CFrance. Notes: - Waypoints are not supported on all Google Maps products; in those cases this parameter will be ignored. - This parameter is optional, unless you specify waypoint_place_idsin your URL. If you choose to specify waypoint_place_ids, you must also include waypointsin the URL. waypoint_place_ids(optional): A place ID is a textual identifier that uniquely identifies a place. Waypoint_place_idsallows you to provide a list of place IDs to match the list of waypoints. Place IDs should be listed in the same order as the waypoints, and separated using the pipe character " |" ( URL-escaped as %7C). If you are trying to definitively specify certain establishments, place IDs are the best guarantee that you will link to the right places. URLs that use this parameter must also include waypoints. Directions examples The following URL launches a map in directions mode and provides a form to allow the user to enter the origin and destination. The following example launches a map with bicycling directions from the Space Needle to Pike Place Market, in Seattle, WA. The following example launches a map with walking directions from Google in Sydney, Australia, to the Queen Victoria Building. Display a map The map action returns a map with no markers or directions. Forming the map URL¶meters Parameters map_action=map(required): Specifies the type of map view to display. Maps and Street View share the same endpoint. To ensure a map is displayed, the map_actionmust be specified as map. center(optional): Defines the center of the map window, and accepts latitude/longitude coordinates as comma-separated values (for example, -33.8569,151.2152). zoom(optional): Sets the initial zoom level of the map. Accepted values are whole integers ranging from 0 (the whole world) to 21 (individual buildings). The upper limit can vary depending on the map data available at the selected location. The default is 15. basemap(optional): Defines the type of map to display. The value can be either roadmap(default), satellite, or terrain. layer(optional): Defines an extra layer to display on the map, if any. The value can be one of the following: none(default), transit, traffic, or bicycling. Map examples This example URL launches a default Google Map, centered on the user’s current location. The following example displays a map centered on Katoomba, NSW, Australia (at -33.712206,150.311941), and sets the optional zoom and basemap parameters.¢er=-33.712206,150.311941&zoom=12&basemap=terrain Display a Street View panorama The pano action lets you launch a viewer to display Street View images as interactive panoramas. Each Street View panorama provides a full 360-degree view from a single location. Images contain 360 degrees of horizontal view (a full wrap-around) and 180 degrees of vertical view (from straight up to straight down). The pano action launches a viewer that renders the resulting panorama as a sphere with a camera at its center. You can manipulate the camera to control the zoom and the orientation of the camera. Google Street View provides panoramic views from designated locations throughout its coverage area. User contributed Photospheres, and Street View special collections are also available. Forming the Street View URL¶meters Parameters map_action=pano(required): Specifies the type of view to display. Maps and Street View share the same endpoint. To ensure a panorama is displayed, the actionmust be specified as pano. One of the following URL parameters is also required: viewpoint: The viewer displays the panorama photographed closest to the viewpointlocation, specified as comma-separated latitude/longitude coordinates (for example 46.414382,10.013988). Because Street View imagery is periodically refreshed, and photographs may be taken from slightly different positions each time, it's possible that your location may snap to a different panorama when imagery is updated. pano: The specific panorama ID of the image to display. If you specify a panoyou may also specify a viewpoint. The viewpointis only used if Google Maps cannot find the panorama ID. If panois specified but not found, and a viewpointis NOT specified, no panorama image is displayed. Instead, Google Maps opens in default mode, displaying a map centered on the user's current location. The following URL parameters are optional: heading: Indicates the compass heading of the camera in degrees clockwise from North. Accepted values are from -180 to 360 degrees. If omitted, a default heading is chosen based on the viewpoint (if specified) of the query and the actual location of the image. pitch: Specifies the angle, up or down, of the camera. The pitch is specified in degrees from -90 to 90. Positive values will angle the camera up, while negative values will angle the camera down. The default pitch of 0 is set based on on the position of the camera when the image was captured. Because of this, a pitch of 0 is often, but not always, horizontal. For example, an image taken on a hill will likely exhibit a default pitch that is not horizontal. fov: Determines the horizontal field of view of the image. The field of view is expressed in degrees, with a range of 10 - 100. It defaults to 90. When dealing with a fixed-size viewport, the field of view is considered the zoom level, with smaller numbers indicating a higher level of zoom. Street View examples The first two examples display a panorama of the Eiffel Tower. Example one uses only a viewpoint for the location, and sets the optional heading, pitch, and fov parameters. For comparison, example two uses a pano ID as well as the same parameters set in the first example. The third example displays an indoor panorama image. Example 1: Uses only a viewpoint to specify location. Example 2: Uses a pano ID as well as a viewpoint location. The pano ID takes precedence over the viewpoint. In this example, the panorama ID is found, so the viewpoint is ignored. Notice that the panorama image that is displayed for the pano ID is slightly different, and more recent, than the image found using only the viewpoint. Example 3: Displays a panorama of the interior of the Sarastro restaurant in London, UK, specified with a panorama ID. Finding a panorama ID To find the ID of a specific panorama image, there are multiple methods you can use. - For JavaScript, use the StreetViewPanorama class. - For Android, use the public class StreetViewPanoramaLocation. - For iOS, use the GMSPanorama class. - You may also make metadata requests using the Google Street View Image API. Image metadata requests provide data about Street View panoramas, including the panorama ID. More examples Directions examples using waypoints The following directions examples launch Google Maps and display driving directions from Paris, France to Cherbourg, France, routing through the following waypoints: In the example URLs, the waypoints are defined in different ways so you can compare the differences in the display of the waypoints on the resulting maps. Example 1: Waypoints defined as City, Country: Example 2: Waypoints defined as specific place names: Example 3: Waypoints defined as City, Country, and also provides waypoint_place_ids for a specific establishment in each waypoint: Example 4: Defines waypoints as City, Country, but lists the waypoints in a different order compared to the previous examples. Demonstrates that the map displays waypoints in the order they are listed in the URL. Map examples Displays a map with a specified basemap (satellite) and layer (transit).¢er=37.7992940,-122.3976113&zoom=15&basemap=satellite&layer=transit Street View examples Displays a Street View panorama using a FIFE image key as the pano ID. Note that the pano ID is prefaced with F:.
https://developers.google.cn/maps/documentation/urls/guide?hl=tr
CC-MAIN-2019-51
refinedweb
2,822
53.41
29 August 2012 11:58 [Source: ICIS news] SINGAPORE (ICIS)--Asia’s monoethylene glycol (MEG) spot prices gained $14-28/tonne (€11-22/tonne) to a five-month high on Wednesday on concerns over supply as large-scale plants in Louisiana, US, may have been shut in the wake of Hurricane Isaac, market sources said. MEG was assessed at $1,045-1,068/tonne CFR (cost and freight) China Main Port (CMP) at the close of trade, according to ICIS. Some spot MEG lots were settled at $1,065-1,070/tonne cost & freight (CFR) China Main Port (CMP) in the late afternoon, while traders booked material in the morning at $1,045-1,050/tonne CFR CMP. “We are not sure whether the major US MEG plants have been shut, but traders are actively bidding up prices,” a major regional trader said. ?xml:namespace> A number of refinery and petrochemical operations in the US Gulf were shut because of Hurricane Isaac, which made a landfall in Shell Chemical runs a 125,000 tonne/year and 250,000 tonne/year MEG plants
http://www.icis.com/Articles/2012/08/29/9590671/Asia-MEG-rises-14-28tonne-on-concerns-over-US-supply.html
CC-MAIN-2015-22
refinedweb
182
56.73
HL7 Schemas and Available Tools This chapter provides an overview of the Ensemble tools that you can use to work with HL7 Version 2 schemas and documents. It contains the following sections: Using the HL7 Schema Structures Page Using the Custom Schema Editor Using the HL7 Message Viewer Page Overview of HL7 Schemas and Messages Ensemble can process and pass through an HL7 message without using a schema to parse it, but associating a schema with a message allows you to do the following: Parse the message and access field values in: Data transformations Routing rules Custom ObjectScript code Validate that the message conforms to the schema. Each HL7 message is identified by a message type, which is specified in the MSH segment MessageType field (MSH:9). Some message types share the same message structure. For example, in HL7 Version 2.3.1, the ADT_A05 message to pre-admit a patient has the same structure as the ADT_A01 admit message. The schema specifies that the ADT_A05 message has the structure type ADT_A01. In order to parse an HL7 message, Ensemble needs two pieces of information: Schema category—this is the HL7 version number, such as 2.3.1 or 2.7, or it may be a category for a custom schema defined in Ensemble. Ensemble gets the schema category from the business service Message Schema Category setting or from the Data Transformation settings. Although the HL7 message includes a schema version number in the MSH segment VersionID field (MSH:12), Ensemble does not use this value because many applications do not set this field consistently. Structure type—Ensemble gets the message type from the MSH:9 field and then checks the schema definition to get the structure type for that message. Ensemble uses the MSH:9.3 subfield to qualify the message type in some cases. The MSH:9:3 subfield is used in HL7 messages in two ways: 1) as a modifier to the message type, or 2) to specify the structure type. If MSH:9:3 modifies the message type, typically as a numeric digit, Ensemble includes it as part of the message type. If MSH:9:3 specifies a structure type, such as ADT_A01, Ensemble ignores it in both determining the message type and setting the Name property. Ensemble does not need the MSH:9.3 subfield to determine the structure type because it gets the structure type from the schema. When a business service or Data Transformation creates an EnsLib.HL7.Message object to store an HL7 message, it combines the schema category and structure type and stores it in the DocType property using this syntax: category:structureType For example, valid DocType values for category 2.3.1 include 2.3.1:ACK, 2.3.1:ADT_A17, 2.3.1:BAR_P01, and 2.3.1:PEX_P07. The message type, which can be different from the structure type is stored in the Name property. If you create an EnsLib.HL7.Message object in ObjectScript code, you should set the DocType and Name properties based on the value in the MSH:9 field. The HL7 standard allows local extensions, such as trailing Z segments. These segments are not defined in the base schema categories. If you want to access a field in a custom Z segment in a data transformation, routing rule, or ObjectScript, you need to define a custom schema category that specifies the extended message. See “Using the Custom Schema Editor” for details on defining a custom schema. Using the HL7 Schema Structures Page The HL7 Schemas page enables you to import and view HL7 Version 2 schema specifications. To display this page, navigate to Ensemble > Interoperate > HL7 v2.x > HL7 v2.x Schema Structures from the Home page. For general information on using this page, see “Using the Schema Structures Page” in Ensemble Virtual Documents. The HL7 Schemas page provides an additional tab: Message Types. This tab identifies two message structures as a request/response pair. Ensemble includes the following HL7 schema versions: 2.1 2.2 2.3 2.3.1 2.4 2.5 2.5.1 2.6 2.7 2.7.1 For information on creating and editing custom schema categories, see “Using the Custom Schema Editor”. Note that HL7 Version 3 is not listed as an HL7 schema category, because it uses entirely different data conventions from HL7 Version 2. For details, see the Ensemble HL7 Version 3 Development Guide. The following example shows how to use this page in more detail. Viewing a List of Document Types To list all the document type structures in a category, first select the category and then click the DocType Structures tab. Viewing a Message Structure To view the internal organization of a message structure, click its name from the DocType Structures tab on the HL7 Schemas page. Ensemble displays the segment structure of the message using the system of visual cues explained below. This is the HL7 Schema Message Structure page. The following example shows the 2.3.1:ORM_O01 message structure. The visual conventions on this page are as follows: The segments that comprise the message structure are listed in sequential order, from left to right and top to bottom. The three-letter name of each message segment is displayed: MSH, NTE, PID, etc. This name indicates the type of segment that exists at this location in the HL7 message structure. Segment names must be all uppercase. Green dotted lines enclose segments, groups, or fields that are optional. Brown solid lines enclose segments, groups, or fields that, if present, may repeat several times. Yellow dashed lines enclose a choice: this is a union of segments. Only one segment from the union can appear at this location within the message structure. It may be any of the segments listed. A segment, group, or field may be both repeating and optional (see any NTE above). To see the message structure in a raw text format, click Show Raw Definition Text. When you are viewing a segment diagram, if you hover the cursor over a three-letter segment name, a tooltip displays the syntax for referring to this segment in a virtual property path. The message structure name displayed before the diagram has two parts, separated by a colon: category:structure Where: category is the name of a schema category, such as 2.3.1. structure is the name of a message within that schema category. Viewing a Segment Structure To view the structure of a message segment, click on its name in any page similar to the example shown in the previous section. Ensemble displays a table that lists all the fields in that segment. This is the HL7 Schema Segment Structure page. For example, if you click the PR1 segment in the 2.3:ADT_A01 message structure, Ensemble displays the following page. The columns are as follows: Field — the number to use to access the field within the segment (if you prefer numbers). Description — a short description of the field. Property Name — the name to use to access the field within the segment (if you prefer names). Data Structure — for more complex field values that use a data structure, you need further syntax details before you can complete the segment:field virtual property path. You can get this by clicking on the name in this column Symbol — indicates the syntax rules for the field. The characters in this column indicate whether you can expect this field to be present, absent, or repeated within the message segment. Possible values are: Repeat Count — the maximum number of times the field can repeat (if it repeats, and if there is a maximum). Minimum Length — the minimum number of characters in the field. Each repeat of the field must contain this number of characters. Maximum Length — the maximum number of characters in the field. Each repeat of the field may contain this number of characters. Required — displays R for required, O for optional. Repeating — displays 1 for true, 0 for false. Code Table — click on an entry to view the valid codes that may be entered in this field. Alternate Description — a second, longer description of the field. You can use this information, particularly the Property Name column, to build virtual property paths for Ensemble in the format segment:field. The following are examples of virtual property paths involving simple field values from the PR1 segment in the 2.3:ADT_A01 message structure. The () shortcut syntax indicates all available instances of a repeating field, whereas (1) indicates the first instance: PR1grp().PR1:ProcedureType PR1grp().PR1:ProcedureCode() PR1grp().PR1:ProcedureCode(1) PR1grp().PR1:ProcedureCode(x) PR1grp().PR1:ProcedurePriority Viewing a Data Structure When you click on a name in the Data Structure column, Ensemble displays all the fields in that data structure. This is the HL7 Data Structure page. The following columns of the display are most useful: The Component column lists the numbers you can use to access fields within the segments (if you prefer numbers). The Property Name column lists the names you can use to access fields within the segments (if you prefer names). Click on an entry in the Data Structure column (if any) to drill down for detail. Click on an entry in the Code Table column (if any) to view the valid codes that may be entered in this field. The following sample page appears when you click the Data Structure item called 2.3:XCN in the segment structure page above. The page states that the category 2.3 data structure XCN describes an “Extended Composite ID number and name” and consists of fourteen fields. Of these, some are simple values, some are data structures, and some are codes. Given this information, you can create virtual property paths for the complex PR1grp().PR1:Surgeon field in the message structure 2.3:ADT_A01 as follows: PR1grp().PR1:Surgeon.familyname PR1grp().PR1:Surgeon.degree Viewing a Code Table When you click on a name in the Code Table column, it lists and explains the valid codes for that field. This is the HL7 Code Table page. The following sample page appears when you click the Code Table item called 2.3:200 in the data structure page shown in the previous section. The example above shows that the category 2.3 code table 200 describes a “Name type” that can have the value L, O, M, A, C, or D. This means that if you have an HL7 message with a DocType of 2.3:ADT_A01, it has an optional virtual property with the path PR1grp().PR1:Anesthesiologist.nametype that can contain one of the following values: L, O, M, A, C, or D. For details, see “Syntax Guide” in Ensemble Virtual Documents. Choosing a Different Category It is a feature of the HL7 standard that a message structure can differ by HL7 version, even when the structure has the same name and number. For example, both HL7 2.4 and HL7 2.5 define a message structure called ORD_O04, but these definitions contain different segments. Ensemble provides the message structure definitions 2.4:ORD_O04 and 2.5:ORD_O04. The HL7 Message Structure page makes it easy to see the differences between the two definitions, as the following two figures show. Using the Custom Schema Editor The Custom Schema Editor allows you to create a new custom HL7 schema or edit an existing custom HL7 schema. Typically, a custom schema has a base schema, which is a standard schema or another custom schema. When Ensemble is using the custom schema to parse a message, if the message type, segment, or other element is not defined in the custom schema, it uses the definition in the base schema. Consequently, you only have to define the elements in the custom schema that are not present in the base schema or require a different definition from the one in the base schema. You cannot edit a standard schema. The most common reason to define a custom schema is to be able to parse HL7 messages with trailing Z segments. Ensemble can handle messages with trailing Z segments that are not defined in the schema, but to do any of the following you need to define a custom schema: Access field paths in the trailing Z segments in a routing rule, data transformation, or ObjectScript code. Validate the trailing Z segments. If you have a production that is currently using a standard schema and you need to access trailing Z segment field paths in a data transformation or routing rule, you should do the following: Use the Custom Schema Editor in the Management Portal to create a new HL7 schema. Enter a name for the custom schema and specify the base schema. Define the Z segment that can appear in your message. If your Z segment has similar fields to an existing segment in the base schema, you can copy the definition from the base and then modify it as needed. Otherwise, you can create a new segment. You can add fields, delete fields, or change the order of fields. For each message type that includes the trailing Z segments, create a message type and structure type in the custom schema that is copied from the underlying schema. Add the Z segment to the end of the structure type. Modify the business service in your production to use the new custom schema instead of the base schema. Test the production by supplying new messages with the trailing Z segments to the production’s business services. If you view the messages in the message viewer, the Z segments will be shown in blue if they are defined in the schema. Unrecognized segments are shown in black. Detailed instructions are in the following sections. Creating a New Custom Schema To start the Custom Schema Editor from the Management Portal, select Ensemble, Interoperate, HL7 v2.x, and HL7 v2.x Schema Structures. To create a new HL7 schema, click New. In the Custom Schema Editor, select the base schema, schema name, and, optionally, a schema description. For example, to define a custom schema based on the Version 2.5 standard schema category, you could enter the following: Once you have created the custom schema, the Custom Schema Editor presents you with an empty schema, and you can define the message types, structure types, segment structures, data structures, and code tables in it. You have to define only the elements that have different definitions than those in the base schema or that are not defined in the base schema. The Custom HL7 Schema Editor has the following tabs: Message Types DocType Structures Segment Structures Data Structures Code Tables On each of these tabs, you can copy the elements from an existing base definition by selecting Copy From Base. This allows you to create a message type or other element that is an extension of an existing definition without having to reenter the common definitions. Defining a New Segment To define a new Z segment, select your new custom schema in the left panel and then select the Segment Structures tab. For custom schemas, the Segment Structures tab has the New and Copy From Base buttons and lists the segments that are currently defined in the custom schema. Since the schema doesn’t have any segments defined, the segment structure list is empty. If you are viewing a standard schema, you cannot add new segments and the buttons are not present If you want to define a new segment without copying fields from another segment, click the New button and the wizard creates an empty segment. Name the segment and click the Add Field button. The wizard creates an empty field and you can fill in the form. For example: If you are creating a segment that is very similar to an existing segment in the base schema, you should choose Copy From Base, it creates a new segment with the same fields as the specified segment. The Custom Segment Structure Wizard displays the copied fields and has a New button after the fields to create a new field. For example, the following segment was copied from the PID segment. Once you have creating the segment either as a new segment or as a copy of a base segment, you can add or update fields as follows: Click the Add Field button to add a field at the end of the segment. Update the form text boxes that define the segment field. You cannot edit the Property Name text box. The wizard sets the property name based on the field Description value after it removes any spaces or special symbols. The property name is set when you click OK to end the wizard. Change the order of a field by clicking on the up or down arrows. Delete a field from the segment by clicking the red X. When you have completed entering the fields, click OK to save the segment. You can edit any saved segment in a custom schema by clicking on the segment name and then clicking Edit. Once you have defined your Z segments, you should define the message types and structure types that contain the Z segments. Defining a New Message Type and Structure Type The Message Type identifies the message and matches the value in the HL7 MSH:9 field. When you define a message type, you specify the sending message structure type, which may be the same as the message type, and the return type. But you specify the segments that can be in the message in the structure type not in the message type. When you create a message type, you can optionally create a structure type at the same time. To add a Z segment to a message type that is defined in the base schema, copy the message type and structure to the custom schema and then add the trailing Z segment to the structure type. For example, to add the ZPI segment to the ORU_R01 message in a custom schema that has Version 2.5 as the base schema, do the following: Select your custom schema in the left panel, select the Message Types tab, and click Copy From Base. Select the ORU_R01 message type in the Message Type to Copy pull-down. The wizard fills in the new message type name to be the same as the copied message type and sets the Sending Message Structure and Returning Message Type to match the definition in the base. By checking the box, you automatically create the sending message structure in the custom schema if it is not yet defined. It is created by copying the structure from the base schema. After you click OK, the ORU_R01 message type and the ORU_R01 structure type are defined in the custom schema. Click the DocType Structures tab and the ORU_R01 structure type. The custom schema editor displays the graphical representation of the structure type. Click the Edit button. The Custom Message Structure Wizard displays the following: Message Structure Name Description Raw Definition—To edit the structure, you edit the raw definition and then click Save. The raw definition uses the same convention as Studio to describe the structure. Each element is separated by ~ (tilde character), optional segments are indicated by [] (square brackets) and repeating segments are indicated by <> (angle brackets). All Segments—This list contains all segments defined in the custom schema and base schema. You can type the segment names listed into the raw definition. Visual Representation—This graphic description of the structure is updated whenever you save the raw definition. Update the raw definition by entering ~[~ZPI~] at the end of the definition to indicate that the trailing Z segment is optional. Click Save to save the raw definition. The wizard updates the visual representation. Click OK to end the wizard. For example, if you are using the Custom Message Structure Wizard to edit a copy of the ORU_R01 structure type, the wizard displays the following: The Undo button reverts your previous key stroke. The Save button saves the raw definition. The Previously Saved button undoes all changes and reloads the last saved definition. The Legend button displays a help message that explains the raw definition syntax. When you are extending a message definition from the base schema, you should use the same segment and structure name as specified in the base schema. Once you have defined a message structure in the custom schema, that definition is used for all message types that share the same structure. For example, if you add the ZPI trailing segment to the ORU_R30 structure, the trailing Z segment is allowed in the ORU_R30, ORU_R31, and ORU_R32 message types because they all share the same ORU_R30 structure. It is not necessary to include the message types in the custom schema. The definition from the base schema will use the structure type from the custom schema. Editing Data Structures and Code Tables Data structures provide a mechanism to specify a field that has a structured value rather than a simple data type, and code tables provide a mechanism to define a set of allowed values for a field. Typically, data structures and code tables are defined by the HL7 standard body and are not defined as custom extensions. The Custom HL7 Schema Editor does allow you to define data structures and code tables in your custom schemas in the rare cases where this is needed. The wizard to edit data structures is very similar to the wizard to edit segments. The wizard to edit code tables allows you to define codes and descriptions for the code table. The codes specify the values that can be used in a field. Using the HL7 Message Viewer Page Ensemble provides a Message Viewer page for HL7. You can use this page to display, transform, and export HL7 messages (either external files or messages from the Ensemble message archives). To access this page: Click Ensemble. Click Interoperate. Click HL7 v2.x. Click HL7 v2.x Message Viewer and then click Go. stored documents loaded from a file.) None — Do not use any DocType to parse the document. Instead, display the raw segments without transforming any of them into Message The Message Viewer displays the following on the right side of the screen after completing the steps above: Summary Report, which contains following basic information about the document: The Data Transformation applied, if applicable The Message ID The DocType The DocType Category The DocType description, if available The number of segments The number of child and parent documents, if applicable Message Data, which has one row for each segment in the message structure. Each row contains: Segment number Segment name, such as PID or NTE Field contents and separators, as contained in the message If the message matches the schema you have selected, segments and elements will appear in blue, as seen below. Clicking on the segments or fields will link to the relevant structure page. Displaying the Segment Address To display the segment address, hover the cursor over a segment name in the shaded column. The tooltip displays the following: Segment address to use in a virtual property path Descriptive name of this segment Displaying the Field Address To display the field address, hover the cursor over a field within the message structure. The tooltip displays the following: The field address to use in a virtual property path (as a number) The field address to use in a virtual property path (as a name) Characters that indicate the syntax rules for this field. The characters can begin with: Batch Messages If a field is enclosed with angle brackets (<,>) it is a link to a sub-document. Click on it to view that document’s summary report and message data. Also see “Viewing Batch Messages,” later in this chapter. Testing a Transformation To test a transformation: Click. For example, if you installed Ensemble into the directory C:\MyCache and your current namespace is ENSDEMO, the file is saved as C:\MyCache\Mgr\ENSDEMO\filename Viewing Batch Messages The HL7 Document page handles a message differently if it is a group of HL7 messages in batch format, rather than a single HL7 message. Specifically, it allows you to walk through the batch message structure one level at a time. The following display is the result of asking to view a batch message that begins with an FHS segment. Ensemble parses the batch message and finds that it has 3 segments: FHS, FTS, and a block of child documents in between. The block contains two child documents; each beginning with BHS and ending with BTS. The message is a two-level batch message. The Message Viewer assigns the child documents the identifiers <2> and <33>. It displays the top-level parent document, using links (<2> and <33>) to represent the two child documents. The display is as follows: When you click on a child document link in an HL7 batch message display, a new browser window opens to display the child document. The Message Viewer window, with the top-level parent, remains open in the original browser window. The next display is the result of clicking the child document link <2> in the previous display. This example is a two-level batch message, so the child document <2> has children of its own: child documents <3> through <32>. This example highlights a useful navigation feature of the Message Viewer. If there are more than 10 child documents in a batch message, the Message Viewer displays links to the first five and last five child documents. Between the lists is a text field, into which you can enter any identifier number between the first and last numbers. After you enter a number, click Other. A new browser window opens to display the child document. The next display is the result of clicking the child document link <6> in the previous display. Since this is the lowest level of the batch message hierarchy, message <6> is a normal HL7 Version 2 message that begins with an MSH segment. When you are done viewing messages in the batch message hierarchy, you can close all the pop-up browser windows until the top-level parent document remains in the original Message Viewer window. From here, you may return to other Management Portal activities. HL7 Classes For reference, this section lists the classes that Ensemble provides to enable you to work with HL7 Version 2 documents. You can also create and use subclasses of these classes. The business host classes include configurable targets. The following diagram shows some of them: For information on other configurable targets, see “Reference.” Details on the HL7 Message Class Ensemble provides a built-in class for HL7 Version 2 virtual documents. The class is EnsLib.HL7.Message. For basic information on virtual document message classes, see “Virtual Document Classes” in Ensemble Virtual Documents. In addition to the basic properties and methods, EnsLib.HL7.Message provides the following properties: The TypeCategory property contains an HL7 category name. Typically, the HL7 business service that receives HL7 data from outside Ensemble instantiates an HL7 message and assigns a TypeCategory value to it. Ensemble combines this TypeCategory with the message type declared in the MSH segment of the incoming message data; this combination identifies a <MessageType> within the HL7 schema definition. This <MessageType> has an associated <MessageStructure> that Ensemble uses as the DocType for the HL7 message, if no other DocType is assigned. The Name property is a read-only string that contains the HL7 message structure name (such as ADT_A08 or ORM_O01) that the external data source has provided in the MSH segment. The Name can be useful in determining the HL7 message structure that the clinical application thinks that it is sending, although this can differ from the actual message contents.
https://docs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY=EHL72_TOOLS
CC-MAIN-2021-10
refinedweb
4,645
62.38
Created on 2012-01-16 23:22 by terry.reedy, last changed 2017-07-21 02:36 by terry.reedy.> Hi Terry, just take/put away some ... (they're not in a special order nor preference, just some that could 'see' in the browser). Add the string with pangram and chinese, now sample text shows: AaBbCcDdEe FfGgHhIiJjK 1234567890 #:+=(){}[] The quick brown fox jumps over the lazy dog. [1] 南去經三國,東來過五湖 [2] ---------------------- [1]: [2]: There are many different alphabets in the world. Why Chines but not Cyrillic or Devanagari? An example that includes all scripts would be too large (and likely most characters would not be rendered correctly with an arbitrary font). I suggest just make the box for examples editable and save entered examples in the configuration files. Serhiy: Or would it be to detect the user language environment, and come up with user language example sentence? What I remember that Windows font preview will change the sentence in the different language. I don't think that it is worth to include in Python distribution examples for a hundred of languages. If there are some system-wide collections of examples we can use them, but this should be platform specific and not always available. On other hand, we can use the standard font chooser dialog. But it doesn't allow to configure the sample text at all (at least on X Window). Terry, try please the following commands on Windows: import tkinter root = tkinter.Tk() root.tk.call('tk', 'fontchooser', 'show') How it looks? I made this issue a dependency of #24776, which is about redoing the whole font page. The fontchooser has good, inappropriate for IDLE, and bad points. I consider it an alternate mockup proposal for the font page. For this issue: displaying each font name in the font is cute, but I am not sure I want to imitate. I address the sample selection below. This issue is about making it evident that IDLE is a BMP unicode editor, not just an ASCII editor; and about showing the consequence of font choices on a particular OS and machine. Expanding the static sample with example of the top N scripts, with N about 10, will do this. When I looked at Francis's patch, I thought it deficient in that people would not know what chars were being replaced by boxes. Then I tried the patch and none of them were. At least not on Windows. Since I opened this, we added back the Help button. Added help text for this tab can list the scripts represented in the sample. If nothing else, I will use this patch, as it improves of the status quo. I should have done this years ago. An immediate improvement would be all chars from a script on one line and some (more?) hanji/kanji CJK chars. #24776 suggests putting the sample beside the font selection box. The font box only needs 75% of the width it has. With the frame around the sample label removed, there may be more width available. There will certainly be more lines. Louie, I understand your PR to be a suggestion about pangrams, expressed in code, to be 'pulled' into my mind, and possibly into my clone, and not a request to merge as is with only Chinese. Others have noted that submitting work-in-progess patches as PRs, rather than as diffs to the tracker, can be confusing. Yet it makes review easy. In considering the idea, I looked at and also found, which lists pangrams in multiple languages that were once on wiki/List_of_Pangrams. I am rejecting the idea as is for multiple related reasons. The sample is about scripts, not languages. Long phrases mean fewer scripts. Many scripts are used for multiple dialects or even languages. Which one to choose? An innocent or poetic phrase in one language may be less innocent in another dialect/language, or if interpreted metaphorically, or one consider possible alternate meanings of words. One thing I would consider is script names written in the script. This would replace an arbitrary sample from the same script and could be done on a script-by-script basis. I believe 'devanagari' in Devanagari should be intelligible in all or most north Indian languages that use Devanagari or derivatives thereof, and offensive in none. But I would enquire. What do others think of this? Louie, I presume 'hanji' is a single char. How about using the stroke pangram 永 (all basic strokes) in a phrase such as 'hanji character 永'? (I like the look of the char as well). Serhiy, is there one non-controversial pan-slavic way to write 'Cyrillic' in Cyrillic? Or controversy-engendering national variations? A separate issue could add a button and dropdown multiple selection list to print to an output window all or a selection of the 256 blocks of 256 codepoints in the BMP. This should eliminate any need for a configuration option. > likely most characters would not be rendered correctly with an arbitrary font A goal of this issue is to let people see such problems where they exist. The fontchooser sample awful. Only couple of ascii and script chars and a small sample of script that changes with each script. It has no knowledge of default characters. > Serhiy, is there one non-controversial pan-slavic way to write 'Cyrillic' in Cyrillic? No. Even in very close east-slavic languages it is written differently: Ukrainian "Кирилиця", Russian "Кириллица", Belarusian "Кірыліца". I decided to rearrange page #24776 before changing sample #13802.
http://bugs.python.org/issue13802
CC-MAIN-2017-34
refinedweb
924
74.69
CodePlexProject Hosting for Open Source Software hmm. I examined this over the weekend. The fact the page has incomplete content is disappointing. It undermines their conviction slightly I think. The main argument appears to be that Strong Naming can introduce version resolution issues. When I dug into this further I realised that this is actually a feature of strong naming and not a design bug. One of the named purposes of strong naming is to allow the running of different dependency versions side-by-side. From what I can see, most of the problems raised in that page can also be obviated when publishers include a publisher policy in newer versions of their libraries. But I take your point that strong naming is not considered a security tool, it's more akin to a guaranteed unique namespace. Although it beggars belief that on one hand Microsoft implies strong naming has no security benefits, yet with the other, mandates it as a requirement for defining fully trusted assemblies. Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://foolproof.codeplex.com/discussions/648894
CC-MAIN-2017-22
refinedweb
203
65.42
On 2012-09-13 10:47, Marcel Reutegger wrote: > hi, > > remapping an existing namespace prefix in the namespace registry > somewhat breaks existing content. say we create a node foo:test, > save it and then remap prefix 'foo' to 'bar' in the namespace registry. > reading the same node again will still return foo:bar, however 'foo' > is not valid namespace prefix anymore. Was this done on purpose > or this a bug? Overall, it's bug^h^h^hlimitation. I believe the alternatives are: - disallow remapping of prefixes (or of prefixes in use), or - try to rewrite all of the content. How is Jackrabbit handling this? Best regards, Julian
http://mail-archives.apache.org/mod_mbox/jackrabbit-oak-dev/201209.mbox/%3C5051A467.4060207@gmx.de%3E
CC-MAIN-2016-07
refinedweb
107
67.45
Agenda See also: IRC log <benadida> examples by DanBri Steven: I'm also working with Ivan Herman on some examples; Ivan manages the presentation of W3C Talks (from the W3C home page) using RDF. He's looking into representing the Talk data in RDF/A <benadida> previous meeting 2005-07-12 ACTION: Steven send wording for 23.2 to mailing list -- done; Wording for 23.2 Ralph: do you expect that 23.2 will be definitive for all the ways in which an RDF triple can be extracted from RDF/A? Steven: yes, modulo bnodes Ben: what about inheritance? Steven: inheritance is intended to be covered <Steven> That's why the text says "the about property" rather than "the content of the about attribute", since it takes inheritance and defaults into account. ACTION: Ben to notify working group via a status report of upcoming WD of Note -- continues BenA: regarding GRDDL profile, does HTML WG understand that there may be a document at the namespace URI that contains a transform? Steven: yes, that should be fine. Some of these administrative details will happen after Last Call. If you really want an issue to be tracked, send a message to www-html-editor ACTION: Ben send mail to www-html-editors to assign an issue for the GRDDL namespace document behind the profile [recorded in] ACTION: Ben create a way to track progress on the 3 issues of qnames, reification, and custom attributes and elements -- continues Ben:It may be simple enough to create a Web page for tracking these; we can add the other issues to this same document ACTION: jjc to circulate www conf paper -- continues Ralph: Jeremy's paper on RDF/A was suggested as the basis for a WG document at the 27 June WG telecon. I took an action from that meeting to suggest that here: ACTION: Ralph suggest to XHTML TF that Jeremy's WWW2005 Talk be turned into a document [recorded in] [DONE] ACTION: take a serious look at Mark's bnode proposal summary -- continues ACTION: Mark to create an rdf/a wiki -- continues (though some evidence of action) ACTION: Mark to check edge cases of inheritance in RDF/A -- continues ACTION: Ben to put together the "ACID" test for XHTML2 RDF/A -- continues; some progress ACTION: danbri record an issue re # vs / -- continues Ralph:I don't recall the details of this action Ben: perhaps regarding 302 responses? ACTION: Ben to coordinate with Mark for next week's meeting [DONE] Ben: I will continue to do this coordination Steven: status of response to Bjoern Hoehrmann? Ben: I have a draft reply but waiting on the Bag question. The response is also tied up in inheritance question. I don't want to send a response for the record until we have a 100% correct solution Next Meeting: 26 July Ben: I expect to be able to attend through August 9, won't be able to attend from 16 Aug for 6 weeks ... what are the current expectations for XHTML2 Last Call? Steven: The HTML WG really hopes to go to Last Call before our September face-to-face
http://www.w3.org/2005/07/19-swbp-minutes.html
CC-MAIN-2018-30
refinedweb
524
52.02
Hello All, OK, this should hopefully be a simple issue but I can't seem to find the answer. I started a project with CW10.3 for the HCS08 CPU (S08AW60) and when I started the project wizard I did not select the floating point library. Now I find myself wanting to use floating point for 1 calculation but I can't find the setting to use the correct floating point lib. I am using the ADS1118 for thermocouple measurement and I need to calculate the internal temperature sensor value: #include <float.h> float Temp_Sensor; int Sensor_Reading; Temp_Sensor = (float)Sensor_Reading * 0.03125; //calculate degrees When I compile this I get the following errors: I am pretty certain the issue is the missing floating point library. Can anyone tell me where I go to include the floating point libraries in my project? I looked all through the project settings and don't see a "use floating point libraries" check box. Thanks, Dave Hello, the different library file names are described in C:\Freescale\CW MCU v10.3\MCU\lib\hc08c\readme.txt. Remove the __NO_FLOAT__ from the compiler preprocessor setting in the project options. And in the linker Input settings change the library to the other one you want as described in the readme.txt. This should do it.
https://community.nxp.com/thread/304640
CC-MAIN-2018-43
refinedweb
218
72.66
!- Search Loader --> <!- /Search Loader --> At my workplace, we are upgrading the Intel TBB library to Version 2020. After integrating the library we have started seeing deprecation warnings on all the platforms. On windows (MS Visual Studio 2017), these warnings are treated as error and on macOS (XCode 10.14) , Linux (GCC 6.3) these are warnings are displayed as harmless pragma message. For ex. on Windows the warning will be as below 1: foo.cpp 2: c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\exception(375): warning C4996: 'tbb::captured_exception::~captured_exception': was declared deprecated 3: C:\path\tbb\include\tbb\tbb_exception.h(206): note: see declaration of 'tbb::captured_exception::~captured_exception' 4: C:\path\tbb\include\tbb\tbb_exception.h(345): note: see reference to function template instantiation 'std::exception_ptr std::make_exception_ptr<tbb::captured_exception>(_Ex) noexcept' being compiled 5: with 6: [ 7: _Ex=tbb::captured_exception 8: ] On linux and macOS ../path/tbb/include/tbb/task_scheduler_init.h:21:154: note: #pragma message: TBB Warning: tbb/task_scheduler_init.h is deprecated. For details, please see Deprecated Features appendix in the TBB reference manual. #pragma message("TBB Warning: tbb/task_scheduler_init.h is deprecated. For details, please see Deprecated Features appendix in the TBB reference manual.") While Linux and macOS are OK for the time being, (as we will migrate to newer or standard library features as suggested in the warnings and Intel TBB Webpages here and here) whats concerning us is the warnings on the Windows platform as mentioned above. There are more than 1200 instances of this particular warning and all of them are emanating Intel TBB header file tbb_exception.h. The warning is highlighting 1) MSVC's header file exception since tbb_exception.h's deprecated classes are using exception header's classes 2) Any header file that includes tbb_exception.h e.g. concurrent_map.h We are aware that we can suppress these warnings via TBB_SUPPRESS_DEPRECATED_MESSAGES macro. Having said all this, is the TBB development team aware of this issue of warnings and this particular warning emanating from tbb_exception.h ? If yes, do they plan to get rid of these warnings in the future version of TBB library ? Hello, We are transitioning to oneTBB: with what we call revamped TBB API. Please see the document that you can access from the link mentioned here: or directly In oneTBB these features that you see now as deprecated -- will be removed. So longer turn we hope that you can consider switching to new API. Please let us know if you see any problems with this proposal. Meanwhile, we will continue to support old API with TBB 2020 product (and earlier versions). Are you concerned that there are too many messages about deprecation are printed? Were you aware of the information above? Hello, Both cases look strange, could you provide more details regarding build environment (compiler version, OS version, build options)? Hi folks, Thanks for your response. 1) I have updated the post with "Small standalone reproducible example". It contains info regarding build environment (compiler version, OS version, build options). The thing that we have observed is that it if we include any TBB header after standard exception header i.e. #include <exception> #include "tbb/concurrent_queue.h" it blurts out this warning from the header file tbb_exception.h. If the order is reversed, warning disappears. Let us know if there are any workaround(s) or separate flag to get rid of this warning. Or is there just one flag for now i.e. TBB_SUPPRESS_DEPRECATED_MESSAGES ? 2) Yes we are aware of TBBRevamp.pdf document and we are going to recommend our developers to change their code to honor that :) Hi Recker, These extra warnings were caused by environmental issues in some VS versions. Thank you for reporting! This problem will be solved in future releases. Thanks for your response. One more thing, for the same platform and compiler combination(s) a small code like below will blurt out the #pragma message #include "tbb/atomic.h" int main() { return 0; } Linux : tbb/include/tbb/atomic.h:21:141: note: #pragma message: TBB Warning: tbb/atomic.h is deprecated. For details, please see Deprecated Features appendix in the TBB reference manual. #pragma message("TBB Warning: tbb/atomic.h is deprecated. For details, please see Deprecated Features appendix in the TBB reference manual.") Windows TBB Warning: tbb/atomic.h is deprecated. For details, please see Deprecated Features appendix in the TBB reference manual. This is ok since the whole header is getting deprecated.
https://community.intel.com/t5/Intel-oneAPI-Threading-Building/Intel-TBB-Version-2020-Warnings/td-p/1182898
CC-MAIN-2020-50
refinedweb
749
51.24
Join us in Chat. Click link in menu bar to join. Unofficial chat day is every Friday night (US time). 0 Members and 1 Guest are viewing this topic. using System;class ExampleClass{ static void Main() { System.Console.WriteLine("Hello, world!"); }} #include <stdio.h>void main(){ printf("Hello, World");} C has always been the language for pedal to the metal performance. It's one step away from assembly, yet it's also considered a high level language.C is easy to read - I would argue that it's one of the easiest languages to read, due to its limited set of keywords. I would also argue that it compiles to some of the fastest machine code out there. Linux is written in C. The Apache web server, which dishes out most of the world's websites, is written in C. The original Unix operating system and just about all subsequent ones were/are written in C. The compilers or interpreters of other computer languages are often written in C. I mostly agree with you bryan922, just wanted to make it clear that C is grate for low level programming but it also stops there: it's not an effective language for other kinds of applications. // In C:if( intersect_ray_tri( ray, tri, &t )) { ...}if( intersect_ray_sphere( ray, sphere, &t )) { ...}// In C++ without OOP:if( intersect( ray, tri, &t )) { ...}if( intersect( ray, sphere, &t )) { ...}// In C++ with OOP:if( ray->intersect( sphere, &t )) { ...}if( ray->intersect( tri, &t )) { ...} intersect(ray,tri) calling ray->intersect(sphere) TGeometricEngine_Intersect(shpere,Self) OOP languages like java are called performance languages (where previously languages like C were thought of as research style langauges). What would be left if you ditched OOP from C++? How can you possibly implement operator overloading or function overloading without an object? What is it that you don't like about the "->" operator? Are you sure you're not confusing overloading methods with overriding methods? Just because you ca do it with C or ASM doesn't mean you should do it! Just for reference, does anybody know what the java virtual machine or intermediary platform is programmed in? I have read everyone's replys and have another question. For robotics, is C fine or should I switch to C++? True, you need to use what C++ terms an object to do function overloading, but that's a semantic issue that boils down to use of terminology. There is nothing about the conceptual components of function overloading within the realm of computer science that require one to adopt an OOP paradigm with regard to creating function overloading in a language. Function overloading, in its essence, boils down to a compiler detecting the argument types. It is C++'s choice to entangle that with OOP, which outside of C++, conceptually refers to objects which have methods and can inherit. int func1(int x) { return x;};int func1(double x) { return 0;} No, because you can't. You would need a C++ compiler for the processor, and they mostly don't exist. Assuming that, like most of us, you are using the FREE avr gnu compiler -then it also copes with C++ - see my Members Tutorial Please help me understand. By function overloading you mean something like this:Code: [Select]int func1(int x) { return x;};int func1(double x) { return 0;}... and then have the compiler choose between the two based on the type of the RVALUE you're actually passing. Well I've got good news for you, that code up there is perfectly correct C++ code that used overloading for global functions (not part of an object). It compiles without warnings and produces the expected results. When you were talking about method overloading I honestly thought you were confusing overloading with overriding as overriding is what's interesting about OOP, not overloading. As an aside, I think C++ applications and C++ APIs would be cleaner, easier to read, easier to code in, and the code would be more terse and elegant if OOP was ditched, but leaving in operator overloading and function overloading. I also believe you're comparing Apples to Oranges when you're comparing C++ to Lisp - Lisp is an interpreted language and that's where all the interesting sintax comes from. I know there are compilers for Lisp but apparently you loose most of what makes Lisp by writing code that's compileable (ex: You need to use type declaration for everything you use!). There's an other issue: You apparently don't like Perl because of it's inconsistent syntactical rules but you like Lisp because you can define your own syntactical rules (by creating your own domain-specific programming language). I've said it and I repeat it. I've got no problem with all the other programming paradigms and - in fact - I enjoy learning about new programming languages and ideas. I believe that every single one of those programming languages has it's own place. If you insist on bashing C++ do it with the right arguments! Example: C++ is annoying because it's an type-checked language that limits one's creativity for the sake of noobs (that's one of the arguments used by Ruby people) Quote from: Webbot on January 01, 2009, 03:20:32 PMAssuming that, like most of us, you are using the FREE avr gnu compiler -then it also copes with C++ - see my Members TutorialCan you put a link to your tutorial here? I'm trying to locate it in this list but can't find it:. That isn't true. Lisp by definition is not interpreted, and Lisp incarnations which compile do not give up features of Lisp. In fact, by definition, Lisp contains a function called 'compile', which will compile any piece of Lisp code, assuming the Lisp implementation has implemented the function to its fullest potential. Surprisingly, Lisp benchmarks at often only about half the speed of C, which an interpreted language could never do. The Corman Lisp kernel is written in C/C++/x86 assembler a sophisticated native-code compiler which is capable of powerful type inferences, and generates code competitive in speed with C compilers. For those of you who wish to continue to 'diss' C++ then don't forget that early C++ compilers would turn the code into C (using struct contructs) and then compile the C program. So if you think C++ is rubbish then, by implication, you think C is rubbish. In every case I can think of, intersect returns a boolean. Every single case. The 3d point (or 2d point), or ray's parameter value t, or anything else, is, in every single case I have ever seen, an additional argument pointer. Such code is always written:if( intersect( ... )) { ....}Considering I wrote my first ray tracer in 1987 (on an Amiga) and have studied 3d graphics on and off ever since, I am not unfamiliar with said territory. Please, I have been quite clear in what I have been saying, and I have made mistakes, but not generally with regard to where my statements are being attacked. Re-writing everything from oop 'shape1->intersects(shape2)' into 'intersects(shape1,shape2)', when there are many different shapes, is surely just replacing virtual methods with operator overloading and makes the code harder to read and debug as you end up with one monolithic lump of source code. Of course, if you insist on doing this, then you can still do it in C++ anyway if you choose to do so. Quote from: geek1 on January 01, 2009, 07:58:49 AMI have read everyone's replys and have another question. For robotics, is C fine or should I switch to C++?If it means anything to you, Admin started with basic, moved on to C++ for more advanced features, then finally settled on C as my preferred language for microcontrollers.If I were to program for a PC I'd probably use C++ or Visual Basic. It really depends on the task - use the language best for the task at hand. All languages have their advantages and disadvantages. I prefer languages simple to use with a lot of source code and community support, I don't care for 'optimal' as all of them will work fine for my limited apps.As for which language is fastest or takes up the least memory or whatever, that's more of a compiler issue. Hypothetically a compiler, that's good enough, can turn C++ to be as efficient as assembly code when compiled. Hypothetically . . .Anyway, this is a friendly forum, try to be sensitive in your comments. Proving you're an awesome programmer should be limited to the amazing robots you upload on youtube
http://www.societyofrobots.com/robotforum/index.php?topic=6310.msg47626
CC-MAIN-2014-15
refinedweb
1,457
61.87
Now want to demonstrate this without the use of keyboard, mouse or monitor I was faced with the issue of being able to properly shutdown the Pi. I just wanted to start up the demo and be able to shut it down while in the field. I have found the solution by adding a button to the project that shuts down the pi when pressed. The Raspberry Pi user guide (issue 1) page 197 has details of the actual circuit and code required to detect a button press. I then had the issue of how to run both programs at the same time the solution here was to background the shutdown.py process then run the traffic lights program. To do this I edited the .bash_profile text file and added the following pi@raspberrypi:~$ cat .bash_profile hostname -I echo "hello, backgrounding shutdown process" sudo python ./RaspberryPI/gpio/shutdown.py & echo "running traffic lights" sudo python ./RaspberryPI/gpio/traffic2.py This starts up shutdown.py and then backgrounds the task, then starts the traffic lights program up. so the code I used for the shutdown program is as follows import RPi.GPIO as GPIO import time from time import sleep import os GPIO.setwarnings(False) GPIO.setmode (GPIO.BOARD ); GPIO.setup(23, GPIO.IN) #sswitch while True: input_value = GPIO.input(23) if input_value == False: print ("shuttimg dpwm pi") #time.sleep(5) os.system("sudo shutdown -h now") while input_value == False: I found this article to help me with the shutdown routine. then my traffic lights code is here for completeness import RPi.GPIO as GPIO from time import sleep GPIO.setwarnings(False) GPIO.setmode (GPIO.BOARD ); GPIO.setup(11, GPIO.OUT) #red led GPIO.setmode (GPIO.BOARD ); GPIO.setup(13, GPIO.OUT) #yellow led GPIO.setmode (GPIO.BOARD ); GPIO.setup(19, GPIO.OUT) #green led #GPIO.output(11,True) #turn off leds off=[11,13,19] on=[11,13,19] #turn off leds for x in off: GPIO.output (x, False) i = 1 while i < 5: GPIO.output (11, True) # turn on red sleep(1) GPIO.output (13,True) # turn on amber sleep(2) GPIO.output (11, False) #turn off red GPIO.output (13, False) #turn off amber GPIO.output (19, True) #turn on green sleep(2) GPIO.output (19, False) #turn off green GPIO.output (13, True) # turn on amber sleep(1) GPIO.output(13, False) #turn off amber GPIO.output(11, True) #Turn on Red sleep(5) GPIO.cleanup() This all works for me here, there is room for a few tweaks somewhere. But this is for later.
http://zleap.net/traffic-lights-update/
CC-MAIN-2019-04
refinedweb
429
77.94
Detailed Explanation of Numbers(PDF) Blow by Blow InstructionsAbout Input and OutputC++ For BeginnersC++ Programming TutorialCompiling A Program A pointer holds the address of a variable. When your application is loaded into ram part of the ram holds the variables. On the previous page we used the strcpy() function to assign a string. Another way to do this is with a pointer by using * after the type. #include <stdio.h> #include <string.h> int main() { char *name="David Bolton"; printf("My name is %s\r\n",name) ; return 0; } The line char * name="David Bolton"; defines name as a pointer to the first character in the string. The assignment means that as soon as the program loads, the pointer is set to hold the address of where the string is stored. By adding these two lines after the printf, and making the example, you can see this. printf("The address of name is %x\r\n",(int)&name) ; printf("The address that *name points to is %x\r\n",(int)name) ; (int)&name has two important parts. (int) converts (it's called a cast) the pointer type to an int. &name means the address of the variable name. When this runs it prints the following. On your computer the two addresses may be different. My name is David Bolton The address of name is 7fe78 The address that name points to is 408004 << Previous | Next >> sethostent - Linux Command - Unix Commandhstrerror - Linux Command - Unix Commandendhostent - Linux Command - Unix Commandgethostbyaddr - Linux Command - Unix Commandgethostbyname - Linux Command - Unix Command Find a BargainHotel DealsCheap EatsFree AttractionsEntertainment for Less Definition of TypeBlow by Blow InstructionsUsing OutputDebugStringAll about PointersA Car Simulation
http://cplus.about.com/od/learningc/ss/clessonthree_2.htm
crawl-001
refinedweb
275
53.1
Using the following code: char *name = malloc(sizeof(char) + 256); printf("What is your name? "); scanf("%s", name); printf("Hello %s. Nice to meet you.\n", name); Lucas Aardvark scanf() Lucas scanf() People (and especially beginners) should never use scanf("%s") or gets() or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then). Remember than scanf stands for "scan formatted" and there's precious little less formatted than user-entered data. It's ideal if you have total control of the input data format but generally unsuitable for user input. Use fgets() (which has buffer overflow protection) to get your input into a string and sscanf() to evaluate it. Since you just want what the user entered without parsing, you don't really need sscanf() in this case anyway: #include <stdio.h> #include <stdlib.h> #include <string.h> /* Maximum name size + 1. */ #define MAX_NAME_SZ 256 int main(int argC, char *argV[]) { /* Allocate memory and check if okay. */ char *name = malloc (MAX_NAME_SZ); if (name == NULL) { printf ("No memory\n"); return 1; } /* Ask user for name. */ printf("What is your name? "); /* Get the name, with size limit. */ fgets (name, MAX_NAME_SZ, stdin); /* Remove trailing newline, if there. */ if ((strlen(name)>0) && (name[strlen (name) - 1] == '\n')) name[strlen (name) - 1] = '\0'; /* Say hello. */ printf("Hello %s. Nice to meet you.\n", name); /* Free memory and exit. */ free (name); return 0; }
https://codedump.io/share/3cwzXQ1DTi1o/1/how-do-you-allow-spaces-to-be-entered-using-scanf
CC-MAIN-2016-44
refinedweb
248
68.47
#include <iostream> #include <ctime> using namespace std; int main() { tm* timeinfo; time_t seconds = time(NULL); timeinfo = localtime(&seconds); cout << "Seconds since the epoch: " << seconds << endl; cout << "Local time: " << asctime(timeinfo) << endl; return 0; } Here I'm using three functions and one stuct from the C++ standard ctime library to get the time and display it. The time function gets the number of seconds since January 1, 1970 (the start of the Unix epoch) from the operating system. The localtime function converts the time in seconds to a tm structure representing the calendar date and time. Finally, the asctime function converts the tm stucture to a human-readable string format. Compile the program above using g++, then run it to see the following output. Naturally, you'll see different results depending on when you run the executable.Naturally, you'll see different results depending on when you run the executable. $ ./a.out Seconds since the epoch: 1234712674 Local time: Sun Feb 15 10:44:34 2009
http://www.billthelizard.com/2009/02/c-snippets-time.html
CC-MAIN-2017-47
refinedweb
165
51.89
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi folks, With 2.6.33.1 and 2.6.34-rc2 sound splutters for my PC. Moving back to 2.6.29.8 make the problem go away. 00:1b.0 Audio device: Intel Corporation 82801FB/FBM/FR/FW/FRW (ICH6 Family) High Definition Audio Controller (rev 04) Subsystem: AOPEN Inc. Device 05 d4340000 (64-bit, non-prefetchable) [size=16K] Capabilities: <access denied> Kernel driver in use: HDA Intel Can anybody reproduce this? Regards Harri -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - iEYEARECAAYFAkuuTaEACgkQUTlbRTxpHje8tQCghyMjBdzTV4y4Xb9Et2rvW/ll FP8AnjVxIVqE/b8hlEg63Jdpf0jTj1iX =gYRK -----END PGP SIGNATURE----- After the last system upgrade from kernel 2.6.31.6-1 to 2.6.32.3-1 my microphone stoped working. Since I downgraded my kernel back to 2.6.31.6-1 it just worked. I use alsa and the gstreamer backend for phonon. The attached files are generated by alsa-info.sh. One for the working environment with the old kernel and one for the non working environment. Is someone able to help me? #include <Jaroslav Kysela.h> // created 26/03/2010 10:52 > My hints were correct. hda-analyzer is your friend (node 0x20 - index 3 > (Values 6-7 in hda-analyzer controls the analog beep input). > Fortunately, I had access to T61, so the patch fixing the analog beep > input for T61/X61 is here: > >;a=commitdiff;h=0bf0e5a6f304ac1bc93a80cdd68b4d91f3519eb5 # uname -a Linux magritte 2.6.33-gentoo-kz #2 SMP Sat Mar 27 13:46:31 CET 2010 i686 Intel(R) Core(TM)2 Duo CPU T7300 @ 2.00GHz GenuineIntel GNU/Linux # echo 4 > /proc/acpi/ibm/beep it woooooooooooooorks!!! :) many many many thanks.. is since that summer that in can't leave from kernel 2.6.29 because I don't want to loose the firmware beeps... k. Hello Jaroslav! You wrote: > It was event4 on my system. > ============= Actually, this works. However, it is a bit annoying that, when doing volume donw, a '~' (tilde) character is displayd on the screen, and the terminal at the same time beeps. Please note that this behaviour also exist when the scrit you provided is not running. Lars
https://sourceforge.net/p/alsa/mailman/alsa-user/?viewmonth=201003&viewday=27
CC-MAIN-2017-39
refinedweb
365
69.79
0,2 In other words, least m>0 such that 2n+1 divides 2^m-1. Number of riffle shuffles of 2n+2 cards required to return a deck to initial state. A riffle shuffle replaces a list s(1), s(2), ..., s(m) by s(1), s((i/2)+1), s(2), s((i/2)+2), ... a(1) = 2 because a riffle shuffle of [1, 2, 3, 4] requires 2 iterations [1, 2, 3, 4] -> [1, 3, 2, 4] -> [1, 2, 3, 4] to restore the original order. Concerning the complexity of computing this sequence, see for example Bach And Shallit, p. 115, exercise 8. It is not difficult to prove that if 2n+1 is a prime then 2n is a multiple of a(n). But the converse is not true. Indeed, one can prove that a(2^(2t-1))=4t. Thus if n=2^(2t-1), where, for any m>0, t=2^(m-1) then 2n is a multiple of a(n) while 2n+1 is a Fermat number which, as is well known, is not always a prime. It is an interesting problem to describe all composite numbers for which 2n is divisible by a(n). - Vladimir Shevelev, May 09 2008 For a conjectural algorithm of calculation of a(n) see A179680. - Vladimir Shevelev, Jul 21 2010 From V. Raman, Sep 18 2012, Dec 10 2012: (Start) If 2n+1 is prime, then the polynomial (x^(2n+1)+1)/(x+1) factors into 2n/a(n) polynomials of the same degree a(n) over GF(2). For example, the polynomial (x^31+1)/(x+1) factors into six polynomials of degree 5 over GF(2). Thus if 2n+1 is prime then 2n will always be a multiple of a(n). If 2n+1 is prime and the polynomial (x^(2n+1)+1)/(x+1) is reducible over GF(2), then 2 is not a primitive root (mod 2n+1) (cf. A216838). For these values of n, a(n) != 2n (but a divisor of 2n). On the other hand, if (x^(2n+1)+1)/(x+1) is irreducible over GF(2), then 2n+1 is prime, and 2 is a primitive root (mod 2n+1) (cf. A001122). Then (x^(2n+1)+1)/(x+1) consists of a single irreducible factor of degree 2n. For these values of n, a(n) = 2n. Also, for all n > 0, whether 2n+1 is prime or composite, a(n) is the degree of the largest irreducible polynomial factor for the polynomial (x^(2n+1)+1)/(x+1) over GF(2). (End) a(n) is a factor of phi(2n+1) (A000010(2n+1)). - Douglas Boffey, Oct 21 2013 Conjecture: if p is an odd prime then a((p^3-1)/2) = p * a((p^2-1)/2). Because otherwise a((p^3-1)/2) < p * a((p^2-1)/2) iff a((p^3-1)/2) = a((p-1)/2) for a prime p. Equivalently p^3 divides 2^(p-1)-1, but no such prime p is known. - Thomas Ordowski, Feb 10 2014 E. Bach and Jeffrey Shallit, Algorithmic Number Theory, I. T. Folger, "Shuffling Into Hyperspace," Discover, 1991 (vol 12, no 1), pages 66-67. M. Gardner, "Card Shuffles," Mathematical Carnival chapter 10, pages 123-138. New York: Vintage Books, 1977. V. I. Levenshtein, Conflict-avoiding codes and cyclic triple systems [in Russian], Problemy Peredachi Informatsii, 43 (No. 3, 2007), 39-53. L. Lunelli and M. Lunelli, Tavola di congruenza a^n == 1 mod K per a=2,5,10, Atti Sem. Mat. Fis. Univ. Modena 10 (1960/61), 219-236 (1961). J. H. Silverman, A Friendly Introduction to Number Theory, 3rd ed., Pearson Education, Inc, 2006, p. 146, Exer. 21.3..10000 M. Baake, U. Grimm, J. Nilsson, Scaling of the Thue-Morse diffraction measure, arXiv preprint arXiv:1311.4371 [math-ph], 2013. D. Bayer, P. Diaconis, Trailing the dovetail shuffle to its lair, Ann. Appl. Prob. 2 (2) (1992) 294-313 Brillhart, John; Lomont, J. S.; Morton, Patrick. Cyclotomic properties of the Rudin-Shapiro polynomials, J. Reine Angew. Math.288 (1976), 37--65. See Table 2. MR0498479 (58 #16589). Steve Butler, Persi Diaconis and Ron Graham, The mathematics of the flip and horseshoe shuffles, arXiv:1412.8533 [math.CO], 2014. Steve Butler, Persi Diaconis and Ron Graham, The mathematics of the flip and horseshoe shuffles, The American Mathematical Monthly 123.6 (2016): 542-556. A. J. C. Cunningham, On Binal Fractions, Math. Gaz., 4 (71) (1908), circa p. 266. P. Diaconis, R. L. Graham, W. M. Kantor, The mathematics of perfect shuffles, Adv. Appl. Math. 4 (2) (1983) 175-196 M. J. Gardner and C. A. McMahan, Riffling casino checks, Math. Mag., 50 (1) (1977), 38-41. S. W. Golomb, Permutations by cutting and shuffling, SIAM Rev., 3 (1961), 293-297. V. I. Levenshtein, Conflict-avoiding codes and cyclic triple systems, Problems of Information Transmission, September 2007, Volume 43, Issue 3, pp 199-212 (translated from Russian) Vladimir Shevelev, Gilberto Garcia-Pulgarin, Juan Miguel Velasquez-Soto and John H. Castillo, Overpseudoprimes, and Mersenne and Fermat numbers as primover numbers, arXiv preprint arXiv:1206:0606 [math.NT], 2012. V. Shevelev, G. Garcia-Pulgarin, J. M. Velasquez and J. H. Castillo, Overpseudoprimes, and Mersenne and Fermat Numbers as Primover Numbers, J. Integer Seq. 15 (2012) Article 12.7.7 Eric Weisstein's World of Mathematics, Riffle Shuffle Eric Weisstein's World of Mathematics, In-Shuffle Eric Weisstein's World of Mathematics, Out-Shuffle Eric Weisstein's World of Mathematics, Multiplicative Order Wikipedia, Riffle Shuffle a((3^n-1)/2) = A025192(n). - Vladimir Shevelev, May 09 2008 Bisection of A007733: a(n) = A007733(2n+1). - Max Alekseyev, Jun 11 2009 a((b(n)-1)/2) = n for odd n and even n such that b(n/2) != b(n), where b(n) = A005420(n). - Thomas Ordowski, Jan 11 2014 Note that a(2^n-1) = n+1 and a(2^n) = 2(n+1). - Thomas Ordowski, Jan 16 2014 with(numtheory): f := n->order(2, 2*n+1); Table[MultiplicativeOrder[2, 2*n + 1], {n, 0, 100}] (* Robert G. Wilson v, Apr 05 2011 *) (PARI) a(n)=if(n<0, 0, znorder(Mod(2, 2*n+1))) /* Michael Somos, Mar 31 2005 */ (MAGMA) [ 1 ] cat [ Modorder(2, 2*n+1): n in [1..72] ]; // Klaus Brockhaus, Dec 03 2008 (PARI) vector(100, p, factormod((x^(2*p+1)+1)/(x+1), 2, 1)[matsize(factormod((x^(2*p+1)+1)/(x+1), 2, 1))[1], 1]) \\ V. Raman, Sep 18 2012 (PARI) for(i=0, 200, i++; if(i%5==0, print1(0", "), print1(znorder(Mod(2, i))", "))) \\ V. Raman, Nov 22 2012 (PARI) for(i=0, 200, i++; m=0; for(x=1, i, if(((2^x-1))%i==0, m=x; break)); print1(m", ")) \\ V. Raman, Nov 22 2012 (Haskell) import Data.List (findIndex) import Data.Maybe (fromJust) a002326 n = (+ 1) $ fromJust $ findIndex ((== 0) . (`mod` (2 * n + 1))) $ tail a000225_list -- Reinhard Zumkeller, Apr 22 2013 (Python) def A002326(n): a=1 m=0 while True: a*=2 a%=(2*n+1) m+=1 if a<=1: break return m # Alexandre Henrique Afonso Campos, Jul 19 2015; corrected by David Radcliffe, Jun 26 2016 Cf. A003571, A003573, A217469, A070667-A070683, A053447, A053451. Cf. A024222, A006694 (number of cyclotomic cosets). Cf. A014664 (order of 2 mod n-th prime). Cf. A001122 (primes for which 2 is a primitive root). Cf. A216838 (primes for which 2 is not a primitive root). Cf. A000225. Bisections give A274298, A274299. Sequence in context: A131388 A131393 A216476 * A064273 A257986 A232564 Adjacent sequences: A002323 A002324 A002325 * A002327 A002328 A002329 nonn,easy,nice N. J. A. Sloane More terms from David W. Wilson, Jan 13 2000 More terms from Benoit Cloitre, Apr 11 2003 approved
https://oeis.org/A002326
CC-MAIN-2017-09
refinedweb
1,300
76.42
Advanced that takes a string, and returns a valid value for the model we're loading into. The declaration above is a bit messy, though. Let's define our own 'custom_date' conversion function to clean things up. Here it is: def custom_date(fmt): """Returns a converter function that parses the supplied date format.""" def converter(s): return datetime.datetime.strptime(s, fmt).date() return converter What we're doing here is making use of some of Python's flexibility: We're defining a function that returns another function. The inner function (converter) has access to variables from the outer function. This is known as a 'closure'. You can think of our new function as a 'converter generator' - when it's called with a date/time format, it returns a converter that accepts dates in that format and parses them. With the help of our new function, our AlbumLoader now looks like this: class AlbumLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'Album', [('title', str), ('artist', str), ('publication_date', custom_date("%m/%d/%Y")), ('length_in_minutes', int) ]) A noticeable improvement - and we can reuse this function anywhere we're parsing dates, even if we use different formats in different places. Converters can get more sophisticated than that, though. Suppose we want to load a set of images into the datastore so we can serve them to users. We can define a conversion function that takes a filename, and returns the contents of the file, like this: def file_loader(filename): fh = open(filename, "rb") data = fh.read() fh.close() return data class DatastoreImage(db.Model): filename = db.StringProperty(required=True) data = db.BlobProperty(required=True) class ImageLoader(bulkloader.Loader): def __init__(self) bulkloader.Loader.__init__(self, 'DatastoreImage', [('filename', str), ('data', file_loader) ]) When we run the bulkloader with this configuration, we supply a CSV file withtwo fields: The filename we want the file to have on App Engine, and the path (relative to the directory we're running the bulkloader from) to the actual file to upload. Our file_uploader conversion function takes the second of those filenames, and reads the file into memory, so it's uploaded as part of the entity we just created - without us having to figure out a way to embed images in a CSV file! This approach isn't limited to images, of course - it can also be useful if you want to upload HTML files into the datastore, for example. Using this method, we could even define converters that do exotic things like fetching a file over HTTP, or generating an image on the spot using the Python Imaging Library - not that I'd recommend either approach! Keep an eye out for the next post, coming soon: Advanced bulk loading, part 2!Previous Post Next Post
http://blog.notdot.net/2009/9/Advanced-Bulk-Loading-part-1-Converters
CC-MAIN-2017-09
refinedweb
458
55.44
Introduction namespaces allows users to say they want VMs of a certain configurations and minimega will do the heavy lifting underneath to schedule those VMs across a cluster of nodes. This article describes some of that heavy lifting. It assumes that you have already read the article describing namespaces for users. Overview One of the major design goals of namespaces was to make as few changes to the existing API as possible. Ideally, scripts that ran in minimega 2.2, the last release before namespaces, should run on the latest release. So far, we have achieved this goal. Storing the namespace The active namespace is stored in the namespace global string. This should not be used directly -- all the CLI handlers are passed the active namespace when invoked and should not need to touch any of the namespace globals. In a a few places, goroutines may need to access a particular namespace -- this should be done with the "APIs" such as GetNamespace() and not by touching the globals directly. namespace resources Each namespace stores all the state associated with it such as the VMs, tap names, captures, and VNC recordings. These resources are automatically cleaned up when the namespace is destroyed. Commands that list resources (e.g. vm info, vlans, and taps) only operate on the data stored in the active namespace which simplifies their code (in 2.3, each resource had to be namespace-aware and filter appropriately). As a result, there is no way to list resources across namespaces. Nodes may belong to one or more namespaces and are listed as part of the ns hosts command. For brevity, we will refer to the nodes that belong to the active namespace as active nodes. API handler duality Most API handlers have two functions -- they 1) fan out commands to nodes in the active namespace and 2) perform whatever local behavior the command dictates. The fan out behavior is handled automatically by wrapBroadcastCLI and wrapVMTargetCLI. wrapVMTargetCLI behaves the same as wrapBroadcastCLI but includes an additional step to filter `vm not found` errors from the nodes that aren't running the target VM. The fan out behavior simply calls mesh send with the original command embedded in a namespace <namespace> (command) command and the hosts in the current namespace as the target. It then collects and displays the responses. One complication with the above approach is that how does the remote node know that it should perform the local behavior rather than trying to fan out again? Without some mechanism to resolve this, we would fan out again and cause a deadlock. To prevent this, we tag the outgoing minicli.Command using the Source field. Specifically, we set the Source field to the active namespace. The wrapBroadcastCLI and wrapVMTargetCLI handlers check the Source field and, if it is non-zero, perform the local behavior. Otherwise, they will fan out.
https://minimega.org/articles/developer/namespaces.article
CC-MAIN-2020-24
refinedweb
479
64
I don’t want to sound ungrateful for all the fine work you guys did on DeepStream 4. But some python examples would be nice if possible. CPP is just no fun and in the end isn’t that what its all about? DeepStream 4 Python examples because CPP is no fun I don’t want to sound ungrateful for all the fine work you guys did on DeepStream 4. You can install the python bindings for gstreamer and your code will look nearly identical to the C version. Put it this way: gstreamer’s python bindings are not very pythonic and you might as well use C or C++. It’s callback hell in any language, sorry. You might as well make it as fast as it can go. I am considering porting some of the C example code to python for quicker prototyping. As I am a complete gstreamer beginner: Do you guys know if the python API is complete, e.g. a full port would likely be possible? It’s feature complete from what I understand, but the best examples still look like C. If you want a really good example of extremely well written GStreamer python, check this out: It’s for Coral, but you could easily swap out Nvidia’s elements. It’s Apache license. The problem is things like this: def on_bus_message(bus, message, pipeline, loop): if message.type == Gst.MessageType.EOS: seek_element = get_seek_element(pipeline) if loop and seek_element: flags = Gst.SeekFlags.FLUSH | Gst.SeekFlags.KEY_UNIT if not seek_element.seek_simple(Gst.Format.TIME, flags, 0): Gtk.main_quit() else: Gtk.main_quit() elif message.type == Gst.MessageType.WARNING: err, debug = message.parse_warning() sys.stderr.write('Warning: %s: %s\n' % (err, debug)) elif message.type == Gst.MessageType.ERROR: err, debug = message.parse_error() sys.stderr.write('Error: %s: %s\n' % (err, debug)) Gtk.main_quit() That isn’t very pythonic. It looks like C, and it takes just as long to write, which is the area where Python is supposed to excel. Here is a C example from Gstreamer’s Bus documentation:; } Looks pretty similar no? It handles messages from the bus and quits the main loop. All the code in every language is on_this(), on_that(), on_something_or_other(), and so on. It’s not a big deal if they aren’t called frequently, but in GStreamer they often need to be (for example, on every buffer) are and that’s slow in Python. Python’s advantage is that memory management is handled for you, but if you follow the GStreamer tutorials you’re shown how to do that yourself. It doesn’t matter if you don’t know C. Retype enough tutorial examples (they’re really good), read the docs or ask here when you get stuck, and you will learn.
https://forums.developer.nvidia.com/t/deepstream-4-python-examples-because-cpp-is-no-fun/79004
CC-MAIN-2020-45
refinedweb
461
75.81
Tarjan’s Algorithm is used to find strongly connected components of a directed graph. It requires only one DFS traversal to implement this algorithm. Using DFS traversal we can find DFS tree of the forest. From the DFS tree, strongly connected components are found. When the root of such sub-tree is found we can display the whole subtree. That subtree is one strongly connected component. Input: Adjacency matrix of the graph. 0 0 1 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 Output: The strongly connected components: 4 3 1 2 0 findComponent(u, disc, low, stack, stackItemFlag) Input: The start node, discovery time, low, the disc will hold the discovery time of the vertex, and low will hold information about subtrees. The stack to hold vertices and another flag array to track which node is in the stack. Output: Display the SCC. Begin time := 0 //the value of time will not be initialized for next function calls set disc[u] := time+1 and low[u] := time + 1 time := time + 1 push u into stack stackItemFalg[u] := true for all vertex v which is adjacent with u, do if v is not discovered, then fincComponent(v, disc, low, stack, stackItemFalg) low[u] = minimum of low[u] and low[v] else if stackItemFalg[v] is true, then low[u] := minimum of low[u] and disc[v] done poppedItem := 0 if low[u] = disc[u], then while u is not in the stack top, do poppedItem := top of stack display poppedItem stackItemFlag[poppedItem] := false pop item from stack done poppedItem := top of stack display poppedItem stackItemFlag[poppedItem] := false pop item from stack End strongConComponent(graph) Input &,minus; The given Graph. Output − All the strongly connected components. Begin initially set all items in the disc array to undiscovered for all elements in low to φ and mark no item is stored into the stack for all node i in the graph, do if disc[i] is undiscovered, then findComponent(i, disc, low, stack, stackItemFlag) End #include<iostream> #include<stack> #define NODE 5 using namespace std; int graph[NODE][NODE] = { {0, 0, 1, 1, 0}, {1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 0, 0, 1}, {0, 0, 0, 0, 0} }; int min(int a, int b) { return (a<b)?a:b; } void findComponent(int u, int disc[], int low[], stack<int>&stk, bool stkItem[]) { static int time = 0; disc[u] = low[u] = ++time; //inilially discovery time and low value is 1 stk.push(u); stkItem[u] = true; //flag as u in the stack for(int v = 0; v<NODE; v++) { if(graph[u][v]) { if(disc[v] == -1) { //when v is not visited findComponent(v, disc, low, stk, stkItem); low[u] = min(low[u], low[v]); } else if(stkItem[v]) //when v is in the stack, update low for u low[u] = min(low[u], disc[v]); } } int poppedItem = 0; if(low[u] == disc[u]) { while(stk.top() != u) { poppedItem = stk.top(); cout << poppedItem << " "; stkItem[poppedItem] = false; //mark as item is popped stk.pop(); } poppedItem = stk.top(); cout << poppedItem <<endl; stkItem[poppedItem] = false; stk.pop(); } } void strongConComponent() { int disc[NODE], low[NODE]; bool stkItem[NODE]; stack<int> stk; for(int i = 0; i<NODE; i++) { //initialize all elements disc[i] = low[i] = -1; stkItem[i] = false; } for(int i = 0; i<NODE; i++) //initialize all elements if(disc[i] == -1) findComponent(i, disc, low, stk, stkItem); } int main() { strongConComponent(); } 4 3 1 2 0
https://www.tutorialspoint.com/Tarjan-s-Algorithm-for-Strongly-Connected-Components
CC-MAIN-2021-17
refinedweb
590
62.51
Display real-time estimate of commute time between two locations based on traffic and historic data on a Character LCD using Raspberry Pi, Python 3 and Google Maps Distance Matrix API. If you have a LCD and a Raspberry Pi lying around or want to purchase one or if you are often late for work like me and want to have a traffic monitor then this project might be for you. Wiring Software Requirements We are going to use Python programming language to make an Google Maps API call and then display the results to LCD Installing the dependencies Adafruit Python CharLCD library Get the LCD library from following Github link. CD to the downloaded folder and run the following command. sudo python3 setup.py install Requests sudo pip3 install requests Google Maps Distance Matric API sudo pip3 install -U googlemaps Getting an API key to make API calls Login to your google account by visiting the following link and get the API key for your project. If you don't have an existing project, then you might have a create a new one. Python Code Python 3 code for getting the commute time and displaying it on LCD Importing the dependencies import time import Adafruit_CharLCD as LCD import requests Variables for making API call Update the api_key variable with the key you got before. api_key = 'YOUR_API_KEY' base_url = '?' Origin and destination addresses origin = 'Papakura,Auckland,New+Zealand' destination = 'Penrose,Auckland,New+Zealand' Variables for driving the LCD Corresponding Raspberry Pi GPIO pins for register select, instruction and data registers on LCD. We will use these variables later to initialize the LCD. lcd_rs = 4 lcd_en = 17 lcd_d4 = 25 lcd_d5 = 24 lcd_d6 = 23 lcd_d7 = 18 Size of the LCD, If you have a character LCD of 16x2, then modify the lcd_columns variable to 16 and lcd_rows to 2. Since, I used 20x4 LCD, I will use the following values. lcd_columns = 20 lcd_rows = 4 Initialize the LCD Create a lcd object by calling the constructor method defined in the Adafruit LCD library and pass in the required parameters. If your LCD supports backlight, then you could pass in an additional parameter of backlight = 1 or backlight = 0 to turn it on or off. lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows) Making the API call We are going to structure the URL and then use python library requests to make a get request to API endpoint. To get a valid response you will also need to include additional parameters namely origins, destinations, departure time, traffic_model and API key in your request. Response message is then stored in variable and converted to JSON. In this example, I have passed in the result to display message. This method makes two requests - one to get best guessed commute time and other to get pessimistic time. Pessimistic time will be often more than the best guessed time. def get_data(): try: # Make request to get best guess duration between specified two points r1 = requests.get(base_url+'origins={}&destinations={}&departure_time={}&traffic_model={}&key={}'.format(origin, destination, time_in_seconds_UTC(), 'best_guess', api_key)) r1= r1.json()['rows'][0]['elements'][0] # Convert the response to JSON best_guess_duration = r1['duration_in_traffic']['text'] # Make request to get worst case duration between specified two points r2 = requests.get(base_url+'origins={}&destinations={}&departure_time={}&traffic_model={}&key={}'.format(origin, destination, time_in_seconds_UTC(), 'pessimistic', api_key)) r2 = r2.json()['rows'][0]['elements'][0] # Convert the response to JSON pessimistic_duration = r2['duration_in_traffic']['text'] display('Estimated Drive Time', 'BG: ' + best_guess_duration, 'PSMT: ' + pessimistic_duration, human_readable_time()) # Pass the results to display function except requests.exceptions.RequestException as e: # Print time when exception happened and exception meyyssage print(time.strftime("%d-%m-%Y %H:%M:%S", time.localtime())) print(e) display('Error, check console', 'Trying again...') # Update LCD with error message Also, I have wrapped the code in try and except block to catch if the request fails for whatever reason. If the exception happens, print function will print the time when it happened and reason in console and LCD will show Error, check console', 'Trying again...'. LCD will update with commute data again if the next request is successful. The display function Display function takes advantage of the message function provided by Adafruit LCD library. You can pass in upto four strings while calling it and it will display each string on a new line. lcd.clear() will clear any existing text on LCD and lcd.home() will bring the cursor to row 1 and column 1. For best results, you might want to limit the string length to maximum characters your LCD can display on each line. If you want to display multi-line message, then its best to use lcd.message() def display(line1 = '', line2 = '', line3 = '', line4 = ''): lcd.clear() # Clear the display lcd.home() # Bring cursor to row 1 and column 1 lcd.message(line1 + '\n' + line2 + '\n' + line3 + '\n' + line4) # Print message Get real time traffic data So far, we have the code to get distance and duration but but we are not actually making a request. To get a response we have to call get_data() function and keep calling it every minute to get the updated duration based on traffic. I have wrapped this code in main() function def main(): display('Loading...') get_data() # Gets and displays data on LCD time.sleep(60) # Wait for 1 minute The following code will keep the program running once started and display Stopped on LCD when you stop it. while True: try: main() finally: display('Stopped') Other helper functions Helper functions are called in get_data() method. # This piece of code returns the time in seconds in UTC which is passed to maps API as a value for departure_time def time_in_seconds_UTC(): return int(round(time.time())) #Following code returns a human readable date and time, this is printed on fourth line of LCD def human_readable_time(): return time.strftime("%d %b %Y %I:%M %P", time.localtime()) Starting the app Finally, we are at a point to start the program and get the real time traffic duration and distance on the LCD. You can get the code from following Github link. Copy the code to file and name in app.py Open up your command prompt or terminal and cd into the folder and run the following command. python3 app.py End Result Blog Post
https://www.hackster.io/dilpreet/display-commute-time-on-lcd-using-raspberry-pi-183ff0
CC-MAIN-2018-39
refinedweb
1,046
62.07
Context When you’re working with a UI or plain text data integration, conversions are often an issue. In this case I would like to talk about DateTime objects. Recently, there was an issue in one of the other teams. They had a WinForms UI where they wanted to display a DateTime property in two different textboxes, one for the date and another for the time. They had their reasons for not using a DateTimePicker control or any other method. That wasn’t really the problem. One of the business users discovered an error when trying to save changes. The development team figured out what went wrong, apparently it was a “Culture” thing. The business user’s computer was using Windows XP and its regional settings were set to English – United States. When the application tried to parse the textboxes and store the value back in the property, the month and day were swapped. In Europe we usually use “dd/MM/yyyy”, in the US they use “MM/dd/yyyy”. Normally this should not pose a problem, the date was successfully loaded, so why wouldn’t it convert back as expected. Well, one of the main reasons is VB.NET. VB.NET has a feature called CDate, which can convert a string to a Date object. In C#, you only have a DateTime object. What happened? The CDate takes the regional settings and when you enter 16/10/2010, it will crash, because there is no 16th month. Enter Mike I overheard an intense discussion going on and decided to see if I could be of use. Call it interfering if you want; I see it as helping colleagues . They explained the situation of the custom controls (the two textboxes) and the error. One of them was telling they needed to use DateTimePicker controls, another wanted to change regional settings in the database and application (I missed the point of that one), and so. After a bit of evaluating, I noticed they were only complicating the solution/problem. I told them they only needed to parse the string into a DateTime object with specific format, and then assign the DateTime to the Date object. So instead of doing a lot of changes, add a single line of code… I created a helper/utility class on the fly, so they could end their discussion and get back to work (and stop bothering the rest of us ). DateTimeParser using System; using System.Globalization; namespace MyNamespace { public static class DateTimeParser { public static DateTime ParseDateTime(string value, string inputFormat) { return ParseDateTime(value, inputFormat, CultureInfo.InvariantCulture); } public static DateTime ParseDateTime(string value, string inputFormat, CultureInfo provider) { if (string.IsNullOrEmpty(value)) throw new ArgumentNullException("value"); try { return DateTime.ParseExact(value, inputFormat, provider); } catch (Exception ex) { throw new Exception("Could not parse date: " + value, ex); } } } public class DateTimeParserDemo { public DateTime Test() { string myDate = "31/12/2010 23:59:59"; return DateTimeParser.ParseDateTime(myDate, "dd/MM/yyyy HH:mm:ss"); } } } VB.NET code If you prefer the code in VB.NET head to the website of DeveloperFusion.com, they have an excellent C# to VB.NET converter.
http://www.mikebevers.be/blog/2010/10/converting-text-to-datetime-objects-datetimeparser/
CC-MAIN-2018-05
refinedweb
519
56.25
chdir(), fchdir() and getcwd() in C When working to build any software we could be working with different files stored at different locations and thus there might be cases when we would need to change our current working directory. C language provides us two functions that help us to change our current working directory these functions are chdir() and fchdir().These functions are included in the unistd.h header file so in order to use these functions we need to include this header file into our program. To verify the changes due to the above two functions, we use getcwd() function of C. <unistd.h> header file: The <unistd.h> header defines miscellaneous symbolic constants and types, and declares miscellaneous functions.It contains the chdir() and fchdir() functions. For further reference see here chdir(): The chdir function is used to change the current working directory of the program or process by passing the path to the function as shown in the syntax. Function declaration: int chdir( const char *pathname ); Return value : The function return a integer value ,it returns 0 if the change of directory was successful otherwise it returns -1 and the current working directory remains unchanged and errno is set to to indicate the error type. Errors: -. Example code: #include<stdio.h> #include<unistd.h> int main() { //pass your path in the function int ch=chdir("xxx"); /*if the change of directory was successful it will print successful otherwise it will print not successful*/ if(ch<0) printf("chdir change of directory not successful\n"); else printf("chdir change of directory successful"); return 0; } fchdir() The fchdir function is similar to the chdir function but in this we pass a file descriptor as the function parameter.A file descriptor is a number that uniquely identifies an open file in a computer's operating system. It describes a data resource, and how that resource may be accessed. Function declaration : int fchdir(int fd); Function return : The function return a integer value ,it returns 0 if the change of directory was successful otherwise it returns -1 and the current working directory remains unchanged and errno is set to to indicate the error type. Errors: - EACCES :Search permission is denied for the directory referenced by fildes. - EBADF :The fildes argument is not an open file descriptor. - ENOTDIR :The open file descriptor fildes does not refer to a directory. - EINTR :A signal was caught during the execution of fchdir(). - EIO :An I/O error occurred while reading from or writing to the file system. Example code: #include<stdio.h> #include<unistd.h> int main() { //pass your file descriptor in the function int ch=fchdir("file descriptor"); /*if the change of directory was successful it will print successful otherwise it will print not successful*/ if(ch<0) printf("fchdir change of directory not successful\n"); else printf("fchdir change of directory successful"); return 0; } To verify if the above functions are actually changing the directories, we need to check the current working directory just before and after the function call. How to check the current working directory? After using the chdir() function we might need to verify whether out current working directory has been changed or not for this we use the getcwd() function. getcwd():.The return value represent our current working directory. Function declaration: char *getcwd(char *buf, size_t size); Function return :The getcwd() function returns a pointer which points to a character array where the path of current working directory is stored.In case the path is not found then it returns a null pointer and the contents of the array are undefined and the errno is set to indicate the type of error. Type of errors in getcwd(): 1.EINVAL:The size argument is 0. 2.ERANGE:The size argument is greater than 0, but is smaller than the length of the pathname +1. 3.EACCES:Read or search permission was denied for a component of the pathname. 4.ENOMEM:Insufficient storage space is available. Example code: #include <unistd.h> #include <stdio.h> int main() { char cwd[256]; if (getcwd(cwd, sizeof(cwd)) == NULL) perror("getcwd() error"); else printf("current working directory is: %s\n", cwd); return 0; } Using getcwd() to check changes made by chdir(): We can use getchd() to check whether after using the chdir() function the desired changes have been made or not.We first need to make the desired changes using the chdir() function and then use the getcwd() function to see whether the current working directory is the same as desired or not. C code to check the changes made by chdir(): #include<stdio.h> #include<unistd.h> int main() { char cwd[256]; if (chdir("Your desired path") != 0) perror("chdir() error()"); else { if (getcwd(cwd, sizeof(cwd)) == NULL) perror("getcwd() error"); else printf("current working directory is: %s\n", cwd); } } With this, you have the complete idea of using chdir() and fchdir() and validate the result or changes using getcwd(). Enjoy.
https://iq.opengenus.org/chdir-fchdir-getcwd-in-c/
CC-MAIN-2020-24
refinedweb
827
60.04