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
Nested-purpose types. Nested types are best suited for modeling implementation details of their enclosing types. The end user should rarely have to declare variables of a nested type and almost never should have to. √ DO use nested types when the relationship between the nested type and its outer type is such that member-accessibility semantics are desirable. X DO NOT use public nested types as a logical grouping construct; use namespaces for this. X AVOID publicly exposed nested types. The only exception to this is if variables of the nested type need to be declared only in rare scenarios such as subclassing or other advanced customization scenarios. X DO NOT use nested types if the type is likely to be referenced outside of the containing type. For example, an enum passed to a method defined on a class should not be defined as a nested type in the class. X DO NOT use nested types if they need to be instantiated by client code. If a type has a public constructor, it should probably not be nested. If a type can be instantiated, that seems to indicate. X DO NOT define a nested type as a member of an interface. Many languages do not support such a construct..
https://msdn.microsoft.com/en-us/library/ms229027(v=vs.110).aspx
CC-MAIN-2015-22
refinedweb
209
63.8
This article covers how to implement custom fields for Piranha. If you want to read more about the standard field included, please refer to Fields in the section Content.. In order to create a custom field your class has to implement the IField interface from the Piranha.Extend namespace. The interface contains the following methods that needs to be implemented: public interface IField { /// <summary> /// Gets the list item title if this field is used in /// a collection regions. /// </summary> string GetTitle(); } string GetTitle(); Gets the list item title if this field is used in a collection region. Please note that it's only supported to reference Field Properties as title. // Synchronous Init method void Init(...); // Asyncronous Init method Task Init(...); Initializes the field for client use. This is called when the field is loaded and is used for loading additional resources. As an example, the ImageField loads the referenced image from the database when Init() is called. The method supports Dependency Injection which means that any service registered in the DI Container can be added as an parameter. This is useful when loading custom data from your application. // Synchronous Init method void ManagerInit(...); // Asyncronous Init method Task ManagerInit(...); Initializes the field when it's loaded from within the manager. This can for example be useful if you want to load meta-data for the field that you only need when editing it. Just like the regular Init method it supports Dependency Injection so that you can use any service registered in the DI Container. Let's take a look at how a simple string field could be implemented. using Piranha; using Piranha.Extend; [FieldType(Name = "Simple String", Component = "simple-field")] public class SimpleStringField : IField { public string Value { get; set; } public string GetTitle() { return Value; } public void Init() { // Nothing special for this field } } When registering a field with the FieldTypeAttribute you can set the following properties. public string Name { get; set; } The display name of the field type in the manager interface. public string Component { get; set; } The name of the global Vue component that should be used for rendering the field in the manager interface. All available fields has to be registered in the singleton Piranha.App after the app has been initialized. Piranha.App.Init(api); // Register custom fields Piranha.App.Fields.Register<SimpleStringField>(); The manager interface is based on Vue.js and assumes that all fields are registered as global components. As these components are written in Javascript you need to register your custom resources in the manager. For more information about this, please refer to Resources in the section Manager Extensions. Let's take a look at how the component for our SimpleStringField could look like. Vue.component("simple-field", { props: ["uid", "toolbar", "model", "meta"], template: "<textarea class='form-control' " + " :" + "</textarea>" }); All field components get the following. This is your custom field, i.e the SimpleStringField serialized as JSON. Meta information about the field collected from both the FieldTypeAttribute and the FieldAttribute on the model. The meta object has the following properties. { uid: "Runtime generated unique string", name: "The field name", title: "The title if this component is used in a list", description: "Optional description", placeholder: "Optional placeholder", component: "The name of the vue component", id: "The field id", isHalfWidth: "How the field is rendered", notifyChange: "If this field should notify changes to title" } Serializers.
https://piranhacms.org/docs/extensions/fields
CC-MAIN-2020-40
refinedweb
558
56.86
The Fast Way to Test Django transaction.on_commit() Callbacks2020-05-20 Django’s transaction.on_commit() hook is useful for running tasks that rely on changes in the current database transaction. The database connection enqueues callback functions passed to on_commit, and executes the callbacks after the current transaction commits. If the transaction is rolled back, the callbacks are discarded. This means they act if-and-when the final version of the data is visible to other database connections. It’s a best practice to use on_commit for things like sending external emails or enqueueing Celery tasks. (See my previous post Common Issues Using Celery (And Other Task Queues).) Unfortunately, testing callbacks passed to on_commit() is not the smoothest. The Django documentation explains the problem: Django’s TestCaseclassinstead. TransactionTestCase is correct and works for such tests, but it’s much slower than TestCase. Its rollback behaviour flushes every table after every test, which takes time proportional to the number of models in your project. So, as your project grows, all your tests using TransactionTestCase get slower. I cover this in my book Speed Up Your Django Tests in the section “ TestCase Transaction Blockers.” on_commit() is one thing that can force you to use TransactionTestCase, “blocking” you from the speed advantages of TestCase. Thankfully there’s a way to test them using TestCase, with a little help from a targeted mock. Django Ticket #30457 proposes adding a function for running on_commit callbacks inside TestCase. I’ve used a snippet similar to those posted on the ticket in several client projects, so I figured it was time to pick up the ticket and add it to Django core. I’ve thus made PR #12944 with TestCase.captureOnCommitCallbacks(). My PR is awaiting review and (hopefully) a merge, and it targets Django 3.2 which will be released nearly a year from now in April 2021. I’ve thus released it in a separate package django-capture-on-commit-callbacks, available now for Django 2.0+. After you’ve installed it and added it to your project’s custom TestCase class, you can use it like so: from django.core import mail from example") These tests POST to a view at /contact that uses an on_commit() callback to send an email. Passing execute=True to captureOnCommitCallbacks() causes it to execute the captured callbacks as its context exits. The assertions are then able to check the HTTP response, the number of callbacks enqueued, and the sent email. For more information see django-capture-on-commit-callbacks on PyPI. Fin I hope this helps speed up your tests, —Adam Working on a Django project? Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests. One summary email a week, no spam, I pinky promise. Related posts: - Common Issues Using Celery (And Other Task Queues) - Django's Test Case Classes and a Three Times Speed-Up Tags: django, python
https://adamj.eu/tech/2020/05/20/the-fast-way-to-test-django-transaction-on-commit-callbacks/
CC-MAIN-2021-04
refinedweb
493
64.81
Im programming with PYTHON... I have two diferent dates...and I want to know the difference (in days) between them. The format of the date is YYYY-MM-DD To explain myself in a better way... I have a function that can ADD or SUBSTRACT a given number and get the date....for example: def addonDays(a,x): ret = time.strftime("%Y-%m-%d",time.localtime(time.mktime(time.strptime(a,"%Y-%m-%d"))+x*3600*24+3600)) return ret Use - to get the difference between two datetime objects and take the days member. from datetime import datetime def days_between(d1, d2): d1 = datetime.strptime(d1, "%Y-%m-%d") d2 = datetime.strptime(d2, "%Y-%m-%d") return abs((d2 - d1).days)
https://codedump.io/share/adgzR976r696/1/difference-between-two-dates
CC-MAIN-2016-44
refinedweb
121
62.75
Python has a collection of scientific libraries that is called the SciPy stack 1 . It consists of powerful data structures to manipulate multidimensional using simple expressions and powerful routines to perform analysis and data manipulation. The SciPy stack consists of the following Python modules: NumPy. Multidimensional arrays and basic operations SciPy. A library for scientific computing which contains functionality for statistics, signal processing, optimization and linear algebra. matplotlibfor plotting pandasprovides easy to use data structures for data with mixed data types. Sympyfor symbolic math IPythonfor a rich Python shell nosefor testing. In addition to these libraries the statsmodels package for statistics and the scikit-learn package for machine learning are very useful. We will use the following statement to import most important functionality from NumPy, SciPy and matplotlib into main namespace. from pylab import * This form is in my opinion easiest to use for beginners. The pylab module imports core components from Numpy, Scipy and matplotlib for easy interactive use. When you get more familiar with Python you can then import only the parts that you need. Bare in mind that there are also other forms that can be used to import modules when you read examples from various sources. Numpy package contains efficient multidimensional arrays that form the basics of data manipulation also in Scipy. The array datatype is the basic type we are using. It can used in scalar computations, like adding two arrays elementwise, or in linear algebra operations. Numpy has methods for reading data from files to arrays, creating arrays with a certain range and converting other Python sequences to arrays. The linspace command can be used to create a vector between given and start endpoints with predetermined number of elements and arange commands is used to create vector with elements with certain difference between elements. Here are some methods to create arrays: >>> linspace(0, 1 ,5) #Five elements from 0 to 1 array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> arange(0, 2, 0.3) #From 0 to 2 by 0.3 array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8]) >>> array([3.2, 1, 4]) #From list array([ 3.2, 1. , 4. ]) The advantage of arrays is that they can be used in equations easily without looping trough all elements like you would need to do with a list. Suppose for instance that we have a 12V power source and we want to calculate the power for currents between 0 and 2A. This is given by formula \( P=VI \) And the solution using Numpy arrays: >>> V = 12 >>> I = linspace(0, 2, 6) >>> I array([ 0. , 0.4, 0.8, 1.2, 1.6, 2. ]) >>> P = V*I >>> P array([ 0. , 4.8, 9.6, 14.4, 19.2, 24. ]) The following table shows for basic operations on arrays. See Numpy refence for complete details . Numpy has easy methods for reading and writing numerical data to and from text files. A simple example: >>> x = randn(5, 3) >>> savetxt('data.txt', x) >>> x2 = loadtxt('data.txt') >>> x2 == x2 array([[ True, True, True], [ True, True, True], [ True, True, True], [ True, True, True], [ True, True, True]], dtype=bool) You can also use converters to read in e.g. dates. The following example will load a datafile with dates in the first column and convert the iso formatted date to numeric format. from matplotlib.dates import datestr2num data = loadtxt("data.txt", converters = {0: datestr2num}) NumPy arrays are very useful and efficient when you only have numerical data, but they are a lot less convenient to work with when you have data consisting of multiple data types such as strings, factors and booleans. The pandas library provides data structures and functions that make working with mixed data types a lot easier. The library is very well documented at , but I will show few examples to give an idea about how the library can be used. The main pandas data structure is the DataFrame. The library provides a several functions to read a DataFrame from files (csv, excel, hdf5) or from SQL database. You can also construct DataFrames from several data structures e.g. lists, dicts and NumPy arrays. Here is a simple example about making a DataFrame from a list of Python dicts: >>> import pandas as pd >>> cowList = [{"id" : 101, "weight" : 650}, ... {"id" : 102, "weight" : 720}, ... {"id" : 103, "weight" : 800}, ... {"id" : 104, "weight" : 560}] ... >>> #Create DataFrame >>> df = pd.DataFrame(cowList) >>> >>> #Look at the contents >>> df id weight 0 101 650 1 102 720 2 103 800 3 104 560 Let’s look at a more interesting example of roughage intake data from dairy cows in feedintake.csv file. The dataset contains roughage feeder trough visit information from 48 cows during 24 hours. Each row corresponds to one visit from a cow with recorded trough number, start and end time, visit duration in seconds and feed intake in kilograms. We will read the data from csv file using pandas: >>> feed = pd.read_csv("data/feed_intake.csv") >>> #Look at the first rows using head function >>> feed.head() cowID trough begin end duration intake 0 9 18 2015-08-18 00:03:50 2015-08-18 00:12:03 493 2.5 1 2 13 2015-08-18 00:06:27 2015-08-18 00:12:18 351 1.3 2 9 18 2015-08-18 00:12:32 2015-08-18 00:17:51 319 1.3 3 43 11 2015-08-18 00:08:06 2015-08-18 00:20:09 723 3.5 4 42 23 2015-08-18 00:03:38 2015-08-18 00:21:10 1052 4.6 We can access the columns of the DataFrame with the column name: >>> feed["intake"].head() 0 2.5 1 1.3 2 1.3 3 3.5 4 4.6 Name: intake, dtype: float64 >>> feed["duration"].head() 0 493 1 351 2 319 3 723 4 1052 Name: duration, dtype: int64 And also remove columns, note that the inplace option can be used to modify an existing object and is more efficient. # Make a copy with dropped column feed2 = feed.drop(["trough"], 1) # Modify existing object feed.drop(["trough"], 1, inplace =True) And select data from the DataFrame e.g. select all data from cow number 1 and plot feed intake vs feeding bout duration: cow1 = feed[feed["cowID"] == 1] plot(cow1["duration"], cow1["intake"], 'o') xlabel("Feeding time (s)") ylabel("Feed intake (kg)") We can easily calculate the total feed intake and feeding time for each cow by grouping the dataset by “cowID” column and applying the sum function. >>> feed_sums = feed.groupby("cowID").sum() >>> feed_sums.head() duration intake cowID 1 9778 73.6 2 11868 66.0 3 858 2.4 4 9796 68.8 5 12848 69.7 You can also apply several aggregate function passing them as a list >>> feed.groupby("cowID").agg([np.sum, np.std]).head() duration intake sum std sum std cowID 1 9778 136.811512 73.6 0.995150 2 11868 235.607678 66.0 1.480723 3 858 109.874474 2.4 0.551362 4 9796 491.439436 68.8 3.548356 5 12848 227.878629 69.7 1.546469
http://pyageng.mpastell.com/book/scipy.html
CC-MAIN-2018-39
refinedweb
1,194
66.64
Using an external solver with Aspen Posted June 17, 2013 at 09:49 AM | categories: programming | tags: aspen | View Comments One reason to interact with Aspen via python is to use external solvers to drive the simulations. Aspen has some built-in solvers, but it does not have everything. You may also want to integrate additional calculations, e.g. capital costs, water usage, etc… and integrate those results into a report. Here is a simple example where we use fsolve to find the temperature of the flash tank that will give a vapor phase mole fraction of ethanol of 0.8. It is a simple example, but it illustrates the possibility. import os import win32com.client as win32 aspen = win32.Dispatch('Apwn.Document') aspen.InitFromArchive2(os.path.abspath('data\Flash_Example.bkp')) from scipy.optimize import fsolve def func(flashT): flashT = float(flashT) # COM objects do not understand numpy types aspen.Tree.FindNode('\Data\Blocks\FLASH\Input\TEMP').Value = flashT aspen.Engine.Run2() y = aspen.Tree.FindNode('\Data\Streams\VAPOR\Output\MOLEFRAC\MIXED\ETHANOL').Value return y - 0.8 sol, = fsolve(func, 150.0) print 'A flash temperature of {0:1.2f} degF will have y_ethanol = 0.8'.format(sol) A flash temperature of 157.38 degF will have y_ethanol = 0.8 One unexpected detail was that the Aspen COM objects cannot be assigned numpy number types, so it was necessary to recast the argument as a float. Otherwise, this worked about as expected for an fsolve problem. Copyright (C) 2013 by John Kitchin. See the License for information about copying.
http://kitchingroup.cheme.cmu.edu/blog/2013/06/17/Using-an-external-solver-with-Aspen/
CC-MAIN-2020-05
refinedweb
260
53.27
Since a long time, Visual Basic and Visual Studio have Crystal report with it. People are saying that since 1993. But in VS2010, they excluded Crystal reports. Yes, what you just heard is right, Crystal Report has been dropped from Visual Studio 2010. But don't worry, it is available as a separate download from the SAP web site. These are the things that I found from the internet. 'It turns out that Crystal Reports for Visual Studio 2010 will be released separately, instead of included with the product and Most importantly, Crystal Reports for Visual Studio 2010 will continue to be free, with no registration required.' 'It turns out that Crystal Reports for Visual Studio 2010 will be released separately, instead of included with the product and Most importantly, Crystal Reports for Visual Studio 2010 will continue to be free, with no registration required.' Download Crystal report from this link, or just directly paste the link below to your address bar and it will ask to save an EXE file. I was searching the internet for Crystal reports in 2010 and I found in 2005, but was not able to find any particular tutorials for 2010. So I thought, let me take a chance to write it for some beginners like me who have not worked on Crystal Reports earlier. In this article, I will show you simple report creation process with screenshots. A picture is worth more than a thousand words, so I always believe in an article with screenshots. Let's start by creating a new website in VS2010. See the following screen: As per figure 1, create a new website in VS2010 and name it as per your choice. Now let me show you the database table structure. The above figure shows the db table structure. And the below figure (Figure 3) will show you some sample data in the table: If you want to run this sample project directly, then you can download the database script from the link at the top. Now we have to create an xsd file as a blank data source as we are going to use strong data type. Here I will divide this tutorial in 5 sub sections as mentioned below: The below figure shows you the process to create an XSD file. For adding an XSD file, click on Solution Explorer -> Right Click on Project -> click on Add new Item and then it will show you the below screen. Click on the ok button, so it will ask for confirmation to put that file in App_Code folder. Just click ok and that file will open in the screen as a blank screen. Now we will add one blank datatable to that XSDfile. Just right click on the file and select Add -> Datatable. It will add one DataTable1 to the screen. Figure 5 shows how to add datatable to XSD file. DataTable1 Now datatable1 is added to XSD file. Now we will add data column to the datatable1 as per figure 6. Remember whatever fields (columns) we add here, it will be available to show on the report. So add column which you want to display in your reports one by one here. datatable1 Remember to give the exact same name for data column as in database and also select data type which is the same as database, otherwise you will get an error for field and data type mismatch. Once we add all the required columns in datatable, then set property for the datacolumn as it has in database. The below figure will show you how to set property for data columns. Default datatype for all the columns is string here so if datatype is other than string then only change it manually. datacolumn string datatype Just right click on the datacolumn in datatable and select property and from property window, select appropriate datatype from DataType Dropdown for that datacolumn. datatable DataType Dropdown datacolumn That's it. XSD file creation has been done. Now we will move to create Crystal report design. Just how you want to create the report. Figure 9 will show you a screenshot. Just click ok button to proceed. It will lead you to figure 10: Under project data, expand ADO.NET Datasets and select DataTable1 and add to the selected table portion located at the right side of the windows using > button. Now click on the Finish button and it will show the next screen (Figure 11): Once report file is added, you can see Field Explorer on the left side near server explorer. Expand Database Fields, under that you will be able to find Datatable that we have created earlier. Just expand it and drag one by one filed from Field Explorer to the rpt file under detail section. Now the report design part is over. Now we have to fetch the data from database and bind it to dataset and then bind that dataset to the report viewer. Let's go step by step. First Drag a CrystalReportViewer control on aspx page from tool box as per below screen: CrystalReportViewer Now we will fetch the data, pass data to the dataset and then add that dataset to the Crystal Report. Below is the C# code which will do the job: using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; using System.Data; using System.Data.SqlClient; using System.Configuration; Below is the final code for reports: protected void Page_Load(object sender, EventArgs e) { ReportDocument rptDoc = new ReportDocument(); dsSample ds = new dsSample(); // .xsd file name DataTable dt = new DataTable(); // Just set the name of data table dt.TableName = "Crystal Report Example"; dt = getAllOrders(); //This function is located below this function ds.Tables[0].Merge(dt); // Your .rpt file path will be below rptDoc.Load(Server.MapPath("../Reports/SimpleReports.rpt")); //set dataset to the report viewer. rptDoc.SetDataSource(ds); CrystalReportViewer1.ReportSource = rptDoc; } public DataTable getAllOrders() { //Connection string replace 'databaseservername' with your db server name string sqlCon = "User ID=sa;PWD=sa; server=databaseservername;INITIAL CATALOG=SampleDB;" + "PERSISTSECURITY INFO=FALSE;Connect Timeout=0"; SqlConnection Con = new SqlConnection(sqlCon); SqlCommand cmd = new SqlCommand(); DataSet ds = null; SqlDataAdapter adapter; try { Con.Open(); //Stored procedure calling. It is already in sample db. cmd.CommandText = "getAllOrders"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = Con; ds = new DataSet(); adapter = new SqlDataAdapter(cmd); adapter.Fill(ds, "Users"); } catch (Exception ex) { throw new Exception(ex.Message); } finally { cmd.Dispose(); if (Con.State != ConnectionState.Closed) Con.Close(); } return ds.Tables[0]; } Now just save everything and run report. It will look like the below figure: Here we will see only report design and rest of the things, you can refer from Section 1. Here we will group Customer, Product, Order and Quantity. For details, just go through Figure 14. Customer Product Order Quantity Just add a report (.rpt) file to the solution. Select the appropriate dataset from popup window. Once it's done, then select grouping option like figure 14. dataset Now, right click on the report, select Report -> Group Experts and the resulting window will look like figure 15: Now we want to group like Customer Name and Product name so first add Customer to the right Panel. Then move product name to the right panel like figure 16: Customer This time Crystal report design will be different than the previous time. See figure 17. GroupHeaderSection1 and GroupHeaderSection2 are added to the report designer. Here Group #1 Name refers to Customer Name and Group #2 Name refers to Product Name. GroupHeaderSection1 GroupHeaderSection2 And also GroupFooterSection1 and GroupFooterSection2 are added below if you want to add something to group footer. GroupFooterSection1 GroupFooterSection2 Now under every group, we want to show the number of orders per customer and productwise, so for that, we have to add summary to the GroupFooterSection2. Refer to Figure 18. GroupFooterSection2 Right Click on the GroupFooterSection select Insert -> Summary. It will show you the next screen (Figure 19). And I have also added Order_ID and Product_Qty field to the detail (section 3) part. GroupFooterSection Order_ID Product_Qty In summary window, select the column which you want to summarize in the first dropdown. Select Sum (First option) from the calculate drop down. Summary Location is already set to the report footer. So just click ok to place that summary field to the report.. I have moved to the FooterSection1 so it will show Customer Wise Total Quantity. Refer to Figure 20. groupFooterSection2 FooterSection1 Now save the report and run it finally. It looks like figure 21. Chart is the most important and visible part of the reporting tool. Crystal has very powerful feature to add chart in report. Let's see how to add chart in CR. Here also, we will see only designing of the chart for other thing. Please refer to Section 1. Here we will show customer wise product ordered quantity in chart. X portion will display Customer name and Y portion will display customers total ordered quantity. customer First add charts to the report design. Right click on the .rpt file and select Insert->Chart. Refer to figure 22. Once you add chart to the report, it will not show chart on the report file but with mouse pointer you can see one blank rectangle is moving. So just click on the Report header. It will open popup for chart style and other options. Refer to figure 23. Now from type tab, select type of the charts like bar chart, line chart, pie chart, etc. form the left side. Select sub type from the right pane like side by side chart, percentage bar chart, etc. I am not going into the detail of it. I am leaving it for you to practice work. And also select vertical or horizontal radio button from the below section if you want to change the chart style vertically or horizontally. Check Use depth effect check box if you need shadow effect on the graph. Refer to figure 23. As per figure 24, move to the next tab data. There are three boxes, available fields, on change of and show values. So move Customer Name from available fields to on changes of box, and move Product Quantity filed to the show value box and click ok. Now you can see chart is added to the report header section as per figure 25. Now, just save the report and run it. You can see a Report as a chart on the screen. Crystal reports provide reports inside report feature which are normally known as a subreport feature. Let me explain it in detail. Here also, we will design only sub report design. For rest of the things, refer to Section 1. Add new report to the solution. Then add Report->Group and select only Customer name because we want to design report for each customer and sub report product wise. So there will be only one group header inside the Customergroup header as per figure 26. customer Customergroup Now right click on Detail section and select Insert->Subreport. Refer to figure 27. Once we add subreport, it will show screen like figure 28. As per figure 28, by default, choose a Crystal Report in project is selected if you want to add report from the project, then otherwise select create a subreport with the report wizard. Once we select create a subreport with Report Wizard (3rd radio button), we have to click on the Report Wizard button to select report type and data source just do as Part - 1 first. Then click on ok button so like chart report it will show a moving rectangle around mouse, click on the detail section where you want to show subreport. Now to edit the sub report, refer to figure 29. Click on the edit subreport option and format the report as per your need. Here I will suggest add product name and product quantity or you can add chart also for sub report. When you click on the subreport button, it will open subreport designer, actually CR will create a separate .rpt file but it will remain hidden inside the main .rpt file so we can't see it.. Now run the report and you can see the result, report inside report like figure 30. Here number 1 is the main report and number 2 is the subreport it's showing title as Product wise. First, let me make it clear as to what is a Cross tab report. Normally, we generate report row wise like first we show customer name, then product wise, etc. But suppose we want to see report as column wise like product name should be displayed as column in report, then cross tab report comes into the picture. See result of Cross Tab report in figure 31. Here also, I will show how to design cross tab report only, for rest of the things, refer to Section 1. First add .rpt file to the solution. Then add cross report to the Report Header section as per the below figure (Refer to figure 32). Remember we can add cross tab report only in Report header or report footer section. Once we click on cross tab report options, it will show moving rectangle around mouse pointer just place it to the report header section. As we click on header section, it will lead to the figure 33. As per the figure, move Customer name field to the Rows section, Product name we want to show as a Column so move it to the Columns fields, and we want to show product total so move it to the summarized fields. That's it. Just run the report and you can see the output as shown in figure 31. Product product It's as simple as that. If you have any queries regarding any type of the above mentioned reports, please let me know by way of comments. I will try my level best to fulfill your request. Let's enjoy reporting! Article Source: DotNet.
http://www.codeproject.com/Articles/166291/Generate-a-report-using-Crystal-Reports-in-Visual?fid=1613977&df=90&mpp=25&sort=Position&spc=Relaxed&tid=4363751
CC-MAIN-2014-52
refinedweb
2,328
74.39
How to split string but keep all delimiters Jack Bush Ranch Hand Joined: Oct 20, 2006 Posts: 235 posted Jul 17, 2011 09:03:54 0 Hi All, I need your regular expression skill to help with finetuning this Java String.split("(?=\\b[\\d{1,4}/?-?|\\$\\d{1,3},\\d{1,3}(,\\d{1,3})?])" that is not retaining all the delimiter correctly. Below is the type of input string used: Los Angeles 9/31-33 Rose St 7 br h $350,000 J M&C Bunker Hill Current output gives: Los Angeles 9 / 31- 33 Rose St 7 br u $ 350 , 000 J M&C Bunker Hill However, I want the output to be: Los Angeles 9/31-33 Rose St 7 br u $350,000 J M&C Bunker Hill I am looking for a clean as simple solution instead of with StringTokenizer or LinkedList . Would finetuning the regular expression achieve the objective? Otherwise, please advice on other possible better solution. The examples available are either messy or not suitable to this requirement. Thanks in advance, Jack James Sabre Ranch Hand Joined: Sep 07, 2004 Posts: 781 I like... posted Jul 17, 2011 09:35:11 0 It is not obvious to me what the split criteria is; your regex certainly does not provide the rule since it fails to do what you want. Is the general rule it to split before a decimal, then before decimal again and then before $ ? If not, you need to define the rule. Also, testing with a single test case does not allow one to have confidence in the resulting regex. Edit: Regular expression use "[ just about anything ]" to define a character set so in ("(?=\\b[\\d{1,4}/?-?|\\$\\d{1,3},\\d{1,3}(,\\d{1,3})?]" you have a character set of "[\\d{1,4}/?-?|\\$\\d{1,3},\\d{1,3}(,\\d{1,3})?]" ! Are you expecting the '[' and ']' to in some way group the content? Retired horse trader. Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me. Greg Brannon Bartender Joined: Oct 24, 2010 Posts: 563 posted Jul 17, 2011 15:30:28 0 Are you making it harder than it has to be? Your desired output simply breaks the example string into 4 parts between desired spaces: between the beginning and the second space, between the second space and the fifth space, between the fifth space and the eighth space, and between the eight space and the end. That's easy enough to do by determining the location of the separating spaces and breaking the string accordingly. Always learning Java, currently using Eclipse on Fedora. Linux user#: 501795 Luigi Plinge Ranch Hand Joined: Jan 06, 2011 Posts: 441 I like... posted Jul 17, 2011 21:06:16 0 OP, it's not really clear what exactly your split criteria are. It would help if you tried to describe it in words for any address. If your intention is "start a new line when the first character of a word is a number or a $", I'd do something like this: String d = "Los Angeles 9/31-33 Rose St 7 br h $350,000 J M&C Bunker Hill"; StringBuilder r = new StringBuilder(); for (String s : d.split(" ")) { if(!s.isEmpty() && (s.charAt(0) == '$' || (s.charAt(0) >= '0' && s.charAt(0) <= '9'))) r.append("\n"); r.append(s).append(" "); } System.out.println(r.toString()); It's a bit longer, but it more understandable and maintainable than an unintelligible regex, and actually works... Or here I tried regex: Pattern p = Pattern.compile(" [0-9$]"); Matcher m = p.matcher(d); StringBuilder sb = new StringBuilder(); int pos = 0; while(m.find()){ sb.append(d.substring(pos, m.start())).append("\n"); pos = m.start() + 1; } sb.append(d.substring(pos)); System.out.println(sb.toString()); Or how about a recursive function: static String get(String input, Pattern p, String output) { Matcher m = p.matcher(input); return m.find() ? get(input.substring(m.start() + 1), p, output + input.substring(0, m.start()) + "\n") : output + input; } String r = get(d, Pattern.compile(" [0-9$]"), "") System.out.println(r); Luigi Plinge Ranch Hand Joined: Jan 06, 2011 Posts: 441 I like... posted Jul 17, 2011 23:16:49 0 Here's a more general method that works smilarly to String.split, which you can cut out and keep, paste into your class, add to your toolkit... import java.util.*; import java.util.regex.*; /** * Splits a String according to a regex, keeping the splitter at the end of each substring * @param input The input String * @param regex The regular expression upon which to split the input * @param offset Shifts the split point by this number of characters to the left: should be equal or less than the splitter length * @return An array of Strings */ static String[] splitAndKeep(String input, String regex, int offset) { ArrayList<String> res = new ArrayList<String>(); Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int pos = 0; while (m.find()) { res.add(input.substring(pos, m.end() - offset)); pos = m.end() - offset; } if(pos < input.length()) res.add(input.substring(pos)); return res.toArray(new String[res.size()]); } /** * Splits a String according to a regex, keeping the splitter at the end of each substring * @param input The input String * @param regex The regular expression upon which to split the input * @return An array of Strings */ static String[] splitAndKeep(String input, String regex) { return splitAndKeep(input, regex, 0); } In your case you could do String d = "Los Angeles 9/31-33 Rose St 7 br h $350,000 J M&C Bunker Hill"; for (String s: splitAndKeep(d, " [0-9$]", 1)) System.out.println(s); (The 1 is because we want the number part to the matcher group to appear at the start of the following string, rather than with the space at the end of the previous one.) James Sabre Ranch Hand Joined: Sep 07, 2004 Posts: 781 I like... posted Jul 18, 2011 02:09:06 1 The OP has not yet defined the syntax of the data and the criteria then needed to perform the split. The original regex is most definitely badly flawed and the fact that the Pattern class does not throw an exception is just luck. Until the OP defines his requirement we are only guessing but I suspect all this proposed extra code is over elaborate. My best guess is that all the OP needs is String[] theSplitString = theString.split(" (?=[0-9$])"); Jack Bush Ranch Hand Joined: Oct 20, 2006 Posts: 235 posted Jul 18, 2011 07:51:27 0 Hi James, You are a champion! That is it. Well guessed. Below is the output I was looking for: Los Angeles 9/31-33 Rose St 7 br h $350,000 J M&C Bunker Hill Los Angeles 9/31-33 Rose St 7 br u $350,000 J M&C Bunker Hill New York 40 June St 3 br h $490,000 Century 21 New York 40 June St 3 br h $490,000 Century 21 Excellent. Would you mind explain how (?=[0-9$]) works? Thank you very much, Jack James Sabre Ranch Hand Joined: Sep 07, 2004 Posts: 781 I like... posted Jul 18, 2011 08:01:52 0 Jack Bush wrote: Would you mind explain how (?=[0-9$]) works? Jack Bush Ranch Hand Joined: Oct 20, 2006 Posts: 235 posted Jul 18, 2011 21:33:17 0 Hi Greg & Luigi, Thank you for your detail suggestion but it wasn't what I was after. Cheers, Jack subject: How to split string but keep all delimiters Similar Threads shift operator Q#5 majji. Can any one explain this please?? Problem allowing comma using regex Alphabets How to mask string not conforming to a regular expression pattern All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/545716/java/java/split-string-delimiters
CC-MAIN-2015-06
refinedweb
1,320
70.13
Following up on my previous post about Prism for WinRT applications, I thought I’d start digging in and trying to see what’s present in the Prism framework libraries. I wasn’t entirely sure how to approach this. With the Prism bits you get three things; - The Prism libraries for Windows Store applications - A number of quick-start projects - The AdventureWorks Shopper application and then there’s also a bunch of documentation that you can either read online or download. I thought about a few different ways that I could start to explore what was there. One thing I’d point out is that I have a bit of an aversion to samples so I tend to look at samples last rather than first and I know a lot of people work the other way around so bear in mind while you’re reading this that I have a particular way of going about these things and that these are really just my slightly scrappy notes as I try and poke around the new Prism framework and figure out what’s there for a Windows Store app. If you want the definitive guide – read the definitive docs The Docs I started with the docs. At the time of writing, I haven’t completely finished reading them but what I’d say from my first reading is; - They are quite big at around 200 pages. - They are surprisingly readable for a 200 page document. - There’s a lot in there that is going to be useful to you whether you ever use the Prism framework or not. If you’re building a Windows Store app (or a Phone app) then I think these docs are still very much worth a read as they cover a lot of ground. Here’s some topics that I was not expecting to find in the Prism docs; - “What is MVVM?” - “Adding design time data” - “Reading error messages from resource files” - “Making key decisions about touch” - “Handling suspend, resume” and so on – it’s a long list of really useful and thought provoking topics for anyone who’s thinking about building an app. As an aside, one of the things that I’m not overly keen on is seeing Prism describing itself as guidance for “Windows Store Business Applications”. For me, I don’t really see the guidance as being anything specific to business applications. I see the guidance as being for writing good, structured, layered, maintainable applications. I don’t think those attributes should only be thought about in the context of business applications – they need to be applied to all applications that are going into the Windows Store and I’d almost say that they are more important for consumer applications because at least in a business you typically have a closer relationship with the end user whereas in a general Store, you need to make sure your app is solid from day one as your consumer isn’t likely to drop you an email if the app doesn’t meet their expectations. Other than that, I think the docs are great and really deserve a proper read and I’ll finish my own reading of them in the coming days. The Framework/Libraries The next thing that I wanted to do was to have a poke around the libraries themselves. The package distributes; and so I figured that I’d start off in the world of the pub-sub-events folder and then poke into the StoreApps folder and, from time to time if I get stuck, maybe I’d drop into the Quickstarts folder to see if that helped me figure things out. Prism.PubSubEvents The idea of the pub-sub events project is to promote loosely coupled events. In .NET events are first class citizens of the languages like C# and VB but there’s a tight coupling between ClassA and ClassB if the former wants to handle an event raised by the latter – they need to know about each other from a typing perspective if they are going to achieve that. They also will need to know about whatever type represents the event data that’s passed from the source of the event to the sync of the event but that’s pretty much unavoidable. As an aside, I’m reminded a little bit of the old notion of “connection points” in COM which had a form of loosely coupled events based around (being COM) interfaces rather than implementation types but that’s really “another story” so let’s leave that alone. In Prism, there’s this notion of an EventAggregator which looks like this; The fact that EventAggregator implements an interface means that a class can make use of it without taking a hard dependency on anything other than the interface type ( i.e. with no hard dependency on the implementation type EventAggregator itself ). It also means that it’s easy to register an event aggregator into some Inversion of Control (IoC) container and have it resolved dynamically to some type which implements IEventAggregator. What does it do? It provides a dating agency for events. Let’s say that I’m building an app which can be used anonymously but, equally, can be used by a logged on user and the decision as to whether to login or not might be up to the user and it might be possible for the user to login at any time during the lifetime of the application (perhaps it’s on the Settings charm in Windows 8). When the user logs in, I might need to fire an event around the application to let “interested” components know that the user has logged in or logged out. Let’s say that the event payload looks like; public class LoginStatus { public bool IsLoggedIn { get; set; } public string UserName { get { if (!this.IsLoggedIn) { throw new InvalidOperationException("Not logged in"); } return (this._userName); } set { this._userName = value; } } string _userName; } If I wanted one component to be able to “publish” an event of this “shape” and another component to be able to “subscribe” to an event of this “shape” then the only thing that I really want to share between those 2 components is the “shape” of the data class itself along perhaps with any common “pub/sub” infrastructure that I’m prepared to take a dependency on to get the job done ( in this case, that infrastructure is Prism PubSub Events ). I’d need to create an EventAggregator somewhere; // Ok, so in this instance I know where my aggregator is coming from // because I'm creating it but let's pretend it's in a container. EventAggregator aggregator = new EventAggregator(); // Let's treat the aggregator as though we don't know very much // about it. IEventAggregator abstractedAggregator = aggregator; Now, assuming that I have some code that “knows” how to locate an IEventAggregator and that the code “knows” about the previously defined LoginStatus class I could define an event args class which will “carry” the LoginStatus event data; public class LoginStatusChangedEventArgs : PubSubEvent<LoginStatus> { } and then I could publish an event; LoginStatus newLoginStatus = new LoginStatus() { IsLoggedIn = true, UserName = "Mike" }; abstractedAggregator.GetEvent<LoginStatusChangedEventArgs>().Publish( newLoginStatus); and then some other component can subscribe to receive events of that particular shape – e.g. IEventAggregator abstractedAggregator = aggregator; abstractedAggregator.GetEvent<LoginStatusChangedEventArgs>().Subscribe( loginStatus => { // Do something with the new login status. } ); Now, there are some bits in there which I left out and there are some additional nuances that the library does around this event publication/subscription functionality. Firstly, what does PubSubEvent<T> look like? Putting that onto a class diagram really involved putting most of the rest of the pub sub library code onto a diagram; In short – PubSubEvent<T> is a class that maintains a list of subscribers to an event of “shape” <T> and knows how to publish data of shape <T> to those subscribers. It has some additional smarts though which can best perhaps be seen by looking for all the overloads of the Subscribe() method; We can subscribe to an event of a particular shape but we can also specify on which thread we’d like that subscription delivered; - Dispatched on whatever thread the publisher calls the Publish() method from. - Dispatched to the synchronization context represented by the SynchronizationContext property on the EventBase base class – this would usually mean “the UI thread” but it could be any arbitrary synchronization context. - Dispatched from the .NET thread pool. and we can also specify a filter (Predicate<T>) to filter when we’d like the event subscriptions delivered to our subscriber. For instance – in my example I might only want events delivered if the user was logged in or logged out. Finally, there are some smarts here around garbage collection – that is, if objectA makes a subscription to an event then should that subscription keep objectA alive in the absence of any other references to objectA or should objectA get garbage collected? If you look at the class diagram, this is where IDelegateReference and DelegateReference come in – these are being used to keep weak references (where requested) to the delegates provided for any filtering and for the subscription itself. I think this is an important topic because in MVVM applications you might often want to use this form of loose-event communication to get a piece of data from ViewModelA to ViewModel B. However, it’s often the case that two otherwise unrelated view models would have mutually exclusive lifetimes and so this idea of which components are “alive” and when they are “alive” becomes important. Subscribing returns a SubscriptionToken and that is needed to be kept for a call to Unsubscribe (subject to all I’ve just said about weak references ) and disposing of a SubscriptionToken looks to be equivalent to passing it to the Unsubscribe() method. One last things about the pub-sub library – it is portable so you can build code into a portable class library that makes reference to this code and then use that library from any .NET (4+), Silverlight (4+), Windows Phone (7.1+) or Windows Store application. Prism.StoreApps As you might expect, there’s quite a lot more in the Prism.StoreApps project than there is in the pub/sub events project. One of the things that occurs to me first when looking at this code is that it perhaps could be re-factored to extract it out into more than one library because some of the code in here is not specific to building a Windows Store application and so might gain from being packaged as a separate library to get some re-use from other kinds of app projects (e.g. Windows Phone). The DelegateCommand Class An example of that would be this DelegateCommand class; This is a class which takes a couple of delegates and puts an ICommand interace on top of them. Everyone in the MVVM world needs this kind of class and most people have written it once or twice themselves and it really belongs in the .NET framework but it’s good that it’s here in this library. That said, I’d argue that this is not specific to building Windows Store apps – it’s applicable in Windows Phone, WPF and Silverlight apps too so could maybe be packaged separately. Regardless, while we’re looking at it – it’s a simple way to make a command on a view model. So, if you have some view model; public class MyViewModel { DelegateCommand _someCommand; public MyViewModel() { _someCommand = new DelegateCommand( OnSomeCommand, OnCanExecuteSomeCommand); } void OnSomeCommand() { } bool OnCanExecuteSomeCommand() { return (true); } } then you can use DelegateCommand to provide an ICommand implementation for you over the top of one or two delegates ( one for execution, one for “can execute” ) and there’s a method there for raising the CanExecuteChanged event of ICommand. It’s worth saying that you can omit the “can execute” delegate and the class defaults to returning true to signify “Yes, I can execute”. The ViewModel Class The MyViewModel class I just wrote wouldn’t get me very far – it’s well understood that it needs to implement INotifyPropertyChanged so there’s a base class in the Prism framework that gives me an implementation of that interface – it’s called BindableBase; and anyone who’s looked at the Windows Store templates in Visual Studio 2012 will be familiar with BindableBase and will know that it implements INotifyPropertyChanged for you and will (like me) be scratching their heads as to why this still isn’t in the .NET framework around 8 years after we first started to need an implementation of INotifyPropertyChanged. Anyway, it’s here in this library so that’s a good thing. Looking a little further, it’s clear that the Prism ViewModel base class does more for us than just INPC. It also provides two other pieces of functionality; - It implements INavigationAware such that if an app has a Page1/ViewModel1 which drives a navigation to Page2/ViewModel2 and possibly passes a parameter as part of that navigation then it’s possible for the ViewModel2 to pick up that parameter and do something with it. Anyone who’s been along to my recent Windows Phone sessions will have seen me build an interface and implementation a little like this to solve this exact same problem so it’s nice to see something like this here in Prism. Without something like it, it can be a bit tricky to have a view model get access to navigation parameters from the built-in navigation service which is somewhat tied to the UI classes. - It has a notion of a state dictionary – this is for the app lifecycle management situations in a Windows Store application where we need to suspend an app and save its state away which potentially means saving the state of views, view models and services. This is how Prism builds support for the view model being able to plug-in to that requirement. It turns out that these things work together. Having a look at those two methods; If we accept that there’s some componentry somewhere which can hook into Windows 8 Suspend/Resume and navigation such that; - when we are suspending the app that componentry can call a ViewModel’s OnNavigatedFrom method and ask it to populate a state dictionary which can then be persisted along with the navigation history (depending on the navigation mode). - when we come back to an app in the case where the app was terminated by Windows that componentry can restore the navigation history, restore the view and the ViewModel and then pass into the OnNavigatedTo method the stored dictionary then this can be used to suspend/resume ViewModels. The base ViewModel class already does this in that it looks for any properties on the ViewModel which have a custom attribute applied to them; and it automatically grabs their values and stores them into the dictionary. Where this dictionary is stored is a mystery at this point in my exploration but I’m sure it’ll become clear later on The ViewModelLocator Class One of the pain points in MVVM is always in trying to decide the Chicken/Egg situation between a View and its ViewModel and how they get instantiated and learn about each other ( by which I mean the ViewModel becomes the DataContext of the View ). The Prism library has a ViewModelLocator class to help with this. It’s pretty simple to understand but that’s not to say that it’s not useful or powerful. Here it is; and it’s probably not immediately obvious from that picture that it brings with it a an attached property called AutoWireViewModel. What that means is that I can author a view in an app like this; and the presence of that AutoWireViewModel property is going to cause the ViewModelLocator class to attempt to “magically” set the DataContext of this view for me. How does it do that? - The class maintains a list of factories. It’s a simple mapping from a type name (the type name of the view) to a factory function which is used to create the ViewModel. That list of factories can be appended to using the Register method. - If the factories list doesn’t know how to produce the view in question then; - The defaultViewTypeToViewModelTypeResolver is used to try to map from the Type of the view to the Type of the ViewModel. - This resolver can be overridden by calling the SetDefaultViewTypeToViewModelTypeResolver method. - Without any overriding, the class will essentially try to take the name of the View type and manipulate the namespace to change “Views” into “ViewModels” and “View” into “ViewModel”. This would mean that if you have a Views folder in your project with classes ending in …View then they would be matched up with classes ending in …ViewModel in a corresponding ViewModels folder. - The defaultViewModelFactory is used to try and create the ViewModel. - This factory can be overridden by calling the SetDefaultViewModelFactory method. - Without any overriding, the class will try to use Activator.CreateInstance() to create the ViewModel. This is all nicely lined up to allow for dependency injection. At application start-up time it’s easy to grab hold of the ViewModelLocator and call its SetDefault…X methods to pass in functions which can delegate the work of creating ViewModels to a IoC container. Navigation Navigation can be a bit of a struggle in an MVVM app. The main problem is that navigation is performed by a Frame which is a UI construct and we don’t usually have reference to UI constructs in a ViewModel which means that we usually need to have some abstraction of a navigation service which make the services of the Frame available from within a ViewModel without exposing the details of the Frame itself to the ViewModel. The other struggle with navigation is that it works differently on Windows 8 to how it works on Windows Phone 8 which means that a developer wanting to target both with a single codebase has to do some more abstraction work. The Prism libraries have abstracted a navigation service. The essence of this is the INavigationService interface; where the Navigate method has moved towards a hybrid of the Windows 8 style implementation where you navigate to a Type of page and pass a parameter of type object and the Windows Phone implementation where you navigate to a URI with the parameter embedded within it. The Navigate() method looks like; so you’re navigating based on some string plus an object parameter and that string can then be mapped onto some actual view type at a later point. A ViewModel (or some other component) can then take a dependency on INavigationService and an implementation of the service could be injected. In the framework, there’s an implementation called FrameNavigationService; Initially, I’d have perhaps expected the FrameNavigationService to make direct use of a Frame but, instead, it further abstracts its dependence on a Frame by hiding it behind IFrameFacade. That interface (which has interesting GetValue/SetValue methods on it like it was derived from DependencyObject) is then implemented by another class FrameFacadeAdapter which implements it on top of an actual (Windows 8) Frame; The FrameNavigationService needs an IFrameFacade to work but it also depends on two other bits of functionality; One is a function that knows how to resolve a string parameter into a Type. When the navigation service is asked to Navigate(“foo”) it can pass that string through the navigationResolver in order to map from the string name to an actual view type. The other service that’s required by the FrameNavigationService is the ISessionStateService; The provided implementation of this session state service (SessionStateService) firstly has a Dictionary<string,object> called SessionState which is publicly accessible can be used to store the objects that represent global state and the methods SaveAsync() and RestoreSessionStateAsync() will write/read that dictionary into a file in much the same way as the SessionStateManager class from the Visual Studio templates does (possibly with the addition of encrypted data). In order to save those objects stored in the state dictionary, they will need to be serializable with the DataContract serializer and any additional types that the serializer needs to know about need to be registered via the RegisterKnownType() method. The other thing that the class does is to manage a set of frames (represented by IFrameFacade here) although most apps will perhaps have a single frame. Frames (IFrameFacades) can be registered with the service via the RegisterFrame(IFrameFacade facade, string sessionStateKey) method. Registration stores the session key passed with the IFrameFacade on the IFrameFacade itself (via the SetValue method) and stores a weak reference to the IFrameFacade in a list held by the SessionStateService. Essentially, in combination with the GetSessionStateForFrame(IFrameFacade) method, a slot in the SessionState is reserved for the frame using the session state key for that IFrameFacade. That slot stores another Dictionary<string,object> specifically for the frame. A weak reference to the frame is also stored in a list inside of the SessionStateService. So, we end up with a Dictionary<string,object> where some of the entries are more Dictionary<string,object> for any frames that have registered a key to store their state. When the state service is saving state, it walks its list of IFrameFacades and makes sure that each one records its current navigation state into its own dictionary and then the service writes the whole “master” dictionary to a file. The FrameNavigationService ties all these things together. Most of its “work” is delegated down to the IFrameFacade (which in turn delegates down to the Frame) so for simple things like; - GoBack() - CanGoBack() - ClearHistory() not much happens. When it comes time to Navigate(), the service uses the navigationResolver to translate the string that has been passed to Navigate() into a Type parameter before asking the underlying IFrameFacade to actually Navigate() which, in turn, will ask the underlying Frame to Navigate(). Finally, the service effectively adds the “idea” of navigation support to ViewModels. The service attaches event handlers to the IFrameFacade’s Navigating and Navigated events such that whenever navigation occurs, the IFrameFacade is interrogated to see if it contains Content and if that content is a FrameworkElement then that can be used to obtain a DataContext and, finally, if that object living in the DataContext implements INavigationAware then that provides a means via which the ViewModel can be notified as the app is navigating to/from the page that is loading that ViewModel. This is done via INavigationAware.OnNavigatingTo and INavigationAware.OnNavigatingFrom and it’s a means via which the ViewModel can; - Pick up the navigation parameter. - Pick up the navigation mode. - Save/Restore state for itself. The FrameNavigationService also makes sure that if the app suspends or wakes from a termination then the navigation history is put back in place on the frame( s ) and the relevant ViewModel is driven to save/restore state by driving it through this OnNavigatingTo/OnNavigatingFrom logic. The VisualStateAwarePage Class The VisualStateAwarePage is the Page-derived base class for your pages and feels pretty similar to the LayoutAwarePage that comes with the Visual Studio templates (you get that page if you add a Basic Page project item to a Windows Store project). The page does a number of things; - Watches for view/orientation changes and drives the UI into different visual states depending on those changes. The state names used are taken directly from the ApplicationViewState enum and so will end up being called “FullScreenLandscape”, “Filled”, “Snapped”, “FullScreenPortrait”. These state changes are handled for the page itself along with any controls on the page that have been registered as being “interested” in visual state changes via the StartLayoutUpdates method. - Implements state management for the page (i.e. the View rather than the ViewModel) by providing virtual methods LoadState and SaveState which are passed Dictionary<string,object> for you to save/restore your view’s state. - Provides some convenience methods for forward/back/home navigation and for trapping mouse/keyboard/touch gestures to trigger them. and that’s pretty much it for the VisualStateAwarePage except that it does one other slightly “odd” (to me) thing. There’s a public static property on this class called GetSessionStateForFrame and that property is of type Func<IFrameFacade, IDictionary<string,object>>. This is part of (2) above – the state management of the view. When the page is navigated to or navigated from and wants to restore/save state it needs somewhere to put that state. What it does is to; I must admit that I found this functionality a bit “opaque” and it felt a little to me like there’s a missing interface somewhere – it took quite a bit of staring at to try and figure out what’s going on. The MvvmAppBase Class The MvvmAppBase class is the class that brings all the other pieces together for your app and replaces the standard Application class that provides the base class in the framework and in the standard Visual Studio templates. It derives itself from that Application class and, in my view, simplifies some of the rough edges of that class for you. It does quite a lot of work on your behalf and provides lots and lots of places to hook into the default behaviour by overriding methods. The starting point for this behaviour is in the override of the OnLaunched method for when the application first runs up. This initialises the root frame which involves a lot of functionality; - Creating the Frame. - Creating a FrameFacadeAdapter to implement IFrameFacade on top of that Frame. - Creating the SessionStateService to provide an implementation of ISessionStateService and storing this in a protected property (SessionStateService of type ISessionStateService) of the MvvmAppBase class itself and registers the main Frame with that service. - Creating the INavigationService by calling a virtual method CreateNavigationService and passing it the IFrameFacade and the ISessionStateService. This is stored in a protected property NavigationService on the MvvmAppBase class itself. - Wires up the static property VisualStateAwarePage such that it has a method to call in order to get the Dictionary<string,object> session storage for a particular frame. - Wires up the SettingsPane such that when it requires settings information for your app it will effectively call the classes own virtual method called GetSettingsCharmActionItems() which you can implement to return your settings options. - Wires up the ViewModelLocator so that, by default, it will call a virtual function Resolve on the MvvmAppBase class in order to create view models. - Calls a virtual method to OnRegisterKnownTypesForSerialization() in case you have any to register with the ISessionStateService. - Sets up handlers for the suspend/resume/terminate state management pieces (and implements those handlers). - Calls a virtual OnInitialize() method via which you can initialise your app’s code. That’s quite a lot and you’d need a few overrides in order to get this wired up to look to a container for resolution of these types. Once the application is actually up and running the class also; Checks the application manifest and if the Search charm is declared there then it grabs hold of the SearchPane and, effectively, wires up the submission of a search query to its own OnSearchApplication virtual method for you to override. It’s worth pointing out that the class also overrides the base class OnSearchActivated such that it initialises things and then calls the same OnSearchApplication virtual method thereby giving you one place to implement that functionality. Finally, the Suspending event is wired to an OnSuspending handler which will do the right thing around the NavigationService and the SessionService ( using the properties on this class to get hold of those values ) and will also set a simple IsSuspending flag while the operation is in flight. Wrapping Up At a sketchy level, that’s perhaps most of the classes that Prism provides. I’ve not touched on some of the other services like the ability to display flyouts but that’s my first encounter with the source code. I’ve also not poked so far into the reference application. What I think I’d want to do next is build my own “Hello World” using an IoC container like Unity or AutoFac and see how that goes. Of course, there’s already a sample in the QuickStarts which does exactly this but I figure I’ll learn more by experimenting with it for myself…
https://mtaulty.com/2013/06/12/m_14859/
CC-MAIN-2021-25
refinedweb
4,738
52.02
Asked by: Variable Array I am wanting to create an Array or Collection of mixed data - like a list of names, addresses and phone numbers for multiple groups and people. I am new to C# and have only been able to locate information for what I would describe as a 1 dimensional array or list. For example if I want to have the following excel-like table in C# - how do I configure the code? Name Address Phone Number Joe 123 anywhere 502/123-4567 Jill 235 someplace 418/229-4750 etc. Thanks in advance Ken in Kentucky Question All replies You need to think in a more structured way rather than in an "Excel-like bunch of cells holding anything" way! What you are describing is an array/collection of person information, where each block contains the person's name, address, phone number and so on. So first you need to describe your person, for which you can define a struct or class. E.g. public class Person { public string Name {get;set;} public string Address {get;set;} public string PhoneNumber {get;set;} } Now you could have an array of Person objects. E.g. Person[] persons = new Person() { new Person {Name="Bob"}, new Person {Name="Carol", Address="somewhere"} } Note that this is not necessarily the best way - that all depends on where you get your data from, what you want to do with it and so on. For example, you may want to define an Address class first holding a FirstAddressLine, SecondAddressLine, Town, County etc; and then define your Person class to hold an Address object rather than a simple string for the address. - Edited by RJP1973 Friday, February 17, 2017 2:18 PM - Proposed as answer by Cor LigthertMVP Sunday, February 19, 2017 10:53 AM You need to create an array containing 'objects', for each 'object' you want to include the Name e.g. "Joe", Address e.g. "123 anywhere" and phone number e.g. "502/123-4567" To do this we create a struct or class first, this is like a blueprint of what each 'object' is going to contain public class Person { public string Name {get;set;} public string Address {get;set} public string PhoneNumber {get;set} public Person(string Name, string Address, string PhoneNumber) { this.Name = Name; this.Address = Address; this.PhoneNumber = PhoneNumber; } } This allows us to create an instance of the object 'Person', set a Name, Address and PhoneNumber then add it into our array We can create a new instance of the object 'Person' a couple of ways - Person person = new Person("Joe", "123 anywhere", "502/123-4567"); or Person person = new Person; person.Name = "Joe"; person.Address = "123 anywhere"; person.PhoneNumber = "502/123-4567"; This will create an instance of 'Person' with the following details Name: 'Joe', Address: '123 anywhere', PhoneNumber: "502/123-4567" Now you can create a collection of 'Person objects' Person[] people = { new Person("Joe", "123 anywhere", "502/123-4567"), new Person("Jill", "235 someplace", "418/229-4750") }; This will create an array of instanced objects of type 'Person' each holding a name, address and phone number, to use the data in this array we can index it then use the set methods to return values, e.g. (using the array we created above) Console.WriteLine(people[0].Name); Console.WriteLine(people[1].PhoneNumber); //Console output would look like //Joe //418/229-4750I'm sure its not the best if youre copying from an excel file, but its simple, hope it helps someone - Edited by Daniel Loudon Saturday, February 18, 2017 1:02 AM - Proposed as answer by Wendy ZangMicrosoft contingent staff, Moderator Monday, March 06, 2017 4:24 AM The Person class is the way to go, but the heck with using an Array. Use a generic List: List<Person> Persons = new List<Person>(); Person person = new Person("Fred", "1234 Main Street", "(509) 123-4567"); Persons.Add(person;) ~~Bonnie DeWitt [C# MVP] - Proposed as answer by Wendy ZangMicrosoft contingent staff, Moderator Monday, March 06, 2017 4:24 AM
https://social.msdn.microsoft.com/Forums/en-US/e175b9e8-d110-4e2a-bafa-5615c2334be8/variable-array?forum=csharpgeneral
CC-MAIN-2018-17
refinedweb
671
54.36
the problem is for me to compute and approxiamte value for euler's constant by summing the series (adding up the terms 1, 1/2, ...., 1/n in that order and then subtracting the value fo In(n)). I have to do this with both double and float arithmetic. Here is what I have so far. import java.io.*; public class PP2 { public static void main(String[] args) throws IOException { System.out.println("Enter the limit for sum:"); BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in)); String S = kbd.readLine(); int loops = Integer.parseInt(S.trim()); int n; for (n = 1; n <= loops; n++) { double sum = sum + (double)(1/n); float sum2 = sum2 + (float)(1/n); } double condoub = sum - (double)Math.log(loops); float conflout = sum2 - (float)Math.log(loops); System.out.println("Euler's const, double: =" + condoub); System.out.println("Euler's const, flout: =" + conflout); } } thanks for the help Forum Rules Development Centers -- Android Development Center -- Cloud Development Project Center -- HTML5 Development Center -- Windows Mobile Development Center
http://forums.devx.com/showthread.php?147037-Compute-and-approximat-value-for-euler-s-constant&p=437558&mode=threaded
CC-MAIN-2017-09
refinedweb
168
51.65
Iteratees for cats I figured I better bring this topic to iteratee channel. As mentioned in Circe channel, I want to produce json with Circe in a streaming fashion. I’ve tried to start and faced one question. Basically I need a function like this (imports omitted): def writeJson[T: Encoder](enum: Enumerator[Task, T], file: File): Task[Unit] = { val printer = Printer.noSpaces.copy(dropNullKeys = true) val opener = Enumerator.enumOne[Task, String]("[") val closer = Enumerator.enumOne[Task, String]("]") val entries = enum.map(_.asJson.pretty(printer) + ",") opener.append(entries).append(closer).into(writeLines(file)) } The problem is the comma after the last entry, which makes the resulting json invalid. Is there a way to somehow introspect the Enumerator and to know if that’s the last entry, to handle it differently? Iteratee, Enumerateeand Enumerator, what they do on their own and how they interact with each other. IIRC you’ve promised a blog post about Iteratee architecture some time ago (no pressure! :smile: ) , but in absence of it, could you please explain here what they are and what they do, in general?? Iterable[A]and () => Aare equivalent.)
https://gitter.im/travisbrown/iteratee?at=585bff9d0730ce6937fa3a5d
CC-MAIN-2022-21
refinedweb
187
50.63
I am making a game, and the player has multiple weapons, and I want to display which weapon is being used. I made two pictures to show which picture is being used. But I have no idea how to make it switch from one to another. I understand how to access the GUITexture, but I don't understand how to access the Texture that is in my assets folder. This is the code I am currently using, but I don't know what's going wrong. GameObject.Find("Weapon").guiTexture.texture = Resources.Load("sword") as Texture2D; The image is names "sword". If you find a URL to my problem, please link me to it, but I could not find an answer. Answer by Imankit · Jan 19, 2013 at 09:47 AM public GameObject weapon; // drag your GUITexture object here in inspector // When you want to change the texture... weapon.GetComponent<GUITexture>().texture = Resources.Load("sword") as Texture2D; // This is for C# I tried that and it worked even worse than before. Before, the image disappeared, so the GuiTexture was connected, but now the image doesn't even disappear. Really all I'm looking for is how to change the right side with resources.load to make it work. In which folder your Texture is if its in Resources folder then it should have worked.. Answer by JPLKit · Mar 27, 2014 at 03:55 PM but I don't understand how to access the Texture that is in my assets folder. You want to create a folder called Resources inside your Assets folder and put your image(s) inside the Resources folder. (Capital R in resources is important) Then you can use Resources.Load(); Answer by blenderblender · Nov 02, 2014 at 10:10 AM using UnityEngine; using System.Collections; public class GUIController : MonoBehaviour { public Texture2D yourtexture; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnGUI() { GUI.DrawTexture(new Rect(10,10,60,60), your properly load textures? 2 Answers How to make a custom GUITexture at runtime? 2 Answers Animate a GuiTexture to make a spinning object 2 Answers Changing custom import settings at RUNTIME 0 Answers New GameObject with GUITexture is a Horribly Incorrect Size 1 Answer
https://answers.unity.com/questions/383479/how-to-change-the-image-texture-of-a-guitexture-in.html
CC-MAIN-2021-04
refinedweb
374
63.29
Class instance with names defined by string In 'pure ruby' (not rails), given a class: class Person end ...and an array of strings: people_names = ['John', 'Jane', 'Barbara', 'Bob'] how can I instantiate the Person class, with each instance variable named one of the elements in my array? John = Person.new Jane = Person.new Barbara = Person.new Bob = Person.new Its pretty unclear what you actually want here since an identifier in ruby starting with an uppercase letter in Ruby is a constant. John = Person.new Jane = Person.new Barbara = Person.new Bob = Person.new You can dynamically assign constants with Module#const_set. module MyModule ['John', 'Jane', 'Barbara', 'Bob'].each do |name| const_set(name, Person.new) end end # this imports the constants into Main which is the global scope include MyModule John => #<Person:0x007f973586a618> Instance variables on the other hand use the @ sigil. You can dynamically assign instance variables with instance_variable_set: ['John', 'Jane', 'Barbara', 'Bob'].map(&:downcase).each do |name| instance_variable_set("@#{name}", Person.new) end @john # => #<Person:0x007f9734089530> While you can declare an instance variable named @John it violates the conventions of the language. Local variables cannot actually be defined dynamically. You can only change existing variables via eval and binding.local_variable_set. def foo a = 1 bind = binding bind.local_variable_set(:a, 2) # set existing local variable `a' bind.local_variable_set(:b, 3) # create new local variable `b' # `b' exists only in binding p bind.local_variable_get(:a) #=> 2 p bind.local_variable_get(:b) #=> 3 p a #=> 2 p b #=> NameError end Creating and Using Classes and Methods, The string identifier is both the internal class name and the name of the A scope refers to the methods and object variables defined for a single class (not This means that for each object or instance of a class, the instance variables are different. Unlike class variables, instance variables are defined within methods. In the Shark class example below, name and age are instance variables: class Shark: def __init__(self, name, age): self.name = name self.age = age I'm sure Ruby has some means for you into defining constants dynamically, but I'm not going to bother looking that up because this feels, almost 100%, like something you don't really want to do. It seems like you want some way to associate a "name" to a class instance. That is exactly what Hash is for. people_names = ['John', 'Jane', 'Barbara', 'Bob'] people = people_names.each_with_object({}) do |name, ppl| ppl[name] = Person.new(name) end people['John'].name # => 'John' people['Jane'].name # => 'Jane' Why do I say what you're asking for is probably not what you want? Because use meta programming to dynamically create and dynamically read from local variables/constants/instance variables is just generally frowned upon in professional development. For your own projects, for experimentation, sure maybe. For any project as part of a team though, when you start using meta-programming features to dynamically add these values and reference them (maybe directly, maybe indirectly later) is all well and good but when you try and figure out what's going on you will almost never be able to figure out where these things are defined/coming from unless the array with the dynamic names is hard coded. And if it's hard-coded why can't you just build the constants/variables/targets directly in the code? That's significantly better than dynamically doing it. # this is a fake API to demonstrate # let's assume this is what you want PEOPLE_NAMES = ['John', 'Jane'] PEOPLE_NAMES.each do |name| const_def(name, Person.new) end get_person('Jane').do_something # maps to const_get('Jane').do_something get_person(PEOPLE_NAMES[0]).do_something John.do_something If you want the above, why can't you just do: John = Person.new Jane = Person.new John.do_something The latter is loads more clear, can still be dynamically looked up, but has a hardcoded definition that can easily be targeted when debugging. That's my recommendation and answer. I'm pretty sure you don't want to do what you're asking to do. Hash totally fits the needs you desire, it's used heavily for purposes like this and closely related to it, I recommend you try and make that work for your needs then try and figure how to solve the problem you're specifically looking to get an answer too. EDIT As a really fun add-on, you can do some really cool dynamic stuff with Hash here that doesn't lead to tons of confusion unless you happen to hide where the hash is coming from. But you could do something like: people = Hash.new { |h, k| h[k] = Person.new(k) } # right now, people contains no actual people people['John'].name # => 'John' # now people contains one Person instance This is cool for two reasons 1) You don't have to have a list to generate the hash, so if you get names after hash creation that's fine you can just add them by accessing that users name and 2) Being lazy, it will only use the memory you need. If you preload the hash with all four persons, and then access data from only two persons you wasted the space required for the unused 2 Person instances, so this let's you use only as much as you need and otherwise offers you all the same benefits. Understanding Class Members (The Java™ Tutorials > Learning the , In the case of the Bicycle class, the instance variables are cadence , gear , and speed For example, the following variable declaration defines a constant named PI Note: If a primitive type or a string is defined as a constant and the value is Define a public class called Account that i. has an instance variable called name of type String ii. has an instance variable called balance of type double ii. defines a constructor that takes two parameters used to set the instance variables name and balance Define a subclass of Account called InterestAccount that You can certainly do it, although as Brandon says it probably isn't a good idea. Here's how to do it: people_names.each { |name| eval("#{name} = Person.new")} eval takes a string passed as an argument and executes it as a line of code. So, you use each to do that once for each member of your array. You might want to google "eval" to see any number of articles about why it's evil. Many of these go off on metaprogramming ( eval is an example of metaprogramming) in general, and make some good points. I have a bit more moderate approach to metaprogramming than that ( attr_accessor, after all, is an example of metaprogramming, too, and people use it all the time), but you can certainly write some very tangled code using eval. Note also, as several posters have observed, that by capitalizing your strings you are defining them as constants. You can change a constant's value in Ruby, but you will get a warning every time you do so. Javanotes 8.1, Answers for Quiz on Chapter 5, That is, the class contains the source code that defines instance variables and public class Player { private String name; private int score; public String If I have the name in a string of one of the framework's core classes (such as "System.Collections.ArrayList"), what's the easiest way for me to create an instance of the appropriate class? In VB6 I would have simply used CreateObject, is there an equally simple way in VB.NET? Thanks,--(O)enone Javanotes 8.1, Section 5.1 -- Objects, Instance Methods, and , If an object is also a collection of variables and methods, how do We just left the word "static" out of the subroutine definitions! class UserData { static String name; static int age; }. As the name implies, public instance methods are methods available on class instances. class ClassWithPublicInstanceMethod { publicMethod() { return 'hello world' } } const instance = new ClassWithPublicInstanceMethod() console.log(instance.publicMethod()) // expected output: "hello worl d" Public instance methods are added to the class Object orientation, Classes do not need to have the same base name as their source file definitions but it is highly recommended in most Python isinstance() to check whether the object is an instance of the specified class type. isinstance() function to check instance with the String type, number type, dict type, list type.isinstance() with Python Class and inheritance Defining and using a class, If our attribute name is stored as a string value in a variable, we have to use the getattr function to retrieve the attribute value from an object: for key in ["a", "b",
http://thetopsites.net/article/58331441.shtml
CC-MAIN-2020-34
refinedweb
1,431
63.19
I am completely convinced that the patch you are using (which Ibelieve is the same as the one Andrew calls"tty-shutdown-race-fix.patch") is the problem. What happens is thatrelease_dev() in tty_io.c calls cancel_delayed_work(), which callsdel_timer_sync() without decrementing nr_queued for keventd_wq.When flush_scheduled_work() gets called it sleeps on the work_donewaitqueue. The only place work_done gets woken up is inrun_workqueue, and it only happens ifatomic_dec_and_test(&cwq->nr_queued) decrements nr_queued to 0.But after calling cancel_delayed_work(), that can never happen (wedeleted the timer that was going to add the work that we're waitingfor).It seems to me that the implementation of cancel_delayed_work() isnot quite right. We need to decrement nr_queued if we actuallystopped the work from being added to the workqueue.Andrew, I've never seen a reply from you about this, can you tell meif I'm missing something here?By the way, I assume that the process below is the one that's hung: bash D C04CDC68 4233453816 8524 1 8387 (L-TLB) Call Trace: [<c010cd75>] do_IRQ+0x235/0x370 [<c01394a5>] flush_workqueue+0x305/0x450 [<c010ac18>] common_interrupt+0x18/0x20 [<c011de30>] default_wake_function+0x0/0x20 [<c011de30>] default_wake_function+0x0/0x20 [<c0257a44>] release_dev+0x6a4/0x860 [<c01566ab>] zap_pmd_range+0x4b/0x70 [<c0258204>] tty_release+0x94/0x1b0 [<c016dd7c>] __fput+0xac/0x100 [<c0258170>] tty_release+0x0/0x1b0It would seem to be stuck in the flush_workqueue() called fromrelease_dev(), just as I would expect.Shawn, can you try the patch below instead of Andrew's ttyfix2? - Roland===== drivers/char/tty_io.c 1.72 vs edited =====--- 1.72/drivers/char/tty_io.c Thu Apr 3 10:20:22 2003+++ edited/drivers/char/tty_io.c Tue Apr 8 20:23:44 2003@@ -1286,8 +1286,15 @@ } /*- * Make sure that the tty's task queue isn't activated. + * Prevent flush_to_ldisc() from rescheduling the work for later. Then+ * kill any delayed work. */+ clear_bit(TTY_DONT_FLIP, &tty->flags);+ cancel_delayed_work(&tty->flip.work);++ /*+ * Wait for ->hangup_work and ->flip.work handlers to terminate+ */ flush_scheduled_work(); /* ===== include/linux/workqueue.h 1.4 vs edited =====--- 1.4/include/linux/workqueue.h Mon Nov 4 13:12:06 2002+++ edited/include/linux/workqueue.h Tue Apr 8 20:42:41 2003@@ -63,5 +63,12 @@ extern void init_workqueues(void); +/*+ * Kill off a pending schedule_delayed_work(). Note that the work callback+ * function may still be running on return from cancel_delayed_work(). Run+ * flush_scheduled_work() to wait on it.+ */+extern int cancel_delayed_work(struct work_struct *work);+ #endif ===== kernel/workqueue.c 1.6 vs edited =====--- 1.6/kernel/workqueue.c Tue Feb 11 14:57:54 2003+++ edited/kernel/workqueue.c Tue Apr 8 20:27:50 2003@@ -125,6 +125,24 @@ return ret; } +int cancel_delayed_work(struct work_struct *work) {+ struct cpu_workqueue_struct *cwq = work->wq_data;+ int ret;++ ret = del_timer_sync(&work->timer);+ if (ret) {+ /*+ * Wake up 'work done' waiters (flush) if we just+ * removed the last thing on the workqueue.+ */+ if (atomic_dec_and_test(&cwq->nr_queued))+ wake_up(&cwq->work_done);++ }++ return ret;+}+ static inline void run_workqueue(struct cpu_workqueue_struct *cwq) { unsigned long flags;@@ -378,5 +396,5 @@ EXPORT_SYMBOL(schedule_work); EXPORT_SYMBOL(schedule_delayed_work);+EXPORT_SYMBOL(cancel_delayed_work); EXPORT_SYMBOL(flush_scheduled_work);--To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2003/4/9/2
CC-MAIN-2015-06
refinedweb
518
58.58
I am looking for a way to round a floating point number up or down to the next integer based on a probability derived from the numbers after the decimal point. For example the floating number 6.1 can be rounded to 6 and to 7. The probability for beeing rounded to 7 is 0.1 and the probability to be rounded to 6 is 1-0.1. So if I run this rounding experiment infinite times, the average of all integer results should be 6.1 again. I don't know if there is a name for such a procedure and if there is already and implemented function in Python. Of course it'd be very nice if it is possible to round also to e.g. 2 decimal places the same way. Does that make sense? Any ideas? The probability you're looking for is x-int(x). To sample with this probability, do random.random() < x-int(x) import random import math import numpy as np def prob_round(x): sign = np.sign(x) x = abs(x) is_up = random.random() < x-int(x) round_func = math.ceil if is_up else math.floor return sign * round_func(x) x = 6.1 sum( prob_round(x) for i in range(100) ) / 100. => 6.12 EDIT: adding an optional prec argument: def prob_round(x, prec = 0): fixup = np.sign(x) * 10**prec x *= fixup is_up = random.random() < x-int(x) round_func = math.ceil if is_up else math.floor return round_func(x) / fixup x = 8.33333333 [ prob_round(x, prec = 2) for i in range(10) ] => [8.3399999999999999, 8.3300000000000001, 8.3399999999999999, 8.3300000000000001, 8.3300000000000001, 8.3300000000000001, 8.3300000000000001, 8.3300000000000001, 8.3399999999999999, 8.3399999999999999]
https://codedump.io/share/Bppnq02M681k/1/random-rounding-to-integer-in-python
CC-MAIN-2017-04
refinedweb
280
78.75
Knights on a chess board The power and beauty of Markov Chains. By Vamshi Jandhyala November 19, 2020 Problem A white knight and a black knight are situated on diagonally opposite corners of a $3 \times 3$ square. In turn, starting with White, they move randomly until (inevitably) Black captures White. What is the expected number of Black moves to achieve capture? Solution Key Observations - The complete state of the game is determined by the position of the two knights on the board. - The next state of the game only depends on the current state. - Multiple configurations(rotations, reflections) of the board can be collapsed into a single state. This is essentially a Markov Chain problem. Board States The diagram below illustrates all possible board states apart from the absorbing state State 1 is the initial state. State Transition Matrix The state transition diagram for the game markov chain is shown below State 5 (where the black knight captures the white knight) is the absorbing state of the markov chain. The transition matrix $\mathbf{Q}$ is given by $$ \mathbf{Q} = \begin{bmatrix} 0 & 0.5 & 0.5 & 0\ 0.5 & 0 & 0 & 0.5 \ 0.25 & 0 & 0 &0.5 \ 0 & 0.25 & 0.5 &0 \end{bmatrix} $$ Fundamental matrix and expectation For a Markov chain $\mathbf{P}$, the matrix $\mathbf{N} = (\mathbf{I} − \mathbf{Q})^{−1}$ is called the fundamental matrix for $\mathbf{P}$. Let $t_i$ be the expected number of steps before the chain is absorbed, given that the chain starts in state $s_i$, and let $\mathbf{t}$ be the column vector whose $i^{th}$ entry is $t_i$. Then $\mathbf{t} = \mathbf{Nc}$, where $\mathbf{c}$ is a column vector all of whose entries are $1$. We have $$ \begin{align*} \mathbf{Nc} &= (\mathbf{I - Q})^{-1}\mathbf{c} \ &= \begin{bmatrix} 1 & -0.5 & -0.5 & 0\ -0.5 & 1 & 0 & -0.5 \ -0.25 & 0 & 1 & -0.5 \ 0 & -0.25 & -0.5 & 1 \end{bmatrix} ^{-1} \begin{bmatrix} 1 \ 1 \ 1 \ 1 \end{bmatrix} = \begin{bmatrix} 8 \ 8 \ 6 \ 6 \end{bmatrix} \end{align*} $$ Therefore, the expected number of steps taken by the black knight to capture the white knight from the initial configuration is $\mathbf{8}$. Computational Verification from random import choice transitions = { (0,0):[(2,1),(1,2)], (0,1):[(2,0),(2,2)], (0,2):[(1,0),(2,1)], (1,0):[(0,2),(2,2)], (1,2):[(0,0),(2,0)], (2,0):[(0,1),(1,2)], (2,1):[(0,0),(0,2)], (2,2):[(1,0),(0,1)] } runs = 100000 tl = 0 for _ in range(runs): b, w = (0,0), (2,2) l = 0 while True: l += 1 w = choice(transitions[w]) b = choice(transitions[b]) if b == w: break tl += l print(tl/runs)
https://vamshij.com/blog/2020-11-19-knights-on-a-chessboard/
CC-MAIN-2022-21
refinedweb
463
65.01
Programmers We perform small, isolated experiments when we need more information. You’ve probably noticed by now that XP values concrete data over speculation. Whenever you’re faced with a question, don’t speculate about the answer—conduct an experiment! Figure out how you can use real data to make progress. That’s what spike solutions are for, too. A spike solution, or spike, is a technical investigation. It’s a small experiment to research the answer to a problem. For example, a programmer might not know whether Java throws an exception on arithmetic overflow. A quick 10-minute spike will answer the question: public class ArithmeticOverflowSpike { public static void main(String[] args) { try { int a = Integer.MAX_VALUE + 1; System.out.println("No exception: a = " + a); } catch (Throwable e) { System.out.println("Exception: " + e); } } } No exception: a = -2147483648 Although this example is written as a standalone program, small spikes such as this one can also be written inside your test framework. Although they don’t actually call your production code, the test framework provides a convenient way to quickly run the spike and report on the results. The best way to implement a spike is usually to create a small program or test that demonstrates the feature in question. You can read as many books and tutorials as you like, but it’s my experience that nothing helps me understand a problem more than writing working code. It’s ...
https://www.safaribooksonline.com/library/view/the-art-of/9780596527679/ch09s07.html
CC-MAIN-2016-50
refinedweb
239
56.55
Iterate works with firstobject, not with tagobject On 30/10/2014 at 08:58, xxxxxxxx wrote: Hi, I have a project which contains these methods: def GetNextObject(self, op) : if op == None: return None if op.GetDown() : return op.GetDown() while not op.GetNext() and op.GetUp() : op = op.GetUp() return op.GetNext() def IterateHierarchy(self, op) : if op is None: return count = 0 while op: count += 1 print op.GetName() op = self.GetNextObject(op) return count Inside Init I call IterateHierarchy; if I do it with the first object, he prints all my objects. However when I try to do it with the tagobject it returns None Objects. I get them by this: global firstobject firstobject = doc.GetFirstObject() global tagobject tagobject = tag.GetObject() Does anybody see the problem here? Thanks in advance for your awesome help! :D On 30/10/2014 at 16:22, xxxxxxxx wrote: Well, for one "tag" isn't a predefined variable. You'll need to find it using doc.GetActiveTag() In addition to that, the tag needs to be selected for it to be found. Also, for your method to print all of the objects in your scene, you need to select a tag on the very first object in the scene. This works for me: import c4d from c4d import gui #Welcome to the world of Python print op.GetName() op = GetNextObject(op) return count def main() : if (doc is None) or (not doc.IsAlive()) : return firstobject = doc.GetFirstObject() if (firstobject is None) or (not firstobject.IsAlive()) : return tag = doc.GetActiveTag() if (tag is None) or (not tag.IsAlive()) : return tagobject = tag.GetObject() IterateHierarchy(tagobject) if __name__=='__main__': main() Perhaps you want to find the first object in your scene from a tag? Try: first_object = tag.GetDocument().GetFirstObject()
https://plugincafe.maxon.net/topic/8269/10778_iterate-works-with-firstobject-not-with-tagobject
CC-MAIN-2020-45
refinedweb
294
70.19
This bug affects 1 person Bug Description Hi, Yes, pickle is not guaranteed to be cross-compatible between python versions, but it's so close !! ---------- Dump in python 2: import pickle, pytz, datetime with open("date.pickle", "wb") as fp: pickle. ---------- Load in python 3: import pickle with open("date.pickle", "rb") as fp: pickle.load(fp, encoding="bytes") # encoding="bytes" so that pickle can load old str # fails with # AttributeError: 'bytes' object has no attribute 'encode' # because pytz.zone calls 'ascii(zone)' for something that is already in bytes --------- pytz.ascii should not .encode 'bytes', that's it ! Thanks ! Stuart Bishop (stub) on 2016-10-26
https://bugs.launchpad.net/pytz/+bug/1631989
CC-MAIN-2017-51
refinedweb
107
70.7
Most consumers don't want to rely on blind faith to know that what they eat is GM-free. Belgian experts concluded that growing this GM oilseed rape would have negative impacts on biodiversity that could not be brought under control, and that guidelines for farmers to prevent contamination of non-GM crops are unworkable and difficult to monitor. Their advice followed the largest GM field scale trials to date (in the UK), which concluded that growing GM oilseed rape would be worse for wildlife than growing the conventional crop. Other UK studies have also shown that insects can carry the pollen of oilseed rape over many kilometres, indicating that once planted, GM pollen would contaminate non-GM crops. Such research underlines how immensely difficult, if not impossible, it would be to contain the cultivation of GM oilseed rape and protect non-genetically engineered farming. For consumers who want the right to choose clearly labelled non-GM products, crop contamination is a major issue. Germany-based Bayer CropScience had applied through Belgium for a Europe-wide licence to grow the GM oilseed rape. However, 22 other GM applications are being pushed for approval in EU by the European Commission. Ten of them include cultivation. We believe all these applications should now be rejected locally by the governments considering them. The news is not all good, however. While rejecting cultivation of GM oilseed rape, the Belgian Government approved the crop for import and processing in Europe. This part of the application will now be forwarded to other EU member states. Adrian Bebb, GMO. Protecting the environment by rejecting GMOs should be the first responsibility of every Government." Consumers are to some extent protected from GMOs as many food manufacturers refuse to allow GMOs in their products. Although most European consumers have made it clear they don't want GMOs in their food, they will need to keep on actively rejecting such products.
http://www.greenpeace.org/international/en/news/features/gm-oilseed-rape-setback-in-eur/
CC-MAIN-2014-15
refinedweb
321
52.8
« Playing with the new Validator API | Main | Celebrating OWL interoperability and spec quality ».. Filed by Dan Connolly on October 28, 2006 1:23 AM in HTML, Opinions and Editorial | Permalink | Comments (53) | TrackBacks (0) I think it's very brave to try and reinvent something that's got such a widespread adoption and so many flawed interpretations. Sure, HTML is starting to show some cracks and inefficiencies but that's mnostly becuase Ajax / Web2.0 / JavaScript and the competing DOM and event models of IE and Gecko are really starting to push the en envelope. Another incremental evolution (similar to 3.2 to 4.0) is due - to maybe provide some better/more efficient short-cuts that today still require a lot of common code, but also (IMO) it's important that the standards are tightened up around both the DOM, the event model, CSS, Behaviours etc as well as adding some much needed things (eg maxlength on textarea or more OS style combo boxes - rather than the simplistic select) to put the heavy lifting back into the browser and out of th developer space. Tim BL et al did an amazing job, and it's so cool to see that he's not just kicked back and said "I rock".. if he thinks it needs addressing.... maybe it's time for the Gecko and IE teams (now they've got their 2.0 and 7 releases out of the door) to sit up and listen... I, for one, would love to be able to contribute to this process... In his article, Tim BL cites HTML, xHTML and XHTML2. I'm curious. Does "xHTML" represent XHTML1/XHTML1.1? since they are a transistional bridge to XML? And. since XHTML1/XHTML1.1 are not noted specifically in his article, are these two markup languages to be obsoleted? My opinion is that is their quest to "evolve" their standards, the W3C is starting to become an obstacle for their adoption. It seems evident that it is impossible to make something a true standard (adopted by the wide majority), when you make it a moving target at the same time. So in my opinion the W3C should concentrate on making higher quality standards, rather than releasing poor standards often, and fixing things that are not really broken. "Release early, release often!" is good practice for (open source) developers, not for standard bodies! Oh no... This is not helpful. Whe are at a time when - all main browsers have finally reached an acceptable level of support for XHTML and CSS - most influential figures in the web world are pulling for XHTML and semantic markup - the XHTML and semantic markup litterature is there - in the medium/large corporate world, HTML is being obsoleted in favor of the processing-friendly XHTML - most (if not all) web software makers are on the XHTML bandwagon Why add yet another version to a spec that we know should have died long ago? This will not help. You should go the opposite direction. - Deprecate HTML. Completely. Get rid of the HTML validator too. - Provide on the W3C site a version of the XHTML 2.0 spec that mere mortals can read. That cryptic spec is probably the biggest obstacle to the adoption of XHTML: it scares to death anyone who looks at it. Its a Medusa. - Specs are not enough. You have to explain as clearly as possible the choices made in those specs. XHTML is much better than HTML, yes, but you have to tell people why, in a compelling manner. Not everyone is addicted to Molly's, Jeffery's, Eric's or Dave's blogs. - Lobby the makers of code-generating software. Make sure they think XHTML first. Same for browser vendors. I'm glad that various peoples opinions on this are not going un-noticed. One thing though is there anywhere I can read regarding what improvements are to be made to the validator? One thing that would be ideal would be to make it easier to download/compile and move to another location therefore being able to call it recursively to test an entire site off/on line. I suppose «Reinventing HTML» is a title open to many interpretations. Like with «reinventing the wheel»: there was no reason to reinvent it. We had it. And it was semantic too. Browser support is a huge hurdle here. I see a couple modes of attack: One, consider backwards compatibility through scripting. That is, if Internet Explorer 8 won't support the next generation of HTML, it should somehow be possible for a script to take a full-featured HTML document, process it, and make it work pretty well in common user agents. Google's ExplorerCanvas is an example of this strategy, sort of (albeit not with a W3C standard). Two, consider making standards that mesh with nonstandard extensions to HTML and the DOM -- where careful authors can write standards-compliant code that happens to work in nonstandard user agents. I don't know whether there's any point to basing a standard on IE's approach to embedding XML in HTML, but maybe there is. Standardizing XMLHTTP and XSLT processors (if there aren't already W3C standards) wouldn't do any harm. Three, add features that you know browser makers will pick up eventually. If it has to do with security and it's designed in consultation with Microsoft, it will probably wind up in the next update of Internet Explorer. Implementation difficulty, backwards compatibility, and value in the eyes of browser developers are the three big things that count here. What you're describing sounds exactly like WHATWG work. Why isn't this group mentioned? Is it a plan for some secretive merge of WHATWG with W3C or are you starting a new, similar effort? Oops, my mistake. Please ignore my previous comment. Are you going to start with a clear requirement? What problem are you trying to solve, and how will you know when you've solved it? The buck stops with the browser vendors. You can have all the standards in the world but if a main vendor with 90% market share decides to do their own thing, what can you do. Just when I thought I was as tonfused as it was possible to be.. :D Would it be presumptuous at all to make a suggestion re this latest development..? No, cool.. ;) If [Reinventing HTML] becomes something new, an at least somewhat clean slate that some major number of us will be encouraged to use as the reference of the Future, would you all please consider starting out right from the beginning regularly supplementing the latest [standard] with applicable (small) images or diagrams..? Am thinking of, say, the concept of nesting as an easy example.. There are those who could over and OVER read a recommendation for proper nesting and never ever grasp the concept but for whom one picture of the same would be worth the proverbial thousand words.. Am proffering this with thoughts of further accessibility (cognitive disabilities) and possibly saving just a tiny bit of email traffic hitting the multiple related lists.. In addition, the ease of use of something does play some significant part in the extent to which that something will be implemented.. Thanks in advance for considering the above in the spirit in which it was presented.. Looking forward to seeing what direction you all are up to next.. Always an adventure.. :) "Reinventing HTML" is a collection of correct statements which sum to something incorrect. What is wrong is what has been forgotten. What has been forgotten is that the incredible achievements of the W3C, of recognized historical importance, have always been on the political plane, not the technical. Consummate politicians, the W3C volunteers may have had an ideal in mind but the "art of the possible" constrained every effort and the practical results are worthy indeed. One could very well apply every cited criticism of practical HTML to the English language. My unhandsome native language was born of the compromise and illogic of daily intercourse -- and has continued so to this day. Those who yearn to speak a language beautiful in its logic should not speak English. The existence of software spellcheckers is condemnation enough! Yet English continues to find profitable application and so will HTML in the very same sense. Brett Merkey At present Google itself is mostly made with non-valid markup and does not seem to down-rate non-valid markup on indexed pages. Naturally as a result there is a general lack of attention to the format of a page by the very people who could have the most impact on the future of web (as they spend their every waking minute trying to boost their keyword ranking) and avoid the W3C rules. These posts attest well to this.. This is all well and fine BUT DOES THE w3c wish to promote this partnership --- this would lead to a whole new huge force of webmasters helping the w3c --- all that is needed is that a portion of the w3c would turn its attention to white hat SEO in tags --- and what better place than with the semantic web! Tim --- do let us know. AMB, GENEVA. I think new browsers should definitely check the syntax of XHTML, CSS and JavaScript (as some of them already do) documents. But the point is: "Good" old HTML should be shown in the browser as always. So we've got the needed downward compatibility. A new XHTML version should be treated in a different way: if there are (syntax) errors in the document, the page will not be shown, instead there is a error report. New versions of XHTML should have got some "cool", "kick-ass" features and possibilities, or whatever. The goal is to make the new version as popular as possible. Because it is definitely standard XHTML x.0 (CSS, JavaScript, ...) it should be much simpler for the browsers to render. That hopefully brings us better browser compatibility, what would be the smashing advantage over old non-standard and non-audited HTML. I think the growing Mozilla movement shows that there is not only one browser, even (X)HTML beginners should be able to realize that fact. If they also realize the advantages of XHTML we've won. I just learned to love XHTML, an now someone wants to reanimate HTML? I don't think that this is a good idea, I think XHTML in conjunction with CSS is a good idea, and it's easy to use and to work with! Please don't bring a nother Markup - language into the game, it would be much better to speed up the XHTML - development! I Thin it's not a good idea to continue the development of HTML only because some developers are too lazy to use XHTML. XHTML is a really good ML, and every effort should be made to continue development on XHTML. You're probably SOL until sites like myspace.com start accomodating standards. As long as they allow users (non-developers) to customize their own page with a smorgasborg or poorly crafted code, the poorly crafted code will keep getting written. I wish you the best of luck, though, and look forward to your solutions. if you go to alexa.com, see what the top 10 web sites in the US are, and look at the source of their home pages, it is all plain-old" html - no sign of xhtml, xforms, etc. Perhaps there needs to be some explaining done as to why 98% of the web developers/users out there should care about more standards developments at this point? Everyone is tunring to AJAX to do their web apps, and unless it can be explained clearly and compellingly why anyone would want to switch to newer standards, no one will. i like HTML, and i hope it could be better Tim, thank you. Not for HTML vs. XHTML, but for the "listening to commenters" part. Wait when was noticed that some people akin to WhatWG has plans to add XML applications into next HTML5 tag soup, breaking today backward compatibility with hundred of tools. For example your today working documents containing a XML tag <none> would be invalid for a HTML5 browser, whereas new HTML5 tools would generate <none> which would generate error when processes by a XML parser. Here's the bit I find inescapable: The attempt to get the world to switch to XML, including quotes around attribute values and slashes in empty tags and namespaces all at once didn't work. The large HTML-generating public did not move, largely because the browsers didn't complain. I've read Tim's blog, and I don't see how he can get around that. Myself, I use both FF and IE browsers. Routinely, web sites break FF, sometimes both. Unless Tim's XML body can compel browsers to complain (how?) I really don't see that it will do anything differently. Some of the inertia in the html standard is incredible. I taxed one site developer for producing an all-Flash shop window site, which is almost unusuable (can't link to pages, can't cut, can't paste - not even phone numbers!) and he's utterly unrepentant. "This way, it looks the same to everybody," he said. For example of inertia: my browser routinely traps popup windows. So, these days, do most. What is going on? Why are site designers writing popup code in a world where nobody can see the stuff? I suspect the answer is that people are using automated CMS tools like the FCKEditor. That allows you to generate a new window with several options. One is * target="_blank" * another is popup. The one is "deprecated" and the other futile. What will stop people using the built-in CMS tools? As long as people are prepared to ignore browser-objection on the scale that you get for popups, what hope is there to persuade them to start using new features? and, more to the point, to stop using old ones? I have to agree with Nicholas. I went through all the trouble to teach myself about proper HTML/SGML and now XHTML/XML and everything involved to make sure the websites are done the way they should be. I also agree with the point that from a version 1 to a version 2 the specification suddenly seems to quadruple and stack feature upon useless feature which only serves a very minor part of the community. People are moving to XML. It's just taking a while. There will always be people who don't want to change anything that works. Nothing will change that. There will be web pages in HTML 1.0 forever. In the 1970s, there were programs running under an IBM1400 emulator, itself running under an IBM7094 emulator, on IBM370s. The one fatal mistake would be to let this stop the rest of us progressing to XML amd CSS. This whole proposal is broken. Sorry a typo in my previous post. I mean difference between <none> and <none/> P.S: These links can offer a idea of that WhatWG and Mozilla guys want to do with next HTML. A Brazilian-Portuguese translated version for this article can be found at: I think that the concept re-inventing HTML is kind of like closing the dooe after the horse has bolted, as the saying goes. Although Tim and all the W3C staff have the best intentions in mind, we as a community need to educate designers on the existing standards before creating more rules to be broken. It all sounds pretty reasonable. But does "this one will be chartered to do incremental improvements to HTML" mean that 4.01 was NOT the final html spec? Stefan Mackovik said: "I just learned to love XHTML, an now someone wants to reanimate HTML?" Not taking any stance on that one, but... "someone"? You DO know who wrote this post, right? je parle en français et je ne capte rien de tous ça c grave traduiser mec traduis reactualise vieux bonjourj a tous et speak french the boss norbert Suggest to leave HTML as is Just as JavaScript have reached his limits maybe HTML has too. How about modularizing SVG and making it the basement for the new WWW 2D Babel? HTML never made on compliance due to many causes, but one of them being his inherent "display fussiness". SVG by design has less of this problem. Do someone plan to translate the post of Tim into French, or can I do it? (Cf last comment.) Very good idea to improve the human-readibility of the validator. May this include translations of the messages? I'll be very happy to participate. Regarding the matter of HTML, I use XHTML for my private documents, so as to see syntax errors in my navigator, but I can't on the web, since I can't deny access to people who have an obsolete browser, grumble. I do not really understand the need of three (x)HTML. HTML 4.01 is a very good step, XHTML 2 make me very enthusiastic, but XHTML 1.0 and 1.1 are misused (you may know Serving XHTML as text/html considered harmful). What I like most with XML with namespaces is that you do not have to reinvent the wheel each time you need it. At present with HTML you may have one , one , and the same in your RDF file — example of problems caused by a transitional step. But how can we switch when the most part of people suffer from an old browser? However, thank you for the Web, Tim. Really great. Tim's content has mostly been translated in French already : Réinventer HTML I also agree with Nicola. The real problem in any case is browser vendors not yet fully implementing existing specs. What makes you think they will implement future ones? I actually think the W3C should invest the time and resources into generating a rendering engine rather than creating yet another spec. If I write the most perfect XHTML and beautiful CSS and error free accessible Javascript I want this to work on all platforms, not just on those who implement the part of the spec I am using. I realise this a contentious issue, but I honestly do not see the point in having so many different rendering engines. Everybody is simply reinventing the wheel. Let the browser vendors concentrate on what they should have been concentrating all along: browser usability, not markup. There was a period of about 5 years where almost nothing happened in browser development. Now we've had some pretty major developments, but are we going to see another period of stagnation as browser vendors start implementing yet another version of HTML? I'm worried about our conception of the future. I am not a "tekky" (I'm afraid I know of no other term!) but I am extremely interested in ICT, in communication, language, meaning and society. The web is central to all of these things now. Surely listening is only possible if there already exists some initial premise and approach to that premise. If this is not the case then only hearing will result. Babies are hard wired with the basics to build semantic structures from the noise around them but adults shouldn't rely on this inate ability in their approach to communication. It seems to me that there is an apparent absence of fundamental principles and values at the heart of the evolution of the web and of it's current "management". While I appreciate the strenuous efforts being made to enforce conformity, these have only resulted in them being set in opposition to what people are doing or wanting on the ground, either as users, developers, publishers, providers etc. Enforcement is only really possible with overwhelming consensus. Without a value system that goes beyond the isolationist mentality of "tekkies" ("it's the users fault, they just don't understand us"), and which embraces, learns from and respects the work done over centuries in the field of semantics, semiotics, etc the present fleeting opportiunity to make the web a source of inspiration comparable to say the great library of Alexandria, will simply be lost. Well, one part of my message is unsense so At present with HTML you may have one meta name="author", one dc.name="author", and the same in your RDF file — example of problems caused by a transitional step. A new standard is great. It can mend old problems and add new longed for functionality. However, no matter how well made this new standard is, if the web browsers people use don't support it fully(the problem we have today), then we will still have to do things the old way, pushing the real problem ahead of us. What I spend probably more than half of my time making web sites with is browser compatibility. And what my clients complain about most of the time is the very same. What we need is ONE ENGINE with FULL SUPPORT of the standards, USED BY ALL of the browsers out there so that we actually have a stable ground to build our sites and web applications on. There can't be a hundred engines interpreting the standards in a hundred different ways. The world wide web should be accessible to any user, any platform on any device. Without that no gain will come from making a new standard, in my opinion. So basically, if a new standard is to be made, it has to be available with full support to existing browsers in some way. Maybe one browser engine is an impossible dream, but then there should at least be a browser engine validator service that can let the public know what browsers are good to use and which ones are not. Robin Massart wrote: I actually think the W3C should invest the time and resources into generating a rendering engine rather than creating yet another spec. I realise this a contentious issue, but I honestly do not see the point in having so many different rendering engines. Everybody is simply reinventing the wheel. Let the browser vendors concentrate on what they should have been concentrating all along: browser usability, not markup. Eric Johansson wrote: What we need is ONE ENGINE with FULL SUPPORT of the standards, USED BY ALL of the browsers out there There can't be a hundred engines interpreting the standards in a hundred different ways. The world wide web should be accessible to any user, any platform on any device. Without that no gain will come from making a new standard, in my opinion. Fernando Franco asked Tim Berners-Lee about the possibility of W3C making a browser (or at least a rendering engine). Here is the result: Meantime, a few questions have been asked: The problem is structural. W3C will fix nothing. Nor now, nor in the next ten years. The problem is structural. I suggest you, reasonable people, to stop posting here. This message will be ignored, too. The real problem of the W3C is a frightening lack of ability to explain their intentions clearly. Their Recommendations are written in a nearly impenetrable style, and the overarching map to their interconnectedness is nowhere to be found on their site. This re-invention of HTML that is porposed is a step backward in the same vein as CSS2., which has recently, bafflingly been demoted from a Candidate Recommendation to a Working Draft. I predict the same fate for a revitalized HTML. The lack of full adoption of XHTML is not due to any inherent problems with the difference between the two languages, it's due to the W3C's failure to explain clearly and promote effectively what the heck it was there for. The same goes for their modularizing efforts and their products. Many reputable sources are still completely unaware of the existence of XHTML 1.1. Extracting a view of their Master Plan for the Web from their own published material is close to an exercise in futility. Parallel development of HTML and XHTML will only further this state of affairs. Of course, if new work on HTML and XHTML proceeds at the pace of CSS 2.1 and the CSS3 modules, we won't have to deal with the fallout from this decision for nearly another decade. @Scott: "This re-invention of HTML that is porposed is a step backward in the same vein as CSS2., which has recently, bafflingly been demoted from a Candidate Recommendation to a Working Draft." Moving a document from WD to Last Call, Last Call to CR, etc is made accordingly to the Process Document. The Process Document has been written incrementally. When a document is going from CR to Last Call, it doesn't mean it is bad. It just mean that significant changes have been made in the specification. CSS WG which is composed from Browser Vendors mainly want to create a CSS 2.1 specification which really follows what is implemented out there. So they impose on themselves very strict rules to not have reproaches of the type "It is in the spec, but not implemented". A specification can jump from one stage A to another stage B, if the all entrance criterias of stage B are met. It means for example you can jump from WD to CR again. It is better that the vendors creating the products we are using agree before releasing a specification. I find it very interesting that we say people will never close tags or use quotes in attributes, but we find that people who write JavaScript always close brackets and always use quotes in strings. Well, I think most programmers consider HTML as "formatting", just the few "tags" you use to set the presentation of what your server script language outputed. Regarding firms, the web things may only be a part of the computer service, which is only a part of the company, not a priority. Hey guys, you can't make a website within two week-ends anymore. SGML-based user agents dealt with tag soup, XML doesn't permit that. That's not future, that's here. Compliance matters. Wok, HTML-lover (poor French student reading RFCs and specs for hours ^^') Hello, Marc Sparks here. I too agree it is a daunting task to re-invent something. But, it is a task that has to be undertaken to evolve. Great Job! - Marc Sparks. I have been forced (though I happily complied) into the world of xhtml in 2003. I am happy with the standard. I am excited about upcoming standards. Though I seem to be alone most of the time for this, I am excited about the XHTML2 specification/standard. I hate the wait. It is like waiting for the newest version of your latest software. I am excited about the l, column, section and header elements. I think that the expanded use of the object tag will help. I think this will be a great thing. I would like to see it soon. That is my biggest complaint about XHTML2: It's not here. Browsers are not going to forget how to parse XHTML1/1.1 any time soon. XHTML3.2 and 2.0 are still alive and kicking. What is hindering our adoption? Thanks for the hard work, and your consideration of our thoughts, even mine. This is just great. I'm still having a hard time putting quotes around strings, putting slashes in empty elements, and putting "xml:", in front of "lang". I don't even want to think about learning XForms. ZOMG, new tags everywhere! What were they thinking?! I, for one, will welcome HTML 4.5 very gladly. Thanks Tim! Thanks Microsoft! What about CSS 1.5, by the way? I mean, there was too many changes, let's face it. IE does not even really support it, after like 5 years of common use of CSS 2 (and it being defined for more than nine years). With Microsoft budget, and expertise, if they cannot do it, who can, right? (and I'm not even talking about CSS 3... round corners, ZOMG! We'll need at least three to four steps, between CSS 2, and CSS 3...). ... What a laugh. Do you feel the web developer/master job is still too easy? I mean, "let's make it a bit harder, so we won't lose our job because everyone would otherwise be able to do it"... is this it? and all this is to exchange data... this is so screwed up... this is so much a waste of energy, which could be used for so many, and so far better things... well, this is what makes today society... this is no worse than in any other domain... time to wake up people, yeah? Simplicity is the key to a better world. In computing, we should make usability, accessibility, and universality, as prerequisites, and throw all the rest. It souldn't take much time, and we would have to do it only once. Ever. (Oh noes...! the comments are moderated...! Well, writing it is enough to let off some steam... and at least one other individual might read it... It's not as if I was not used to it... I just hope I will be able to achieve my projects, before it's too late... cuddle with one of his imaginary girlfriend) I am totally sick of companies making existing technology obsolete, usually for the purpose of making everybody spend more for the replacement. Examples: Microsoft forcing people to upgrade operating systems every three years or so. For long-term scientific studies, OPERATING SYSTEMS SHOULD BE UNCHANGING CONSTANTS, not cash cows for monopoly corporations. The forced replacement of NTSC TV with HDTV, so we can "beat Japan". They just replaced VCR with DVD, and now they put out Blu-Ray, a new system that requires replacing the player again. The forced change from MS-DOS to Windows made some scientific research projects impossible. The internal timing of Windows precludes accurate control over the precise timing of computer-controlled experiments. Windows proponents claim that timestamps can cure this, but you can't give the organism under study a timestamp telling it that the stimulus should have occurred 22 ms earlier. The forced replacement of line printers with Postscript printers, making it impossible to keep legacy systems working. All of these changes causes loss of access to old materials, and can cause scientific research projects to be terminated early due to the lack of suitable replacement equipment. Any forced change to XHTML is going to cost a lot of people a lot of money recoding old documents. David: You are not alone. There are people who work on XHTML 2, and there are other like you and me that think the new elements are needed. However, I will always need to make an HTML + CSS 1 + JS (because HTML 4 is so poorly rendered nowadays, just think of quotations) alternate version since I do not want to say to old browsers users that they are morons and must get a modern browser. Even these browser make little use of the rich information provided by my markup. Supporting "modern" standards is much more than displaying rounded corners. Anonymous Coward: I do not believe that W3C's aim is to make things harder. If you don't need XForms, don't use them. If you need them, they exist. Don't you believe that standardization (as a pre-requisite fot interoperability) is a good thing? You said "all this is to exchange data"; I think communication and preservation of culture matter. Larry: Who said all existing HTML documents have to be turned to XHTML? Older specs are still here, and there are many software that can deal with all kinds of HTML and with tag soup. The W3C's strategy is to improve existing things, not to force you to switch with flashy useless features. (QA-blog people: I have an OpenID yet but the identification seems to work only with Typekey. Don't you agree that the text area is small, and preview useful? And "some HTML is okay" is not helpful to me, but at least it is not as bad as "you can use HTML for style" ;) But that are details, thanks for letting us comment.) My pages are all done in HTML and they work. My boss has put an incredible amount of time into making his pages totally XHTML compliant, and they are barely functional. We must lose customers all the time because of the implementation. This is definitely NOT the way to go! We finally have: 1. Browsers reaching an acceptable level of XHTML compatibility. You should continue working on the XHTML 2 specifications. Major sites are using XHTML 1.0 Transitional. We are at a point where people are used to putting the transitional doctype in their pages. XHTML will clean up the web. But if parsed as application/xhtml+xml, pages will break. We need to tell content provides to provide code snippets that don't make pages break. XHTML will succeed. There is no need for HTML anymore. As a [redacted] Website developer, this changing of language by browser, technologies, then rewriting old technologies is silly. We need a standardization of web programming. One language, one manual, and for it to work on EVERY version of EVERY browser. Incredibily frustrating. [Website URI redacted] took me 13 hours to build. But it took me an additional 100 hours to make it work perfectly on other browsers/versions/OS. Crazy. What is the point? I am still unable to envisage that i must convert my site [redacted] to HTML5 or not ! I am not a beginner buh i am scared if it break downs the blog.Using shiv js or modernizr is good ? for IE6 and IE7 ? Anyone gimme a polite comment !. Etan Wexler # 2006-10-28 Is that the...? It feels like... Hold on... Yup: Welcome to Web 3.2, everybody.
http://www.w3.org/QA/2006/10/reinventing_html_discuss.html
CC-MAIN-2013-20
refinedweb
5,713
72.97
automating or running a process back Hi everyone I would like to automate sending SMS with an application i am writting but i don't how i to do it. My application must be connected to a server from where it get informations to send via SMS. I am wondering how to create for example a class that inherit QMainWindow and run a process that will check the status of the connection with the server, get information from the server and and send them via mail or SMS every 5 minutes. I resume the fonctioning : - Create a QMainWindow object - Connect to the server and a SMS modem - Check the status of the connection - Send commands and Receive informations - Send the information via SMS - And update information sent status @Network1618033 For networking start here: You can take a look at examples provided with Qt. @jsulm thank for your answer. i forgot something. I'm using QtTelnet (Github) class to establish connection between my application and the server. That works fine. Now i'm looking to check the status and send my commands, receive answer(informations) and send them every 5 minutes. @Network1618033 said in automating or running a process back: QtTelnet I never used it and I'm not sure why you use insecure Telnet to connect to the server. But QtTelnet has documentation. @jsulm Telnet was the solution my teacher suggest me but i am at your disposal for any other solution that can be secured and easy :) . Otherwise I think you have not understand my problem. It is the automating my problem. Should i use a loop (if it is possible) for example or there is an design pattern that permit me run a code that will check my connection state, communicate with my server and send the SMS. - Sunfluxgames Once the server is setup and listening on the sms port grab the datastream from a Qbytearray. Check the first two bytes in the data stream this will be your Opcode or Packetheader.. qbytearray recvbuff; //get the first 2 bytes in the packet //now handling those two bytes or qstring or std:: message quint16 opcode; switch(opcode) { case ErrorConnection : cout << 'message'; // break; // exits the switch case LoginSuccessful : cout << 'messge'; break; case BadLogin : cout << 'message'; break; } Check the status of the connection - Should be a event handler for this to check the State and return it. Send commands and Receive informations - Send function that sends it to the client or server. Recv side see code. Send the information via SMS - Send it from the server with a send method. And update information sent status - Create a signal and slot with a timer and a function that sends it base of time. Could try QtHttp and do it over http or Qtcp This post is deleted! @Sunfluxgames Thanks i'm going try what you explaned. Someone talk me also about Qthread that can permit me run process back. Is it a good idea to ? - Sunfluxgames (windows or linux)???? Are you automating the client and server or just server. If this is so I would create a expect script batch file to run a client. Server wise.. Main.cpp #include <QCoreApplication> #include "mytcpserver.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // create MyTcpServer // MyTcpServer constructor will create QTcpServer MyTcpServer server; return a.exec(); } mytcpserver.h: /#ifndef MYTCPSERVER_H #define MYTCPSERVER_H #include <QObject> #include <QTcpSocket> #include <QTcpServer> #include <QDebug> class MyTcpServer : public QObject { Q_OBJECT public: explicit MyTcpServer(QObject *parent = 0); signals: public slots: void newConnection(); private: QTcpServer *server; }; #endif // MYTCPSERVER_H mytcpserver.cpp: /#include "mytcpserver.h" MyTcpServer::MyTcpServer(QObject *parent) : QObject(parent) { server = new QTcpServer(this); // whenever a user connects, it will emit signal connect(server, SIGNAL(newConnection()), this, SLOT(newConnection())); unsigned int port = 2222 //sms port if(!server->listen(QHostAddress::Any, port)) { //"Server could not start"; } else { //"Server started!"; } } void MyTcpServer::newConnection() { // need to grab the socket QTcpSocket *socket = server->nextPendingConnection(); QByteArray recvbuff; while(!recvbuff.contains('\n')) { socket->waitForReadyRead(); recvbuff += socket->readAll(); } //A function to process client mesasge processTeleNetMessage(message); } void MyTcpServer::processTeleNetMessage(Qstring message) { //use a case system to do login process or Qstring Compare // send automated message read from a text file or just hardcode the message here. socket->write("eat a dick\r\n"); socket->flush(); socket->waitForBytesWritten(3000); /// when all done etc.. // disconnects client... socket->close(); } Now if your doing this all in one application then yea you could use a Qthread to create events that loop thru all this processing. Really up to you and how you want to build this application. @Network1618033 said in automating or running a process back: Otherwise I think you have not understand my problem That's true as your description is unclear. Please do not use QThread until you really know you really need them. Qt networking classes are asynchronous, so there is usually no need for threads. To me it is not really clear what your question/problem actually is. "Connect to the server and a SMS modem" - what modem is it and how do you connect to it? "Check the status of the connection" - again: what modem is it? How do you access it? "Send commands and Receive informations" - what commands? What information? Send/receive to/from where (modem)? "Send the information via SMS" - depends on the way you access the modem. "And update information sent status" - update where? This post is deleted! OK i'm going explan clearly !. I have a BSC(Base Station Controller) that permit to manage failure on GSM equipements(BTS - Base Tranceiver Station - , Links , TRX) connected to it. Informations about Failures can be get from the BSC by sending some commands (for example "ls" on ubuntu that return the list of directories and files existing in the current directory). As the supervision Office is far from the BSC we can use telnet protocol to connect to it in order to send commands we want. In order to warn technicians of some possible failures i decided to automate "sending command to the server in order to receive the list of failures and send these failures via SMS" . I judged that if i want to send SMS with my application, a GSM modem is required. For this I thought that my application should work in the following way : - It must have a main window that show the current failures and their state (Sent or not) Behind this main window a process must execute the following task : When starting , the application should attempt to connect to the different equipments (BSC, GSM modem). If the connections failed the application should wait for them succeed or until the someone close the application. If the connections succeeded the application should start sending commands every 5 minutes for examples in order to list failures and send them via SMS. Before every sending actions (sending commands or messages) the application must check the state of connection to the equipment in order to stuck in waiting and show the in main windows that there is a problem to connect to an equipment. After sending SMS the application must update the state of failure sent I expect i have been more clear now !. Please excuse me for my spelling mistakes or grammatical error; I do not speak fluent English.
https://forum.qt.io/topic/81728/automating-or-running-a-process-back
CC-MAIN-2018-43
refinedweb
1,206
61.67
what i am trying to do here is ask user for an ip address to ping then an ending ip address. so if they want to test a c class all they have to do is run the program and type in starting ip then ending ip. Next step will be saving result to a file. But that will come later. Can someone tell me how to get this working. Arrays are kicking my you know what. I must have read 10 tutorials on arrays. I get the basics, but after that I am lost. it compiles with some errors. it does ask for starting and ending ip address. put it will not ping. i remember to use the strcat for the ping. i wrote a program to ping just one ip and it works great. thanks for the help with that one. code: . #include <stdio.h> #include <stdlib.h> #include <string.h> void main() { char startip[20]; char endip[20]; char pingtest[100] = "ping "; int i; printf("starting ip: "); scanf("%s", &startip); printf("ending ip: "); scanf("%s", &endip); for (i = &startip; i <= &endip; i++) strcat(pingtest,i); system(pingtest); return 0; } .
http://cboard.cprogramming.com/c-programming/42240-array-user-input.html
CC-MAIN-2015-11
refinedweb
192
86.2
Parent Directory | Revision Log Avoid reserved names for functions and variables, bug 516092. elibtoolize: Allow undefined symbols on AIX, needed by and work fine with module libs. namespace ECLASSDIR_LOCAL incase some other eclass tries to use the same var elibtoolize: accept explicit dir args on command line #496320 by Arfrever Frehtes Taifersar Arahesis Remove warning for uclibc if patching fails, bug #492640 libtool.eclass elibtoolize(): Besides ltmain.sh, explicitly locate configure to apply patches rather than guessing based on where ltmain.sh was found. use find to get file permissions instead of chmod --reference which is not portable, bug #468952 do not try to cp/patch/chmod the file if it does not exist #468852 by Samuli Suominen apply fix from upstream to use ${CHOST}-nm by default #462976 by Agostino Sarubbo make sure we save/restore chmod bits in case `patch` is broken and does not do it for us Remove redundant DESCRIPTION variable settings. elt-patches: add Solaris no de-deplication patch to fix built C++ objects from aborting when an exception is thrown also apply sol2-conf patchset Add ELT patch for Solaris x64 libtool problem where the linker is set to 'ld_sol2' elibtoolize: make sure header is included in logs too and not just the sub messages which rely on the context #395489 by Martin von Gagern avoid multiple inclusions when possible to speed caching up allow overlays to specify eclass overrides without breaking libtools lookup of local patches #389009 add a --force flag to elibtoolize so that eautoreconf can make sure it runs even in face of poor interactions with earlier ebuilds/eclasses code #232820 clean up patch applying a bit, and add support for @GENTOO_LIBDIR@ replacements in patches Be compatible with bash3 as well. Use a safer syntax for libtool.eclass (bug #370983). Add a gold-specific patch when gold is used as linker, as only libtool 2.2.7 and later actually report it properly. Check two parents directories for configure as sometimes it would otherwise fail (libarchive), and make the debug log a bit more useful by appending rather than replacing and adding the name of the patch/file it gets tested on. clean up the elcass a bit -- drop dead code, add documentation, etc... Change ELT-patches for AIX to use import files as soname-emulator (bug#213277). This requires switching libtool to force -no-undefined behaviour on AIX. Additionally, get_libname() now does return .so and versions like Linux. change bug notice to report a bug rather than annoy specific people drop spurious arg to popd #314493 rewrite ELT_walk_patches to handle path name as well as locale issues pointed out by Michał Górny #314493 aixrtl and hpux-conf _need_ to apply in a loop, mint-conf does not, (loop dropped in) Activate Prefix ELT-patches when and where necessary, acked by base-system, bug #301190. start an elibtoolize cross category #262042 by Sven Rebhan. Replace touch with bash redirection, so that it doesn't depend on coreutils. It doesn't have to. Restore the ltmain dir as the issue affecting BSD (-pthread) vs Linux (-lpthread) has been fixed Drop the ltmain patch as that breaks KDE on linux apparently. Sucks for BSD eh?, #192495 Apply install-sh patches Add a patch for ltmain.sh-1.5 so that KDE ebuilds link correctly on FreeBSD, #182214 depreciated -> deprecated. bug #180352 declare maintainer and cleanup a little Avoid QA warnings about ppc-macos not in USE by using CHOST like fbsd does. Remove wrong call to glibtoolize on darwin. Remove references to kde-fastinstall patch. Fix bash comment, bug #131649. Don't apply kde-fast-install for now. Add patch to fix kde's fast-install support in libtool, to fix problems reported by truedfx and others. Add code to support applying fbsd-ltconf patch for older libtools. Change $PORTDIR/eclass/ to $ECLASSDIR/ Don't trust the version reported in ltmain.sh to match patches, especially new versions of libtool, patched by distributions, might require newer versions to apply. Check also for configure in the previous directory when using aux directory for libtool files. Do not apply the portage patch if already applied. Add comment to contact us if portage patch fails. Misc cleanups for libtool.eclass. Add updates for max_cmd_len patches. *** empty log message *** Check if the freebsd patch was already applied when it fails to apply. Update elibtoolize to apply darwin patches. Move version retrieve stuff to ELT_libtool_version(). Do not warn on relink patch for libtool < 1.4.0. Make grep tests more consistent. Quoting/style fixes. Make --no-uclibc work again. Added elibtoolize patch for Gentoo/FreeBSD, to use linux-style link versioning. Apply whitespace check from repoman to eclasses. Merge uclibctoolize() stuff with elibtoolize(), and add required patches to make elibtoolize not bork on portage patch failing. Do not run elibtoolize again if already run. The check for no patches applied was in the wrong for loop. Some misc cleanups, and do not warn if portage patch seems to be applied. QA: Apply whitespace checks from repoman to eclasses. Remove ECLASS= and INHERITED= which haven't been necessary for a long time now Remove ECLASS= and INHERITED= which haven't been necessary for a long time now dont run libtoolize anymore Add ltmain.sh version to error if we abort on portage patch. Do not run libtoolize if portage patch already applied. Fixups for bug #83486. Try to match patches more according to libtool version, bug #83486 style updates only make the error failure scary fur uclibc users and add a --no-uclibc in case we already took care of uclibc mmm slightly less ugly bypass allow uclibctoolize to be bypassed '...' -> ' ...' Added darwintoolize. This closes bug #65272. dont try to patch ltconfig if size == 0 bytes #65331 eliminate libtool dependency to address bug 65209 ltconfig-1.4 seems to be compatible with ltconfig-1.3 and uclibctoolize forgot to add the extra search param in uclibctoolize also patch ltconfig files uclibctoolize to fix libtool code found in configure scripts dont change back to $S, change to where we started update the copyright info whitespace cleanup Apply patch from bug #25013 to replace calls to newdepend and newrdepend with variable setting (DEPEND=, RDEPEND=). Add max_cmd_len patch Mostly complete rewrite in effort to make it easier to maintain. Add all the patches temporary in ELT-patches, until I can get a better place that do not need a tarball or such to download. Add patch for libtool-1.4.3 and autoconf-2.13 that cannot find sed unfix earlier fixes If description is set... don't overwrite it... Fixes to everything but ASPELL and KDE-SOURCE header fixes fix if ltmain.sh in CONFIG dir only depend on libtool if not in bootstrap added note about econf and einstall Header updates/cleanups Header updates/cleanups tab fixes small fixor ditto $S fixes libtool reverse deps patch more fixes portage patch updates small fixes fixes small fixes small enhancements enhancements small fixes add libtool.eclass This form allows you to request diffs between any two revisions of this file. For each of the two "sides" of the diff, select a symbolic revision name using the selection box, or choose 'Use Text Field' and enter a numeric revision.
https://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo-x86/eclass/libtool.eclass?view=log&r1=1.84
CC-MAIN-2015-32
refinedweb
1,206
63.9
#include <mudlib.h> #include <ansi.h> #pragma strong_types inherit ROOM; void reset (int arg) { ::reset (arg); if (!present("soldier")) { place_objects("/players/orbital/projects/wiki/amob.c",2); tell_room(environment(this_player()),"Two guards arrive and take up station patrolling the area.\n"); }"); if (present("soldier")) return notify_fail ("The guards seem to be blocking the way!\n"); write ("You pull the lever. You feel healthier.\n"); say (sprintf ("%s pulls the lever. %s looks healthier.\n", capitalize (this_player ()->query_real_name ()), capitalize (this_player ()->query_pronoun ()))); this_player ()->heal_self (50); return 1; } Yet again, we've built upon the basic room. We have created some guards to block the use of the lever. See the line by line description here.
http://dune.servint.net/coding:mobroom
CC-MAIN-2018-34
refinedweb
113
54.39
NAME¶ FBB::Cidr - Compares IP4 addresses to CIDR specifications SYNOPSIS¶ #include <bobcat/cidr> Linking option: -lbobcat DESCRIPTION¶ Objects of the class Cidr can be used for testing whether IP4 Internet addresses belong to address ranges defined by Classless Inter-Domain Routing (CIDR) address block specifications. CIDR blocks are specified as a.b.c.d/m where a.b.c.d are the four octets of a dotted decimal IP4 address specification (e.g., 129.125.14.80) and m is a mask-size (ranging from 0 to 32) defining the number of most significant bits to remain as-is. The CIDR specification 129.125.14.80/16 defines a class B network, with addresses ranging from 129.125.0.0 to 129.125.255.255. The mask size does not have to be a multiple of 8. E.g., when specifying 129.125.14.80/5 only the most significant 5 bits of the first octed are fixed, resulting in an address range ranging from 128.0.0.0 to 135.255.255.255. CIDR specifications passed to a Cidr object must be of the form a.b.c.d or a.b.c.d/m. If the mask is not specified a mask-size of 32 is used, effectively defining an address range of only one address. Mask values of 0 are ignored. Mask values of 0 are ignored by Cidr objects. When specifying CIDRs on a stream, empty lines and comment lines (having a hash-character (#) as their first non-blank character) are ignored. Non-empty lines must start with a CIDR specification, and the Cidr object will ignore all information on a line trailing a CIDR specification. NAMESPACE¶ FBB All constructors, members, operators and manipulators, mentioned in this man-page, are defined in the namespace FBB. INHERITS FROM¶ - CONSTRUCTORS¶ - o - Cidr(std::string const &cidrPattern): The Cidr object is initialized with a single CIDR specification. - o - Cidr(std::istream &cidrStream): The Cidr object is initialized with CIDR specifications read from the std::istream cidrStream. Default, copy and move constructors and the copy and move assignment operators are available. MEMBER FUNCTIONS¶ The return valuess of the accessors (i.e., the const members) are only defined following a successful match (see below, the match members). - o - std::string const &address() const: returns the address matching a CIDR. - o - std::string cidr() const: returns the CIDR containing a specified address. - o - std::string first() const: returns the first address of the range of addresses defined by the CIDR specification. - o - std::string last() const: returns the last address of the range of addresses defined by the CIDR specification. Note that first, last do not define an iterator range. The address returned by last still belongs to the CIDR-range. - o - bool match(std::istream &in): The value true is returned when an IP4 address found in the lines of in belongs to a CIDR range inspected by the Cidr object. The match function returns true at the first matching address. E.g., if a line contains the text and the CIDR specifications This is address 1.2.3.4 and this is 5.6.7.8 were provided to the Cidr object, then the object will report a match for 5.6.7.8. 5.1.1.1/8 1.2.1.1/16 - As soon as a match is found match returns true. If none of the addresses found in the lines of in matches any of the object’s CIDR specifications, false is returned. - o - std::string mask() const: returns the mask used by the CIDR specification. - o - bool match(std::string const &line): The value true is returned when an IP4 address found in line belongs to a CIDR range inspected by the Cidr object. The match function returns true at the first matching address. - If none of the addresses found in line matches any of the object’s CIDR specifications, false is returned. - o - void setCidr(std::istream &cidrStream): A new set of CIDR specification is loaded into the Cidr object, reading the specifications from cidrStream. - o - void setCidr(std::string const &cidrPattern): A new CIDR specification is loaded into the Cidr object, using the specification found in cidrPattern. The Cidr object is initialized with a single CIDR specification which must be of the form a.b.c.d or a.b.c.d/m. If the mask is not specified a mask-size of 32 is used, effectively defining an address range of only one address. Mask values of 0 are ignored. - o - void swap(Cidr &other): The current and other object are swapped. STATIC MEMBERS¶ EXAMPLE¶ #include <fstream> #include <iostream> #include <bobcat/exception> #ifdef BOBCAT #include <bobcat/cidr> #else #include "cidr" #endif using namespace std; using namespace FBB; int main(int argc, char **argv) { enum Spec { NONE, FILE, CIN }; Spec spec = CIN; ifstream in; if (argc > 1) { Exception::open(in, argv[1]); // file containing cidr-specs spec = FILE; } while (true) { string cidrSpec; if (spec == CIN) { cout << "Specify cidr (empty to quit): "; if (!getline(cin, cidrSpec) || cidrSpec.empty()) break; } try { Cidr cidr; switch (spec) { case NONE: return 0; case FILE: cidr.setCidr(in); spec = NONE; break; case CIN: cidr.setCidr(cidrSpec); } while (true) { cout << "Specify address to test (empty to " << (spec == CIN ? "respec. CIDR" : "quit") << "): "; string address; if (!getline(cin, address) || address.empty()) break; if (!cidr.match(address)) { cout << "Address " << address << " not in "; if (spec == CIN) cout << cidrSpec << ’\n’; else cout << "specifications in " << argv[1] << ’\n’; } else cout << "Address " << address << " in " << cidr.cidr() << "\n" "Lowest address: " << cidr.first() << "\n" "Highest address: " << cidr.last() << "\n" "CIDR mask: " << cidr.mask() << "\n" "Address: " << cidr.address() << ’\n’; } } catch (exception const &err) { cout << "Oops... " << err.what() << "\n" "Try again...\n"; } } } FILES¶ bobcat/cidr - defines the class interface SEE ALSO¶ BUGS¶ Members of Cidr use static data. The current implementation of Cidr is therefore not thread-safe.).
https://manpages.debian.org/bullseye/libbobcat-dev/cidr.3bobcat.en.html
CC-MAIN-2021-43
refinedweb
976
66.84
Mark McSpadden - Home tag: Mephisto Noh-Varr 2007-10-15T21:14:02Z markmcspadden tag: 2007-10-15T21:12:00Z 2007-10-15T21:14:02Z The Ruby Abandonment Threshold Survey <p>If you work with Ruby, check out this survey:</p> markmcspadden tag: 2007-09-13T20:54:00Z 2007-09-13T21:04:47Z TMobile + iPhone = Awesomeness From my twitter feed: <blockquote> <p>I have an iphone. I have an iphone on tmobile’s voice and data network. I have an iphone on my home wifi network. I have an iphone.</p> </blockquote> <h2>How it all started</h2> <p>I was browsing through my feeds yesterday and came across <a href="">this story</a> about an open source effort to unlock the iPhone. As a very happy TMobile customer, I had never considered the iPhone within my reach, but now with an open source unlock and 4GB iPhones reduced to $299, I had to give this thing a whirl.</p> <p>So I head over to my local Mac store, inquire about the refund policy (14 days, 10% restocking fee if opened), buy my 4GM iphone and then head home to do some more reading. After a little bit, I decide to eat the $30 bucks and unwrap the beautiful piece of machinery. (I’m a nerd, just the hours spent on the effort are worth that small price.)</p> <h2>The Resources</h2> <p>By the time I write this, there may be an installer available, but in case there’s not:</p> <p>Mac <span class="caps">OS X 10</span>.4 and iTunes version 7.4</p> Apps: <ul> <li>iFuntastic_3.03</li> <li>iActivator</li> <li>Installer.app</li> </ul> <p>Tutorial: <a href=""></a></p> <h2>The hoop jumping</h2> <p>I am definitely not saying this will work for you. It did for me. If you brick your phone it’s your fault. (I’m not even sure you <em>can</em> brick your phone, you should be able to easily restore it, but disclaimers are cool and I wanted one.)</p> <p>First I connected my iPhone to my Mac, itunes came up, I canceled out of the activation. Next I fired up iFuntastic and choose the “Restore” option. This is really nice since you start clean and it gives you a file to revert back to should things go crazy. I then tried to use the “Unshackle” feature, but was unsuccessful.</p> <p>I then decided to try iActivator. It worked great and after following all their instructions, I had an activated iPhone.</p> <p>Now that my iPhone was activated, I could add the Installer.app to it. After I followed all those instructions, I was ready to start unlocking. I hit the tutorial about half way through step 2 (obviously I used the mac Installer.app instead of ibrickr) and used Installer to install the 3 required packages.</p> <p>Next I download the required files (oops, those are at the start of Step 2) and moved them to my iphone. I moved them not using the suggested method, but instead did something else. I first joined my iphone to my wireless network. Then I used ssh to login to my iPhone and test that piece of the puzzle. Then I used a mac program called sshfs that basically mounts a drive for you via ssh. After the drive was mounted, I just did a ‘drag and drop’ for the files and folders specified in the tutorial.</p> <p>I then ran all the tutorial commands, without issue, and at the end, that’s right, an iPhone on Tmobile’s network. Pretty sweet.</p> <h2>Still in trial mode</h2> <p>I still have 13 days to evaluate this setup to see if it’s actually feasible to maintain against the firmware and itunes updates. I’ll be sure and keep you posted!</p> markmcspadden tag: 2007-09-08T13:39:00Z 2007-09-08T13:59:35Z Lone Star Ruby Conference Day #1 <p>I’m in Austin at the Lone Star Ruby Conference and I gotta say Day #1 was so packed that I was too worn out to even talk about it last night. A quick breakdown before Day #2 starts…</p> <p>First the Ruby:</p> <ul> <li>Some great talks about Ruby as a beautiful, fun, and exciting languague</li> <li>Interesting talk by James Edward Gray II about using Ruby as a Glue language to call non Ruby applications within the OS</li> <li>Testing…it’s your friend. It now comes in several Ruby flavors.</li> <li>Ruby community is cool. We’re nice and smart and taking the world by force.</li> </ul> <p>Other Stuff:</p> <ul> <li>Day #1 went from 9am until 10pm. They even served us lunch and dinner here at the conference center. So pretty much one seat for 13 hours.</li> <li>I got to meet and chat with Gregg and Jason from RailsEnvy.com. The “videos” these guys have made for Rails are great and, I’ve got to say, they really know their stuff.</li> </ul> markmcspadden tag: 2007-08-31T03:05:00Z 2007-08-31T03:11:27Z The current state of our "high tech" world <p>I was reading Jim Bruene’s <a href="">Mobile Money and Banking</a> today an I got into his most recent article about <a href=""><span class="caps">SMS</span> Banking</a>. I’m interested in the subject and probably would have just stored it away in my mental file, however, Jim was offering a $5 Starbucks gift card just for posting a “substantive comment.”</p> <p>Having already been to Starbucks today (and $6 poorer for it) I thought I’d share my thoughts on the impact that cell phone service providers will have on the future of <span class="caps">SMS</span> and Mobile web banking.</p> <p>Not long after I submit my comment, Jim emails me to get my physical address so he can mail me the gift card. This exchange struck both of us as kind of funny. We are talking about checking our bank balances and transferring money on cell phones, yet to get me a Starbucks gift card, Jim was going to have to physically go to a Starbucks<sup><a href="#fn1">1</a></sup>, buy a $5 gift card, put it in an envelope, put a stamp on it, and send it half way across the country to my place. :)</p> <p>Jim did point out that we’ve come a long way to get to the Starbucks gift <em>card</em>, but it’s pretty apparent to me that we’ve still got a ways to go.</p> <p><sup>1</sup> Starbucks does sell gift cards through their website that you can have delivered to anyone you want, however the smallest increment they offer is $15.</p> markmcspadden tag: 2007-08-29T10:26:00Z 2007-08-29T23:45:34Z The Panic <p>If you’re a developer, you know what I’m talking about. You’re doing something seemingly trivial, when you see something, you’re not sure what it is, but it doesn’t look quite right. You squint at it. Then you realize, this is something bad, something big, something really big and bad.</p> You then start down a roller coaster of emotions and reactions: <ol> <li>Denial: “No, my code isn’t <em>really</em> doing that.” </li> <li>Anger: “Why is my stinking code doing this!” </li> <li>Blame: “It’s got to be something wrong with a library or a bad default setting.” </li> <li>Generalization: “I can’t be the only person this is happening to. Is this is happening on every site?” </li> <li>Acceptance: “Ok, this is wrong and it needs to be fixed.”</li> </ol> <p>It happened to me yesterday, while scanning the logs of an internal app looking for bugs. I started noticing something that didn’t seem quite right. My application was logging all the details of login requests, including passwords. That’s right, passwords and their associated usernames were just sitting in my log files, clear text for the world to see.</p> <p>So I started the panic…all the stages flew by in a matter of minutes. Then I did the constructive thing and hit up Google for an answer. And one was right there for the taking.</p> <strong>If you use Ruby on Rails, you need to add this to your ApplicationController for every application you have</strong> <pre><code>filter_parameter_logging :password, :password_confirmation</code></pre> <p>What does this do? Well as you probably guessed, it filters the given parameters from being logged in your log files. The request will still be logged, only the specified parameters will be logged as “[FILTERED]” instead of their actual values.</p> <p>Now I know what you’re thinking, “Why isn’t this taken care of by default?” or “How did I miss this?” The first is valid, the second, well you can console yourself in the fact that for some reason it doesn’t seem to be common knowledge among rails people. Let’s fix that shall we…</p> <p><small>Special thanks to <a href="">Baldur Gudbjornsson’s blog</a> for stopping the panic for me!</small></p> markmcspadden tag: 2007-08-09T21:39:00Z 2007-08-09T22:09:35Z The Banktastic Feeds <p>I was doing more normal feed scan on Tuesday, when I came across an article by Robbie Wright titled <a href="">Making <span class="caps">RSS</span> Easy</a>. Little did I know it would steal half of my week.</p> <p>What Robbie and the world didn’t know is that at my <a href="">day job</a> I’ve been hacking away at a community site for bankers that is all about making industry specific information easier to find and use. With that in mind I started hacking away trying to aggregate FI feeds. The results are as follows:</p> <ul> <li><a href="">Six compiled FI feeds</a></li> <li>A <a href="">splash page</a> for Banktastic complete with Google Analytics</li> <li>A <a href="">mailing list</a> for the Banktastic Beta Launch</li> <li>A deadline for Banktastic Beta</li> </ul> <p>The moral of the story: Don’t read Robbie’s blog :)</p> markmcspadden tag: 2007-08-01T17:21:00Z 2007-08-01T18:17:30Z The Email Disclaimer <p><a href="">Open Source CU</a> just <a href="">gave me some props</a> for the little disclaimer I’ve been using at the bottom of my emails. Since a mention on <span class="caps">OSCU</span> usually brings in some people, I thought I’d explain and expand a little for anyone that’s interested.</p> First, the disclaimer that appears just under my name on both my personal <em>and professional</em> emails: <blockquote> Did I just sound like a jerk? If I came across as a little short, it may be due to the fact that I am currently experimenting with different disciplines of email writing. I am currently limiting all my emails to 3 sentences or less. Sound interesting? Read more at and help cut down on email clutter. </blockquote> <h2>Where did I start?</h2> A few months back I read <a href=";s=books&#38;qid=1185988198&#38;sr=8-1">Bit Literacy by Mark Hurst</a> and made a personal commitment to write shorter emails. The problem was that I didn’t really share that commitment with anyone. You’d be surprised (or maybe you wouldn’t) at how many people got upset when I started sending one and two sentence emails that ultimately lacked the “personal fluff” they were used to. I quickly abandoned the practice for fear of losing all my friends. <br /><br /> <h2>The re-birth of the short email</h2> A few weeks ago, I came across the <a href="">three sentences site</a> through my feed reading and was re-energized. I took a look at the 2, 4, and 5 sentence varieties but ultimately set myself on 3 and haven’t looked back. I quickly threw together the disclaimer, slapped it on my personal email, and asked permission to use it on my work emails as well. Since I work for <a href="">one of the coolest companies out there</a> I was given the “ok” and that’s where I sit today. <br /><br /> <h2>Personal Benefits</h2> So I love writing shorter emails. Not only do I find my writing improving, but I find myself more likely to send emails. I know that if I can keep it short, there is a much better chance that my email will get read and be responded to. I do spend more time writing each email in order to get it under the 3 sentence limit, but to me it’s well worth it. <p>Hope you’ve found my little journey enlightening!</p> <strong>Update:</strong> I just tracked down where this whole sentences thing got started and this looks like <a href="">the original</a>. His disclaimer may be better than mine: <blockquote> Q: Why is this email 5 sentences or less?<br /> A: </blockquote> markmcspadden tag: 2007-07-31T23:50:00Z 2007-08-01T00:07:25Z Book Review: The Paradox of Choice <p>I recently started and finished <a href=";s=books&#38;qid=1185925971&#38;sr=8-1">The Paradox of Choice</a> by Barry Schwartz and I have a hard time even explaining how good this book is. You need to buy this book. Go into the bookstore with blinders on (ignore the other choices) and get it today. Seriously.</p> <p>Ok, so why do you need to read this book? Because it’s all about the mess of choices that we face everyday and how, as the the sub-sub title states, “the culture of abundance robs us of satisfaction.” There is a ton of info in this book about the way we make choices and insight into how we can be happier with the choices we make.</p> <p>Now beyond just personal enlightenment, if you are someone in industry that is trying to better serve people, this is a must read. It will help you understand how people choose and why they often choose not to choose when presented with too many choices.</p> <p>I’ve found this book to be extremely beneficial both personally and professionally. It has helped be happier with the daily choices I make and I think it’s helping build better websites.</p> <p>Ok enough sales pitch…go buy it so we can talk about it.</p> markmcspadden tag: 2007-07-27T16:58:00Z 2007-07-27T17:16:25Z Extending Del.icio.us via Javascript <p>So I’m blogging more and posting more comments on blogs I read…which overall is a good thing. However, maintaining and following the conversations I get involved in via comments is super tedious. So I looked to my old friend Delicious for help in the matter.</p> <p>I started by adding all the articles I’ve commented on to Delicious with appropriate tags plus two of my own homegrown tags: <a href="">watching</a> and <a href="">contributed</a>. Why two tags? Eventually I’d like to move articles off my “watching” list, but would still like a place to track down all the conversations I’ve “contributed” to.</p> <p>Next, I wanted to be able to go to my “watching” tag in Delicious and quickly open up all the links. Hmmm…there’s not really a way to do that. So my buddy JS and I spent a half hour together and made our own. Here is the finished product that you can just drag into your “Bookmark Toolbar” on FF: <a><span class="caps">DOAL</span>: Delicious Open All Links</a></p> <p>Now, anytime you are viewing a page in Delicious using FF, you can easily open all the links by clicking on that bookmark. (I don’t know what to tell you non-firefoxers…maybe someone in the comments can help you out.)</p> <p>So, if you’re not a nerd, you should probably stop here. However, if you like Javascript, I’ll give you a quick walk through of what I did to get this thing going.</p> <p>First, I went to my selected <a href="">Delicious tag</a> and opened up Firebug to start playing around. Using the inspect method, I see that the only “h4” tags on the page are the ones that house the links I want. Being a regular prototype user, here was my first attempt via the Firebug console: (Ok it’s not the first thing I typed, but my first real attempt)</p> <pre> <code>$$('li.post h4 a').each(function(element) {window.open(element.href)});</code> </pre> <p>Wow…that is good looking, sexy, one line JS! But it doesn’t work. For some reasons the “window.open” event wasn’t firing as expecting when inside the “each” function.</p> <p>So I move to something like this:</p> <pre> <code>var links = $$('li.post h4 a'); for(var i=0; i<links.length; i++) { window.open(links[i].href) };</code> </pre> <p>Ah the for loop…it’s been a while. This code works in Firebug, so I condense it to one line, put “javascript:” in front of it, paste it into the address bar, and hit enter. No go. ”$$” is not a function. Crap. Assuming prototype lives everywhere is a bad assumption. Let’s try to make it work without my favorite JS library.</p> <pre> <code>var h4s = document.getElementsByTagName("h4"); for(var i=0; i<h4s.length; i++) { window.open(h4s[i].getElementsByTagName("a")[0].href) }; </code> </pre> <p>Sweet. This working in the address bar, and opens up the right links, but it’s causing my Delicious page to go away. Let’s fix that.</p> <pre> <code>var h4s = document.getElementsByTagName("h4"); for(var i=0; i<h4s.length; i++) { window.open(h4s[i].getElementsByTagName("a")[0].href) }; window.refresh();</code> </pre> <p>That’s better. Now all you do is right click in your bookmark toolbar, choose “New bookmark”, name it and insert the one line version of the code with “javascript:” in front of it and you have a Delicious extension!</p> <p>I’m open to re-writes and suggestions for better efficiency, so if you’ve got ideas, let’s hear them.</p> markmcspadden tag: 2007-07-25T22:54:00Z 2007-07-25T22:57:09Z Let's start a discussion thread, user to user. <p>Seriously who talks like that? Unfortunately too many of us that build web apps speak this way through the copy we use on our sites. <a href="">Trey Reeme</a> recently re-inspired me to stop talking like a techie and start talking like a human.</p> <p>So I’m trying to do better, but it’s not all that easy. I’ve been in tech-land a long time. So I thought I’d start a personal “techie to human dictionary” to help me out. You can checkout <a href="">this page</a> to see where I’m at. (Don’t get your hopes up, there’s only 4 entries.)</p> <p>I’d much appreciate any feedback or ideas! I’d really like to see this thing be a real resource…so let’s get started.</p> markmcspadden tag: 2007-07-24T15:47:00Z 2007-07-24T23:09:26Z BarCampBankSeattle Day 2 Recap <p>Day 2…wow…what a day. Started with a great session on <a href="">banker to banker collaboration</a> and ended with a monumental whiteboard of promise and hope. Sound a little dramatic…maybe…but then again maybe not. The amount of space it is taking up in my mind can only be explained by something that truly is revolutionary.</p> <p>Even with the picture of that whiteboard almost tattooed in my mind, the thing that sticks with me the most from Day 2, is Jesse’s unwillingness to let the rest of us settle for the Jesse Robbins solution. There were several times in our afternoon discussion where I could almost feel the room waiting to let Jesse take this project and run all the way with it, filling us in where appropriate. However, much to Jesse’s credit, that was not the path that was taken, nor was it the path that was needed. What needed to happen was a room full people talking to a whiteboard, venting frustrations and forging solutions.</p> <p>And now we sit with an even greater task ahead, continuing forward without sitting in the same room and staring at each other until someone speaks. I am excited about the road ahead, not just for the promise of an open source solution to an industry issue, but also for the collaboration that will occur between bright people and experimentation of the technologies that will best facilitate this conversation.</p> markmcspadden tag: 2007-07-22T10:10:00Z 2007-07-24T23:11:13Z BarCampBankSeattle Day 1 Recap <p>Day 1 of <a href=""><span class="caps">BCBS</span></a> was a whirlwind and honestly wore me out. (Hence I’m recapping in the morning and not last night.) It was my first BarCamp event in general and I have to say, I’m sold!</p> <p>But even beyond the BarCamp experience, being trapped in a room all day with people that eat, sleep, drink, and breathe the financial industry is truly unique. I said it last night and I mention it in the sidebar of this blog, passionate people are awesome! They are contagious. For all the talk about how bad corporate cultures can become in the presence of a few bad people, I have think that just the presence of one of these people in an organization is culture changing and if you were lucky enough to have two I would expect nothing less than earthshaking innovation.</p> <p>Well it’s off to Day 2!</p> markmcspadden tag: 2007-07-16T14:49:00Z 2007-07-24T23:11:42Z BarCampBankSeattle here I come... <p>It’s official, Brad and I are on a collision course with the first <a href="">BarCampBank</a> in the US, <a href="">BarCampBankSeattle</a>!</p> <p>I’ve got so much to do to get ready for this thing that it’s stupid, so the post ends here.</p> markmcspadden tag: 2007-06-21T13:55:00Z 2007-07-24T23:12:29Z Element.Methods.visible may not return what you would expect. <p>I was knee deep in an old php form this week, trying to clean it up a bit, hiding and showing certain questions based on the responses of earlier questions. In addition this form had over 400 lines of JS validation that I had to turn on and off based on a questions visibility. Did I mention most of the fields and labels were stuck in a table?</p> <p>(Ok…I can’t complain too much, it was marked up very nice and clean.)</p> <p>So I’m hacking away at this validation and I need to only validate visible fields. So naturally I try something like this:</p> <pre> if($('fieldId').visible() && oldConditions) { throw an error; } </pre> <p>Seemed pretty simple to me…until it wasn’t working. Fields that I could not see in my browser were still being validated. If I can’t see it, doesn’t that mean it is <span class="caps">NOT</span> visible.</p> <p>According to prototype, I’m way off. The ‘visible’ method only tests <span class="caps">THE SINGLE ELEMENT</span> it is called on for the “style.display == ‘none’” without regard to that element’s ancestors. The problem was, my fields were visible, but the cells that contained them were not. What to do?</p> <p>Extend prototpye of course! After a google and <a href="">a quick read of a short article</a> this is what I came up with:</p> <pre> Element.Methods.truelyVisible = function(element) { var visibleBoolean = element.visible(); element.ancestors().each(function(el){ if(!el.visible()) { visibleBoolean = false; } }); return visibleBoolean; }; Element.addMethods(); </pre> <p>Quickly, it runs through an element’s ancestor’s checking them for visibility and then returning where the element can actually be seen or not. Now you can do <code>$('elementId').truelyVisible()</code> and get whether or not an element can actually be seen in the browser. Hope you enjoy!</p> <p><br /></p> <p><b>PS. Looking at it a day later, it could probably be more efficient like this:</b></p> <pre> Element.Methods.truelyVisible = function(element) { var visibleBoolean = element.visible(); if(visibleBoolean) { element.ancestors().each(function(el){ if(!el.visible()) { visibleBoolean = false; } }); } return visibleBoolean; }; Element.addMethods(); </pre> <p><br /></p> <p><b><span class="caps">PPS</span>. It gets even better…I should blog code more often:</b></p> <pre> Element.Methods.truelyVisible = function(element) { return (element.visible() && !element.ancestors().any(function(el){ return !el.visible(); })) }; Element.addMethods(); </pre> markmcspadden tag: 2007-05-04T11:55:00Z 2007-07-24T23:13:22Z RiskKey Launched! <p>There are not enough exclamation marks in the world to follow that title. I’m so happy to finally have this app up and running and waiting for the world to embrace it.</p> <p>Ok…so it’s really not targeted at the whole world…just the world of Financial Institutions and their Risk Assessments. (But that’s still a good sized world!)</p> <p>Check out the full announcement at: <a href="">blog.riskkey.com</a></p> <p>I hope to follow this launch with several posts about my experience over the last month in trying to push this thing to launch. Should be some fun JS, RoR, and UI discussion!</p>
http://feeds.feedburner.com/MarkMcSpadden
crawl-002
refinedweb
4,359
72.16
In this tutorial I will walk you through some of the uses of the Twitter REST API, and how you can use it to create a game that not only displays real-time Tweets, but uses them to generate objects the player can interact with. Before you read this tutorial, I recommend that you read the AS3 101 sessions by Dru Kepple, Understanding JSON, Understanding the Game Loop - Basix, Greensock Tweening Platform sessions and maybe some design and animation tutorials. Final Result Preview Let's take a look at the final result we will be working towards: Step 1: Let's Get the Assets Ready Before we get started we will need to set up some assets; we are building a game, so you might want to make it look pretty :-). We will need buttons for New Game, Instructions, Menu and Tweet (for the player's score); we will also need a background, some birds, the golden egg and the cracked egg. Besides all that we will need some misc assets such as the loading message, the Tweet message, a "follow me" button, the instructions window and the bar where you will display your Tweets. Step 2: Let's Create Some Classes For this tutorial we will be working with some classes, if you are not familiar with classes you should take a look at the How to Use a Document Class in Flash tutorial. We will need a Main class which will be our main brain, that's the one you will link to your FLA file. Besides that one, we will need a Game class which will handle the game logic of the game and do most of the work. Since games have events that you need to listen to we will create a class named GameEvent which we will use to communicate with our main class. We will also need an Egg class which will hold the data of the Tweet, the kind of egg that it will be, and some other things that we will need later on. And we will need a TweetHolder class which we will link to a movie clip on the library so we can autosize and add some properties to the Tweet that we will show. All of those classes will go to our com folder which needs to be right next to our FLA file. Main.as package com { import flash.display.*; // Extends MovieClip cause this will be linked our FLA file public class Main extends MovieClip { public function Main() { // Here we will add our code :-) } } } Game.as package com { import flash.display.*; public class Game extends Sprite { public function Game() { // Here we will add the logics for our game } } } GameEvent.as package com { import flash.events.*; // This will be our custom event so it will extend Event public class GameEvent extends Event { // Here we will store the parameters that we will receive, so that we can use them later on, that's why it's public public var parameters:String; // Here we add the params since we will use it later on to share information between classes public function GameEvent(type:String = "Default", params:String=null, bubbles:Boolean = false, cancelable:Boolean = false) { // We need to initialize our super so we get all its properties super(type, bubbles, cancelable); } } } Egg.as package com { import flash.display.*; // This will be our custom event so it will extend Event public class Egg extends Event { public function Egg() { // Here we will add the logics for our eggs } } } TweetHolder.as package com { import flash.display.*; // This will be our custom event so it will extend Event public class TweetHolder extends Event { public function TweetHolder() { // Here we will add the logics for our TweetHolder } } } Step 3: Arrange the Menu It's time to start the fun! Place all our menu assets, place your new game button on stage, create the title for your game, add the instructions as well as the instructions button. Once you have all that on stage assign an instance name to each of them since we will need to refer to them in our Main class. Step 4: Prepare TweenLite For this tutorial we will be using TweenLite from GreenSock which you can download HERE (click AS3, download the ZIP file containing it, then unzip it and copy the file named greensock.swc to the folder where you have your FLA file). When you have the SWC file right next to your FLA we will need to link it to our FLA so click Edit on the Properties panel of your file: Then click Settings right next to ActionScript 3.0, then the +, and enter "./greensock.swc" After that we are ready to start working in our Main class. Step 5: Showing the Instructions To show the instructions of the game we will need to have already created a movie clip which will contain the instructions with the instance name of instructions_content and the button that will summon it with the instance name of instructions_btn. Besides that we will take the time to make everything act as a button. We will use just one function to make the instructions show and hide so we will need a variable that will tell us whether the instructions are already being displayed; we will call that variable showingInstructions. package com { // import what we need to animate the objects import com.greensock.TweenLite; import com.greensock.easing.*; import flash.display.*; import flash.events.*; public class Main extends MovieClip { // variable that we will use to know if the instructions are being displayed // set to false since the first position of the instructions will be out of frame private var showingInstructions:Boolean = false; public function Main() { this.addEventListener(Event.ADDED, init); } private function init(e:Event):void { this.removeEventListener(Event.ADDED, init); // set objects to act like button and get the pointer hand instructions_btn.buttonMode = true; instructions_content.close_btn.buttonMode = true; // we will call the function instructionsHandler when the instructions_btn.addEventListener(MouseEvent.CLICK, instructionsHandler); instructions_content.close_btn.addEventListener(MouseEvent.CLICK, instructionsHandler); } private function instructionsHandler(e:MouseEvent):void { // we ask if the instructions are being showed if(showingInstructions) { // if they are we will want to send them out of frame and tell the game that is not being showed TweenLite.to(instructions_content, .4,{y:600, ease:Cubic.easeIn}); showingInstructions = false; } else { // if it's not then we will animate it into stage and tell that it's being showed TweenLite.to(instructions_content, .4,{y:364, ease:Cubic.easeOut}); showingInstructions = true; } } } } Step 6: Follow Me Button Since you are a developer and you might want users to get in touch with you a "follow me" button sounds like a good idea - so let's make your button send the users to your twitter profile; we will do this by like so: private function init(e:Event):void { this.removeEventListener(Event.ADDED, init); // set objects to act like button and get the pointer hand instructions_btn.buttonMode = true; followMe_btn.buttonMode = true; instructions_content.close_btn.buttonMode = true; // we will call the function instructionsHandler when the instructions_btn.addEventListener(MouseEvent.CLICK, instructionsHandler); instructions_content.close_btn.addEventListener(MouseEvent.CLICK, instructionsHandler); followMe_btn.addEventListener(MouseEvent.CLICK, followMeHandler); } The we will need to create our handler which will be called followMeHandler as we wrote when we declared the listener: // this function will receive a MouseEvent object which we will call "e" private function followMeHandler(e:MouseEvent):void { // You will need to change jscamposcr for your username, twitter will take care of the rest navigateToURL(new URLRequest(""), "_blank"); } Step 7: Prepare the Stage for a New Game When you have your menu, the instructions and the "follow me" button working it's time to get your hands dirty and start the hard work - but first we will need to prepare the area with the right objects to start the game. This we will do it by moving out all the objects of the menu, including the instructions. First let's add a click listener to the New Game button that we have in our stage, and then let's create a function that will clean up the stage. private function init(e:Event):void { this.removeEventListener(Event.ADDED, init); // set up listeners, positions, visibility, etc newGame_btn.buttonMode = true; instructions_btn.buttonMode = true; followMe_btn.buttonMode = true; menu_btn.buttonMode = true; instructions_content.close_btn.buttonMode = true; newGame_btn.addEventListener(MouseEvent.CLICK, startGame); instructions_btn.addEventListener(MouseEvent.CLICK, instructionsHandler); instructions_content.close_btn.addEventListener(MouseEvent.CLICK, instructionsHandler); followMe_btn.addEventListener(MouseEvent.CLICK, followMeHandler); } Next we will take all our objects out of the stage in the function startGame}); // we will need to hide the instructions if they are being desplayed if(showingInstructions) { TweenLite.to(instructions_content, .3,{y:600, ease:Quad.easeIn}); showingInstructions = false; } } Now we need to add a menu button and a score text field, we will call the menu button menu_btn and the score will be called score_text and it will be a dynamic text field. Don't forget to embed the font; for this I will embed Verdana Bold by clicking on Embed and adding the characters we will need. Then add both objects at the top of the stage but out of it since we wont need them in our first frame, then we will add two lines that will animate both of them on our startGame let's give the user the chance to go back to the menu by adding a function to the menu button that we just added; we will call this one goToMenu and we will call it when the user clicks on the menu_btn. For that, we will add an event listener in our start game the function that will make things come back: private function goToMenu(e:MouseEvent):void { // we disable the event listener menu_btn.removeEventListener(MouseEvent.CLICK, goToMenu); // we move back all our assets TweenLite.to(title, .3, {y:91, delay:.2, ease:Quad.easeOut}); TweenLite.to(newGame_btn, .3, {x:162, delay:.2, ease:Quad.easeOut}); TweenLite.to(instructions_btn, .3, {x:162, delay:.2, ease:Quad.easeOut}); TweenLite.to(followMe_btn, .3, {y:500, delay:.2, ease:Quad.easeOut}); TweenLite.to(menu_btn, .3,{y:-35, ease:Quad.easeIn}); TweenLite.to(score_text, .3,{y:-30, ease:Quad.easeIn}); } So far the project should look like this: We didn't actually remove the title; we will leave it there while we show a message that says that the Tweets are being loaded. Step 8: Create the Needed Events We are almost ready to start our game engine, but as part of it we need to be able to communicate with our Main class. We will do this with events, so let's take our GameEvent and add the type of events that we want to listen to: - When the game has ended: GAME_ENDED. - When the score has changed: SCORE_CHANGE. - When the Tweets that we load are ready to use: TWEETS_READY. - When the Tweets couldn't be loaded: TWEETS_ERROR. So with all that sorted now we need to edit our GameEvent class package com { import flash.events.*; public class GameEvent extends Event { public static const GAME_ENDED:String = "Game Ended"; public static const SCORE_CHANGE:String = "Score Change"; public static const TWEETS_READY:String = "Tweets Ready"; public static const TWEETS_ERROR:String = "Tweets Error"; public var parameters:String; public function GameEvent(type:String = "Default", params:String=null, bubbles:Boolean = false, cancelable:Boolean = false) { super(type, bubbles, cancelable); parameters = params; } } } With our menu and events created we are finally ready to start our game engine Step 9: Setting Up a Game Instance To get our game working properly we need to instantiate it, add the event listeners, and destroy them when no longer needed; for that we will add some code to the startGame function, the goToMenu function, and a new function we will created called endGame (this one will kill our game instance and remove the event listeners). First let's edit our "start game" function; we will add the next lines to the end of the end of the startGame function. game = new Game(); game.addEventListener(GameEvent.GAME_ENDED, endGame); game.addEventListener(GameEvent.SCORE_CHANGE, changeScore); game.addEventListener(GameEvent.TWEETS_READY, addGame); game.addEventListener(GameEvent.TWEETS_ERROR, errorHandler); Since we are using a var called game we will need to declare it at the begining of our class as a private var: private var game:Game; In our goToMenu function we will add a call to our endGame function which we will create and add the following code: private function endGame(e:GameEvent = null):void { // This will reset the score in case the user starts a new game score_text.text = "Score: 0"; // This will kill our game with the function killGame that we will create inside our game class game.killGame(); // We will remove all our listeners from our game instance game.removeEventListener(GameEvent.GAME_ENDED, endGame); game.removeEventListener(GameEvent.SCORE_CHANGE, changeScore); game.removeEventListener(GameEvent.TWEETS_READY, addGame); game.removeEventListener(GameEvent.TWEETS_ERROR, errorHandler); // If the game has been added then we will fade it out and then we will remove it from stage and memory if (game.addedToStage) { TweenLite.to(game, .4, {alpha:0, onComplete:(function (){game.parent.removeChild(game); game = null})}); } // If not then we will just kill it else { game = null; } } With this we will be good to go and work on our Game class Step 10: Loading Tweets First we will need to declare some variables that we will use later on: // This will hold the information of our Tweets after they are loaded private var goldenEggsData:Object; private var crackedEggsData:Object; // This will hold our eggs private var goldenEggsArray:Array = new Array(); private var crackedEggsArray:Array = new Array(); // The count of eggs that have been used private var goldenEggsCount:int = 0; private var crackedEggsCount:int = 0; // The speed of the eggs while they fall private var speed:int = 4; // This is the nest that we will use to catch the eggs private var nest:Nest = new Nest(); // This will hold the eggs that are on stage private var eggs:Array = new Array(); // This will hold the tweets that are being displayed private var tweetsOnScreen:Array = new Array(); // This ones are self-explained private var score:Number = 0; private var difficulty:Number = 3; private var ended:Boolean = false; // This will tell if the key are being holded private var rightKey:Boolean = false; private var leftKey:Boolean = false; // MovieClip from the library private var tweetsBar:TweetsBar = new TweetsBar(); // This says if the game has been added to the stage public var addedToStage:Boolean = false; Then we need to tell the user what is going on so we will add a movie clip to the stage and name it loadingTweets; this says that the Tweets are being loaded. We will fade it in within our startGame from our Main class private function startGame(e:MouseEvent):void { loadingTweets.x = 130; loadingTweets.y = 230; loadingTweets.alpha = 0; TweenLite.to(newGame_btn, .3, {x:-200, ease:Quad.easeIn}); TweenLite.to(instructions_btn, .3, {x:500, ease:Quad.easeIn}); TweenLite.to(followMe_btn, .3, {y:650, ease:Quad.easeIn}); TweenLite.to(loadingTweets, .3, {alpha:1, delay: ; } game = new Game(); game.addEventListener(GameEvent.GAME_ENDED, endGame); game.addEventListener(GameEvent.SCORE_CHANGE, changeScore); game.addEventListener(GameEvent.TWEETS_READY, addGame); game.addEventListener(GameEvent.TWEETS_ERROR, errorHandler); } And we will fade it out in our endGame function: private function endGame(e:GameEvent = null):void { score_text.text = "Score: 0"; game.killGame(); game.removeEventListener(GameEvent.GAME_ENDED, endGame); game.removeEventListener(GameEvent.SCORE_CHANGE, changeScore); game.removeEventListener(GameEvent.TWEETS_READY, addGame); game.removeEventListener(GameEvent.TWEETS_ERROR, errorHandler); if (game.addedToStage) { TweenLite.to(game, .4, {alpha:0, onComplete:(function (){game.parent.removeChild(game); game = null})}); } else { game = null; loadingTweets.alpha = 0; loadingTweets.x = 800; loadingTweets.y = 2300; } } It's now time to start the fun and create the actual game! For that we will need Tweets. The main idea of this tutorial is to load Tweets, and we will use the search API from Twitter to do this. I recommend you to go and check it out, but for this game we will just use a few of the possible options; we will make two requests and then add the game to the stage, that's why we didnt add it when it was created, we will first load the Tweets for the golden eggs in our Game function and we will add an event listener when it's added, where we start the game: public function Game() { // tweets loader var loader:URLLoader = new URLLoader(); loader.addEventListener(Event.COMPLETE, loadCrackedEggs); loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); // construct the URL q = what we are looking for rpp = the amount of tweets that we want // If you are going to use complex string in your URL make sure to use the function encodeURI("Your String") and then add it to the URL var url:String = ""; loader.load(new URLRequest(url)); this.addEventListener(Event.ADDED, init); } For this request we used just lang which is the language for the Tweets that we want to receive given in a ISO 639-1 code; q which is the main word (can be a phrase as well - just make sure to encode the URL) we are looking for; and rpp which is the number of Tweets that we want to receive. If you want to search for more than one thing you can use OR, it still works just fine but isn't in the new documentation page so I can't tell if or they are going to stop supporting it (the same for NOT which becomes handy when you are getting too many spam Tweets). For even more information about this go to the "using search" page from Twitter. When our Tweets for golden eggs are loaded we will load the Tweets for "cracked eggs" in the function loadCrackedEggs and then we will dispatch an event saying that everything is ready for the game to start: private function loadCrackedEggs(e:Event):void { // We will declare this variable as a private variable so we can store the data here goldenEggsData = JSON.decode(e.currentTarget.data); // tweets loader var loader:URLLoader = new URLLoader(); loader.addEventListener(Event.COMPLETE, startGame); loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); // construct the URL ors = what we are looking for rpp = the amount of tweets that we want var url:String = ""; loader.load(new URLRequest(url)); } Once we load the JSON we will convert it into a object variable that we will declare at the begining of our code - to understand a JSON I recommend you read Understanding JSON - to convert it to an Object we will use the as3corelib from Mike Chambers and its function JSON.decode, which will return an object with all the contents of the JSON file. Step 11: Starting Our Game To start we will create two arrays which will contain the eggs information and for that we will need our class Egg which we created in Step 2; in that class we will store some data and add the graphics for our eggs. To add the graphics we will need to export the graphics for the eggs from the library to use them in our code like this: Then we will need to work in our class: package com { import flash.display.*; import flash.events.*; public class Egg extends Sprite { // Here we will store what type of egg this one is so the right graphic is used public var type:String; // Stores the string text public var tweet:String; // Stores the username of the autor of the tweet public var user:String; // Stores the URL of the avatar of the user public var userImg:String; public function Egg() { this.addEventListener(Event.ADDED, init); } private function init(e:Event):void { this.removeEventListener(Event.ADDED, init); // Here we add the graphic corresponding the the type of egg // We use the MovieClips that we exported in our library if(type == "Golden Egg") { var goldenEgg:GoldenEgg = new GoldenEgg(); addChild(goldenEgg); } else { var crackedEgg:CrackedEgg = new CrackedEgg(); addChild(crackedEgg); } } } } This is all that we will do to our Egg class. Now we will work in our startGame function. Here we will go through the object that contains the information of our Tweets, then for each Tweet that we loaded we will create an egg, give it the required information, and then add it to an array so we can use it later on. private function startGame(e:Event):void { crackedEggsData = JSON.decode(e.currentTarget.data); for (var i:int = 0; i < goldenEggsData.results.length; i++) { var goldenEgg:Egg = new Egg(); goldenEgg.tweet = goldenEggsData.results[i].text; goldenEgg.user = goldenEggsData.results[i].from_user; goldenEgg.userImg = goldenEggsData.results[i].profile_image_url; goldenEgg.type = "Golden Egg"; goldenEggsArray.push(goldenEgg); } for (var x:int = 0; x < crackedEggsData.results.length; x++) { var crackedEgg:Egg = new Egg(); crackedEgg.tweet = crackedEggsData.results[x].text; crackedEgg.user = crackedEggsData.results[x].from_user; crackedEgg.userImg = crackedEggsData.results[x].profile_image_url; crackedEgg.type = "Cracked Egg"; crackedEggsArray.push(crackedEgg); } dispatchEvent(new GameEvent(GameEvent.TWEETS_READY)); } Step 12: Error Handling It can happen that the Tweets can't be loaded so it's a good practice to do something about and not just let it happen, that's why every time we loaded Tweets we added an IOErrorEvent listener, set to call a function named errorHandler. This function will just dispatch an error event so our Main class can handle it: private function errorHandler(e:IOErrorEvent):void { dispatchEvent(new GameEvent(GameEvent.TWEETS_ERROR)); } Then in our FLA we will add a new frame to our loadingTweets movie clip, there you can add your message for the user to know that something went wrong and move to a different frame so that it doesn't show what it isn't supposed to. We will display that in the errorHandler class that we set up as listener for TWEET_ERRORs. private function errorHandler(e:GameEvent):void { loadingTweets.gotoAndStop(2); } Step 13: Initializing Our Game Once the Tweets are ready we can initialize it; for this we will create our addGame function in our Main class, and in this function we will add our game to the stage so the init function on our Game class gets triggered, we will animate out our title, and we will move away the animation we had for the user to know that the Tweets were being loaded. private function addGame(e:Event):void { addChild(game); TweenLite.to(title, .3, {y:-200, ease:Quad.easeIn}); loadingTweets.alpha = 0; loadingTweets.x = 800; loadingTweets.y = 2300; } Then in our init function for the Game class we will create our first bird, and add a nest (which the player will use to catch the eggs) and a black bar (which will hold the Tweets that the user has catched) - so let's create those movie clips. Our nest needs to have graphics and a invisible movie clip that we will use to test collisions with the eggs; the black bar needs just a basic title. We will need to export both of them for AS use. private function init(e:Event):void { this.removeEventListener(Event.ADDED, init); // We set our varible to true so our Main class knows if it has been added or not addedToStage = true; // Set up the position, alpha and animation for our nest object nest.x = 10; nest.y = 497; nest.alpha = 0; TweenLite.to(nest, .5,{alpha:1}); addChild(nest); // Add, position and anomation for the Tweets bar tweetsBar.x = 350; tweetsBar.alpha = 0; TweenLite.to(tweetsBar, .6,{alpha:1}); addChild(tweetsBar); // This is our main loop which will take care of our game and tell whats going on stage.addEventListener(Event.ENTER_FRAME, updateGame); // We will move our nest via keys so we will need to listen to keyboards events stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler); // We will create our first bird which is the begining of the actual game createBird(); // To make this game a bit interesting we will change the dificulty of our game as the user plays it TweenLite.delayedCall(10, changeDifficulty); } With this ready we will now need to work on our birds, our eggs, our Tweets and the main loop for this game. Step 14: Creating Our Birds Our birds will drop our eggs so they are kind of important! So let's create them and animate them. In our createBird function we will create a bird, animate it, and decide when the next bird will be created; besides that we will set up the speed of the bird (to give some variety in the difficulty level they will move faster as the game goes on). private function createBird():void { // Create a new Bird instance from out library var bird:Bird = new Bird(); // This is the time that will pass before the egg is released var time:Number = (Math.random()*1.3)+.5; // We will position out bird out of stage and in random Y position so they look a bit more real bird.x = -100; bird.y = (Math.random()*60) + 50; // Animates the bird and destroys it after it's done animating TweenLite.to(bird, 5, {x: 600, onComplete:killObject, onCompleteParams:[bird]}); addChild(bird); if (! ended) { // We need to tell our bird to release our eggs after a certian time which will be random TweenLite.delayedCall(time, releaseEgg, [bird]); // If the game has no ended we need to create a new bird and depending on the difficulty it will come faster TweenLite.delayedCall(Math.random()*difficulty, createBird); } else { // Since the game has ended we wont need any updates stage.removeEventListener(Event.ENTER_FRAME, updateGame); // If the game has ended we won't want any eggs to be released so we call any calls to that function TweenLite.killTweensOf(releaseEgg); // Besides not letting any eggs come we will delete all the eggs if (eggs.length > 0) { for (var i:int = 0; i < eggs.length; i) { killObject(eggs[i]); eggs.shift(); } } // We will animate out our nest since no more eggs will be catched TweenLite.to(nest, .6,{y:700}); // We will show the score and give the user the option to Tweet it showTweetScore(); } } Step 15: Releasing Eggs Now that we have birds flying around we need them to drop eggs, so in our releaseEgg function we will do that: private function releaseEgg(b:Bird):void { var r:Number = Math.random(); var egg:Egg; // Here we choose if our egg will be a golden eggs or a cracked egg, giving a bit more chance to get a golden egg if (r > 0.45) { // If the user gets a golden egg then we need to assign one egg form our array of golden eggs and refresh the count egg = goldenEggsArray[goldenEggsCount]; goldenEggsCount++; } else { // If the user gets a cracked egg then we need to assign one egg form our array of cracked eggs and refresh the count egg = crackedEggsArray[crackedEggsCount]; crackedEggsCount++; } // Then we will assign the position of the bird that is going to release it egg.x = b.x; egg.y = b.y; // Then we add it to stage and push it to our eggs array so it gets updated addChild(egg); eggs.push(egg); } Step 16: Change Difficulty Over time the difficulty will change; we already made a call for that to happen in our init function, so now we will make that happen: private function changeDifficulty():void { // The first difficulty is set to 3 so if this function is called we will change it so more birds come together and speed up the eggs if (difficulty == 3) { difficulty = 2; speed = 5; // We call this function again so the difficulty chages again TweenLite.delayedCall(10, changeDifficulty); return; } if (difficulty == 2) { difficulty = 1.5; speed = 7; TweenLite.delayedCall(5, changeDifficulty); return; } if (difficulty == 1.5) { difficulty = 1; speed = 8; TweenLite.delayedCall(5, changeDifficulty); return; } // If the difficulty is set to 1 it means that this function has been called some times and that the 30 seconds of this game are gone so it's time to end this game if (difficulty == 1) { ended = true; return; } } Step 17: Getting Things Ready to Move To move our nest we will use our keyboard and our update loop, so we need to tell our game which key is being pressed, for that we already created a couple of variables but now we will add the functionality that will make our nest move. We already set up a couple of event listeners - one for when a key is down and another for when it is released - in our init function, so now let's handle those calls. We will need to use keycodes for this, for more information about those you can visit the Quick Tip about the usage of keycodes private function keyDownHandler(e:KeyboardEvent):void { // When the left or right key is holded we need to set it's value to true // 37 = left // 39 = right if (e.keyCode == 37) { leftKey = true; } if (e.keyCode == 39) { rightKey = true; } } private function keyUpHandler(e:KeyboardEvent):void { // When the left or right key is released we need to set it's value to false // 37 = left // 39 = right if (e.keyCode == 37) { leftKey = false; } if (e.keyCode == 39) { rightKey = false; } } Step 18: Showing Score When the time is gone we will give our user the option to see and share their score, for that we will create a movie clip that states the score and gives the option to share it: Dont forget to assign an instance name to your dynamic text field and to embed the font that you want to use. When your graphic is ready we are good to go and code it; for this we will create a function named showTweetScore in which we will create a new instance of that movie clip, position it, add a message with the score, and give the option to Tweet the score. private function showTweetScore():void { var tweetMessage:TweetMessage = new TweetMessage(); tweetMessage.x = 10; tweetMessage.y = 270; tweetMessage.message_text.text = "You just scored "+score.toString()+" point on Golden Eggs!"; tweetMessage.embedFonts = true; addChild(tweetMessage); TweenLite.from(tweetMessage, .6, {alpha:0}); tweetMessage.tweet_btn.buttonMode = true; tweetMessage.tweet_btn.addEventListener(MouseEvent.CLICK, shareScore); } Step 19: Share Score Once the user clicks on the tweet_btn of our message he or shee will be redirected to a page on Twitter with a prewritten message so they can share their score. To do this we will use another call form the Twitter API - the Tweet button API - for more information about it please visit Twitter's page. For this tutorial we will use just three variables: the text; the URL that we want to share; and "via", which is kind of the bridge that we are using, in this case Activetuts+. The URL that we need to send our user to is, there the user will be able to log in and Tweet about our game. To that URL we must append variables like this: private function shareScore(e:MouseEvent):void { // We need to encode the string var url:String = encodeURI(" just scored "+score.toString()+" points in Golden Eggs!, try to beat me!&url="); // We use _blank so the user can come back and keep playing the game without having to load again the game navigateToURL(new URLRequest(url), "_blank"); } There are some other variables that you can add to your URL, such as recommended accounts and language, but we won't use those because those are for the Tweet button so are useless for this tutorial. But I recommend you to go check them out, as they might come in handy some day. Step 20: Destroy Objects Some times when you create too many variables and objects your application might become slow, so we make use of the garbage collector and tell it what to pick up and what to leave for us to use. Once the eggs get out of stage it means that we don't need them any more (the same is true for our birds) so it's a good practice to get rid of them. We will do this with a function called killObject which we have called already a few times and we will call later on. This function will clear that object and get rid of it; it will take a sprite since we are just going to kill display objects. private function killObject(ob:Sprite):void { // We will remove them from stage and then set them to null so the garbage collector takes care of it ob.parent.removeChild(ob); ob = null; } Besides those objects we might need to get rid of our game instance; in those cases we will kill all the listeners so we dont waste memory on anything. public function killGame():void { if(addedToStage) { stage.removeEventListener(Event.ENTER_FRAME, updateGame); stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler); } } Step 21: Our Game Cycle Our cycle will be one of the most important functions; this will take care of everything that is on stage and keep track of everything. The first thing this function will do is move our nest when the user is pressing the right or left key - keeping in mind that there should be limits for it, so the nest doesn't go out of stage. private function updateGame(e:Event):void { if (nest.x < 250 && rightKey) { nest.x += 5; } if (nest.x > 9 && leftKey) { nest.x -= 5; } } Then we need to take care of our eggs, check whether any have been caught or have moved out of the stage. For that we will need to add the following code to our function: // First we need to check if there are any eggs on stage if (eggs.length > 0) { for (var i:int = 0; i < eggs.length; i++) { // if there are we need to move them so they fall eggs[i].y += speed; // Then we need to check if any of those has been catched by using hitTestObject with the invisible object inside our nest if (eggs[i].hitTestObject(nest.hit)) { // If one egg has been catched then we need to add or substract points if (eggs[i].type == "Golden Egg") { score += 100; } else { score -= 80; } // Then we need to let our Main class know so the score text is changed // We send the score as a parameter of the GameEvent var gameEvent:GameEvent = new GameEvent(GameEvent.SCORE_CHANGE,score.toString()); dispatchEvent(gameEvent); // Then we will show out Tweet in out bar using a class that we will create // We will assign the values to this Tweet from out egg, that's why that class has those properties var tweet:TweetHolder = new TweetHolder(); tweet.user_text.text = eggs[i].user; tweet.tweet_text.text = eggs[i].tweet; tweet.userImg = eggs[i].userImg; tweet.x = 5; tweetsBar.addChild(tweet); // If there are too many Tweets being showed we will need to hide some if (tweetsOnScreen.length > 0) { // first we need to make room for out new tweet for (var a:int = 0; a < tweetsOnScreen.length; a++) { tweetsOnScreen[a].y = tweetsOnScreen[a].y - tweet.height; } // if our first tweet is going to high then we need to fade it out if (tweetsOnScreen[0].y < 100) { // We fade it and them we remove it from stage and from our array of Tweets TweenLite.to(tweetsOnScreen[0], .5,{alpha:0, y:"-100", onComplete:tweetsOnScreen[0].parent.removeChild, onCompleteParams:[tweetsOnScreen[0]]}); tweetsOnScreen.shift(); } // If the new tweet is too long the next one might be too high as well so we need to check and apply the same process if (tweetsOnScreen[0].y < 100) { tweetsOnScreen[0].parent.removeChild(tweetsOnScreen[0]); tweetsOnScreen.shift(); } } // After everything is ready we need to add our new Tweet to our array of tweets tweetsOnScreen.push(tweet); tweet.alpha = 1; tweet.y = 600 - tweet.height - 10; // after we are done it's time to kill that egg killObject(eggs[i]); eggs.splice(i, 1); } // If the Tweet wasn't catched and is out of frame then we should destroy it as well else if (eggs[i].y > 600) { killObject(eggs[i]); eggs.splice(i, 1); } } } Step 22: Creating Tweet Objects For our Tweet objects we will first need an object from our library, which we will export, and to which we will assign a new class to handle the data that is pushed. This movie clip will have a backup image in case the user image can't be loaded, a space for the name of the user who Tweeted it, and a space for the Tweet content. When you create your graphics don't forget to embed the font that you are using. The class that we are going to create will fill the data, resize the text fields, load the publisher's avatar and give the user the posibility to click on the tweet and go to the publisher's profile: package com { import flash.display.*; import flash.events.*; import flash.net.*; public class TweetHolder extends MovieClip { // This will hold the URL of the image so it can be loaded public var userImg:String; public function TweetHolder() { this.addEventListener(Event.ADDED, init); } private function init(e:Event):void { // As we did in our Game class we first added the data and then added this to the stage this.removeEventListener(Event.ADDED, init); // When it's added it resizes the text fields so no space is wasted tweet_text.autoSize = "left"; hit.height = tweet_text.height + tweet_text.y; // Then we load the image and call a function if the image is loaded or is we get an error var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, addImage); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError); loader.load(new URLRequest(userImg)); // We finally make this Tweet clickable and add a function to handle the clicks this.buttonMode = true; this.addEventListener(MouseEvent.CLICK, clickHandler); } private function clickHandler(e:MouseEvent):void { // To go to the user's profile we just need to add the username to Twitter's URL navigateToURL(new URLRequest(""+user_text.text), "_blank"); } private function addImage(e:Event):void { // When the image is added we need to make it look smooth Bitmap(e.currentTarget.content).smoothing = true; // Resize it e.currentTarget.content.height = 40; e.currentTarget.content.width = 40; // And add it to our Tweet holder addChild(e.currentTarget.content); } private function onError(e:Event):void { // If there is an error we just need to catch it // Since we already have a backup image we don't need to do anything if the image is not loaded trace("Image couldnt be loaded"); } } } When we are done with this class everything should be ready to go. Conclusion I hope you guys find this tutorial helpful and find great ways to apply what has been taught! For another example of the usage of this you can visit my site home page at JsCampos.com, or check out some other nice games that use Twitter, such as Tweet Land and Tweet Hunt. Thanks for your time and I hope you liked it, any feedback is well received. Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/golden-eggs-build-a-flash-game-using-twitter-api-calls--active-9686
CC-MAIN-2017-51
refinedweb
6,457
68.2
- What Is a Heap? - Heap Corruptions - Summary In Chapter 5, "Memory Corruption Part I—Stacks," we discussed how stack-based buffer overflows can cause serious security problems for software and how stackbased buffer overflows have been the primary attack angle for malicious software authors. In recent years, however, another form of buffer overflow attack has gained in popularity. Rather than relying on the stack to exploit buffer overflows, the Windows heap manager is now being targeted. Even though heap-based security attacks are much harder to exploit than their stack-based counterparts, their popularity keeps growing at a rapid pace. In addition to potential security vulnerabilities, this chapter discusses a myriad of stability issues that can surface in an application when the heap is used in a nonconventional fashion. Although the stack and the heap are managed very differently in Windows, the process by which we analyze stack- and heap-related problems is the same. As such, throughout this chapter, we employ the same troubleshooting process that we defined in Chapter 5 (refer to Figure 5.1). What Is a Heap? A heap is a form of memory manager that an application can use when it needs to allocate and free memory dynamically. Common situations that call for the use of a heap are when the size of the memory needed is not known ahead of time and the size of the memory is too large to neatly fit on the stack (automatic memory). Even though the heap is the most common facility to accommodate dynamic memory allocations, there are a number of other ways for applications to request memory from Windows. Memory can be requested from the C runtime, the virtual memory manager, and even from other forms of private memory managers. Although the different memory managers can be treated as individual entities, internally, they are tightly connected. Figure 6.1 shows a simplified view of Windows-supported memory managers and their dependencies. Figure 6.1 An overview of Windows memory management architecture As illustrated in Figure 6.1, most of the high-level memory managers make use of the Windows heap manager, which in turn uses the virtual memory manager. Although high-level memory managers (and applications for that matter) are not restricted to using the heap manager, they most typically do, as it provides a solid foundation for other private memory managers to build on. Because of its popularity, the primary focal point in this chapter is the Windows heap manager. When a process starts, the heap manager automatically creates a new heap called the default process heap. Although some processes use the default process heap, a large number rely on the CRT heap (using new/delete and malloc/free family of APIs) for all their memory needs. Some processes, however, create additional heaps (via the HeapCreate API) to isolate different components running in the process. It is not uncommon for even the simplest of applications to have four or more active heaps at any given time. The Windows heap manager can be further broken down as shown in Figure 6.2. Figure 6.2 Windows heap manager Front End Allocator The front end allocator is an abstract optimization layer for the back end allocator. By allowing different types of front end allocators, applications with different memory needs can choose the appropriate allocator. For example, applications that expect small bursts of allocations might prefer to use the low fragmentation front end allocator to avoid fragmentation. Two different front end allocators are available in Windows: - Look aside list (LAL) front end allocator - Low fragmentation (LF) front end allocator With the exception of Windows Vista, all Windows versions use a LAL front end allocator by default. In Windows Vista, a design decision was made to switch over to the LF front end allocator by default. The look aside list is nothing more than a table of 128 singly linked lists. Each singly linked list in the table contains free heap blocks of a specific size starting at 16 bytes. The size of each heap block includes 8 bytes of heap block metadata used to manage the block. For example, if an allocation request of 24 bytes arrived at the front end allocator, the front end allocator would look for free blocks of size 32 bytes (24 user-requested bytes + 8 bytes of metadata). Because all heap blocks require 8 bytes of metadata, the smallest sized block that can be returned to the caller is 16 bytes; hence, the front end allocator does not use table index 1, which corresponds to free blocks of size 8 bytes. Subsequently, each index represents free heap blocks, where the size of the heap block is the size of the previous index plus 8. The last index (127) contains free heap blocks of size 1024 bytes. When an application frees a block of memory, the heap manager marks the allocation as free and puts the allocation on the front end allocator's look aside list (in the appropriate index). The next time a block of memory of that size is requested, the front end allocator checks to see if a block of memory of the requested size is available and if so, returns the heap block to the user. It goes without saying that satisfying allocations via the look aside list is by far the fastest way to allocate memory. Let's take a look at a hypothetical example. Imagine that the state of the LAL is as depicted in Figure 6.3. Figure 6.3 Hypothetical state of the look aside list The LAL in Figure 6.3 indicates that there are 3 heap blocks of size 16 (out of which 8 bytes is available to the caller) available at index 1 and two blocks of size 32 (out of which 24 bytes are available to the caller) at index 3. When we try to allocate a block of size 24, the heap manager knows to look at index 3 by adding 8 to the requested block size (accounting for the size of the metadata) and dividing by 8 and subtracting 1 (zero-based table). The linked list positioned at index 3 contains two available heap blocks. The heap manager simply removes the first one in the list and returns the allocation to the caller. If we try allocating a block of size 16, the heap manager would notice that the index corresponding to size 16 (16+8/8-1=2) is an empty list, and hence the allocating cannot be satisfied from the LAL. The allocation request now continues its travels and is forwarded to the back end allocator for further processing. Back End Allocator If the front end allocator is unable to satisfy an allocation request, the request makes its way to the back end allocator. Similar to the front end allocator, it contains a table of lists commonly referred to as the free lists. The free list's sole responsibility is to keep track of all the free heap blocks available in a particular heap. There are 128 free lists, where each list contains free heap blocks of a specific size. As you can see from Figure 6.2, the size associated with free list[2] is 16, free list[3] is 24, and so on. Free list[1] is unused because the minimum heap block size is 16 (8 bytes of metadata and 8 user-accessible bytes). Each size associated with a free list increases by 8 bytes from the prior free list. Allocations whose size is greater than the maximum free list's allocation size go into index 0 of the free lists. Free list[0] essentially contains allocations of sizes greater than 1016 bytes and less than the virtual allocation limit (discussed later). The free heap blocks in free list[0] are also sorted by size (in ascending order) to achieve maximum efficiency. Figure 6.4 shows a hypothetical example of a free list. Figure 6.4 Hypothetical state of the free lists If an allocation request of size 8 arrives at the back end allocator, the heap manager first consults the free lists. In order to maximize efficiency when looking for free heap blocks, the heap manager keeps a free list bitmap. The bitmap consists of 128 bits, where each bit represents an index into the free list table. If the bit is set, the free list corresponding to the index of the free list bitmap contains free heap blocks. Conversely, if the bit is not set, the free list at that index is empty. Figure 6.5 shows the free list bitmap for the free lists in Figure 6.4. Figure 6.5 Free list bitmap The heap manager maps an allocation request of a given size to a free list bitmap index by adding 8 bytes to the size (metadata) and dividing by 8. Consider an allocation request of size 8 bytes. The heap manager knows that the free list bitmap index is 2 [(8+8)/8]. From Figure 6.5, we can see that index 2 of the free list bitmap is set, which indicates that the free list located at index 2 in the free lists table contains free heap blocks. The free block is then removed from the free list and returned to the caller. If the removal of a free heap block results in that free list becoming empty, the heap manager also clears the free list bitmap at the specific index. If the heap manager is unable to find a free heap block of requested size, it employs a technique known as block splitting. Block splitting refers to the heap manager's capability to take a larger than requested free heap block and split it in half to satisfy a smaller allocation request. For example, if an allocation request arrives for a block of size 8 (total block size of 16), the free list bitmap is consulted first. The index representing blocks of size 16 indicates that no free blocks are available. Next, the heap manager finds that free blocks of size 32 are available. The heap manager now removes a block of size 32 and splits it in half, which yields two blocks of size 16 each. One of the blocks is put into a free list representing blocks of size 16, and the other block is returned to the caller. Additionally, the free list bitmap is updated to indicate that index 2 now contains free block entries of size 16. The result of splitting a larger free allocation into two smaller allocations is shown in Figure 6.6. Figure 6.6 Splitting free blocks As mentioned earlier, the free list at index 0 can contain free heap blocks of sizes ranging from 1016 up to 0x7FFF0 (524272) bytes. To maximize free block lookup efficiency, the heap manager stores the free blocks in sorted order (ascending). All allocations of sizes greater than 0x7FFF0 go on what is known as the virtual allocation list. When a large allocation occurs, the heap manager makes an explicit allocation request from the virtual memory manager and keeps these allocations on the virtual allocation list. So far, the discussion has revolved around how the heap manager organizes blocks of memory it has at its disposal. One question remains unanswered: Where does the heap manager get the memory from? Fundamentally, the heap manager uses the Windows virtual memory manager to allocate memory in large chunks. The memory is then massaged into different sized blocks to accommodate the allocation requests of the application. When the virtual memory chunks are exhausted, the heap manager allocates yet another large chunk of virtual memory, and the process continues. The chunks that the heap manager requests from the virtual memory manager are known as heap segments. When a heap segment is first created, the underlying virtual memory is mostly reserved, with only a small portion being committed. Whenever the heap manager runs out of committed space in the heap segment, it explicitly commits more memory and divides the newly committed space into blocks as more and more allocations are requested. Figure 6.7 illustrates the basic layout of a heap segment. Figure 6.7 Basic layout of a heap segment The segment illustrated in Figure 6.7 contains two allocations (and associated metadata) followed by a range of uncommitted memory. If another allocation request arrives, and no available free block is present in the free lists, the heap manager would commit additional memory from the uncommitted range, create a new heap block within the committed memory range, and return the block to the user. Once a segment runs out of uncommitted space, the heap manager creates a new segment. The size of the new segment is determined by doubling the size of the previous segment. If memory is scarce and cannot accommodate the new segment, the heap manager tries to reduce the size by half. If that fails, the size is halved again until it either succeeds or reaches a minimum segment size threshold—in which case, an error is returned to the caller. The maximum number of segments that can be active within a heap is 64. Once the new segment is created, the heap manager adds it to a list that keeps track of all segments being used in the heap. Does the heap manager ever free memory associated with a segment? The answer is that the heap manager decommits memory on a per-needed basis, but it never releases it. (That is, the memory stays reserved.) As Figure 6.7 depicts, each heap block in a given segment has metadata associated with it. The metadata is used by the heap manager to effectively manage the heap blocks within a segment. The content of the metadata is dependent on the status of the heap block. For example, if the heap block is used by the application, the status of the block is considered busy. Conversely, if the heap block is not in use (that is, has been freed by the application), the status of the block is considered free. Figure 6.8 shows how the metadata is structured in both situations. Figure 6.8 Structure of pre- and post-allocation metadata It is important to note that a heap block might be considered busy in the eyes of the back end allocator but still not being used by the application. The reason behind this is that any heap blocks that go on the front end allocator's look aside list still have their status set as busy. The two size fields represent the size of the current block and the size of the previous block (metadata inclusive). Given a pointer to a heap block, you can very easily use the two size fields to walk the heap segment forward and backward. Additionally, for free blocks, having the block size as part of the metadata enables the heap manager to very quickly index the correct free list to add the block to. The post-allocation metadata is optional and is typically used by the debug heap for additional bookkeeping information (see "Attaching Versus Running" under the debugger sidebar). The flags field indicates the status of the heap block. The most important values of the flags field are shown in Table 6.1. Table 6.1. Possible Block Status as Indicated by the Heap Flag You have already seen what happens when a heap block transitions from being busy to free. However, one more technique that the heap manager employs needs to be discussed. The technique is referred to as heap coalescing. Fundamentally, heap coalescing is a mechanism that merges adjacent free blocks into one single large block to avoid memory fragmentation problems. Figure 6.9 illustrates how a heap coalesce functions. Figure 6.9 Example of heap coalescing When the heap manager is requested to free the heap block of size 32, it first checks to see if any adjacent blocks are also free. In Figure 6.9, two blocks of size 16 surround the block being freed. Rather than handing the block of size 32 to the free lists, the heap manager merges all three blocks into one (of size 64) and updates the free lists to indicate that a new block of size 64 is now available. Care is also taken by the heap manager to remove the prior two blocks (of size 16) from the free lists since they are no longer available. It should go without saying that the act of coalescing free blocks is an expensive operation. So why does the heap manager even bother? The primary reason behind coalescing heap blocks is to avoid what is known as heap fragmentation. Imagine that your application just had a burst of allocations all with a very small size (16 bytes). Furthermore, let's say that there were enough of these small allocations to fill up an entire segment. After the allocation burst is completed, the application frees all the allocations. The net result is that you have one heap segment full of available allocations of size 16 bytes. Next, your application attempts to allocate a block of memory of size 48 bytes. The heap manager now tries to satisfy the allocation request from the segment, fails because the free block sizes are too small, and is forced to create a new heap segment. Needless to say, this is extremely poor use of memory. Even though we had an entire segment of free memory, the heap manager was forced to create a new segment to satisfy our slightly larger allocation request. Heap coalescing makes a best attempt at ensuring that situations such as this are kept at a minimum by combining small free blocks into larger blocks. This concludes our discussion of the internal workings of the heap manager. Before we move on and take a practical look the heap, let's summarize what you have learned. When allocating a block of memory - The heap manager first consults the front end allocator's LAL to see if a free block of memory is available; if it is, the heap manager returns it to the caller. Otherwise, step 2 is necessary. - The back end allocator's free lists are consulted: - If an exact size match is found, the flags are updated to indicate that the block is busy; the block is then removed from the free list and returned to the caller. - If an exact size match cannot be found, the heap manager checks to see if a larger block can be split into two smaller blocks that satisfy the requested allocation size. If it can, the block is split. One block has the flags updated to a busy state and is returned to the caller. The other block has its flags set to a free state and is added to the free lists. The original block is also removed from the free list. - If the free lists cannot satisfy the allocation request, the heap manager commits more memory from the heap segment, creates a new block in the committed range (flags set to busy state), and returns the block to the caller. When freeing a block of memory - The front end allocator is consulted first to see if it can handle the free block. If the free block is not handled by the front end allocator step 2 is necessary. - The heap manager checks if there are any adjacent free blocks; if so, it coalesces the blocks into one large block by doing the following: - The two adjacent free blocks are removed from the free lists. - The new large block is added to the free list or look aside list. - The flags field for the new large block is updated to indicate that it is free. - If no coalescing can be performed, the block is moved into the free list or look aside list, and the flags are updated to a free state. Now it's time to complement our theoretical discussion of the heap manager with practice. Listing 6.1 shows a simple application that, using the default process heap, allocates and frees some memory. Listing 6.1. Simple application that performs heap allocations #include <windows.h> #include <stdio.h> #include <conio.h> int __cdecl wmain (int argc, wchar_t* pArgs[]) { BYTE* pAlloc1=NULL; BYTE* pAlloc2=NULL; HANDLE hProcessHeap=GetProcessHeap(); pAlloc1=(BYTE*)HeapAlloc(hProcessHeap, 0, 16); pAlloc2=(BYTE*)HeapAlloc(hProcessHeap, 0, 1500); // // Use allocated memory // HeapFree(hProcessHeap, 0, pAlloc1); HeapFree(hProcessHeap, 0, pAlloc2); } The source code and binary for Listing 6.1 can be found in the following folders: - Source code: C:\AWD\Chapter6\BasicAlloc - Binary: C:\AWDBIN\WinXP.x86.chk\06BasicAlloc.exe Run this application under the debugger and break on the wmain function. Because we are interested in finding out more about the heap state, we must start by finding out what heaps are active in the process. Each running process keeps a list of active heaps. The list of heaps is stored in the PEB (process environment block), which is simply a data structure that contains a plethora of information about the process. To dump out the contents of the PEB, we use the dt command, as illustrated in Listing 6.2. Listing 6.2. Finding the PEB for a process 0:000> dt _PEB @$peb e90 _PEB_LDR_DATA +0x010 ProcessParameters : 0x00020000 _RTL_USER_PROCESS_PARAMETERS +0x014 SubSystemData : (null) +0x018 ProcessHeap : 0x00080000 +0x01c FastPebLock : 0x7c97e4c0 _RTL_CRITICAL_SECTION +0x020 FastPebLockRoutine : 0x7c901005 +0x024 FastPebUnlockRoutine : 0x7c9010ed +0x028 EnvironmentUpdateCount : 1 +0x02c KernelCallbackTable : (null) +0x030 SystemReserved : [1] 0 +0x034 AtlThunkSListPtr32 : 0 +0x038 FreeList : (null) +0x03c TlsExpansionCounter : 0 +0x040 TlsBitmap : 0x7c97e480 +0x044 TlsBitmapBits : [2] +0x070 CriticalSectionTimeout : _LARGE_INTEGER 0xffffffff`dc3cba00 : 3 +0x08c MaximumNumberOfHeaps : 0x10 +0x090 ProcessHeaps : 0x7c97de80 -> 0x00080000 +0x094 GdiSharedHandleTable : (null) +0x098 ProcessStarterHelper : (null) +0x09c GdiDCAttributeList : 0 +0x0a0 LoaderLock : 0x7c97c0d8 +0x0a4 OSMajorVersion : 5 +0x0a8 OSMinorVersion : 1 +0x0ac OSBuildNumber : 0xa28 +0x0ae OSCSDVersion : 0x200 +0x0b0 OSPlatformId : 2 +0x0b4 ImageSubsystem : 3 7c97e478 2" +0x1f8 ActivationContextData : (null) +0x1fc ProcessAssemblyStorageMap : (null) +0x200 SystemDefaultActivationContextData : 0x00080000 +0x204 SystemAssemblyStorageMap : (null) +0x208 MinimumStackCommit : 0 As you can see, PEB contains quite a lot of information, and you can learn a lot by digging around in this data structure to familiarize yourself with the various components. In this particular exercise, we are specifically interested in the list of process heaps located at offset 0x90. The heap list member of PEB is simply an array of pointers, where each pointer points to a data structure of type _HEAP. Let's dump out the array of heap pointers and see what it contains: 0:000> dd 0x7c97de80 7c97de80 00080000 00180000 00190000 00000000 7c97de90 00000000 00000000 00000000 00000000 7c97dea0 00000000 00000000 00000000 00000000 7c97deb0 00000000 00000000 00000000 00000000 7c97dec0 01a801a6 00020498 00000001 7c9b0000 7c97ded0 7ffd2de6 00000000 00000005 00000001 7c97dee0 ffff7e77 00000000 003a0044 0057005c 7c97def0 004e0049 004f0044 00530057 0073005c The dump shows that three heaps are active in our process, and the default process heap pointer is always the first one in the list. Why do we have more than one heap in our process? Even the simplest of applications typically contains more than one heap. Most applications implicitly use components that create their own heaps. A great example is the C runtime, which creates its own heap during initialization. Because our application works with the default process heap, we will focus our investigation on that heap. Each of the process heap pointers points to a data structure of type _HEAP. Using the dt command, we can very easily dump out the information about the process heap, as shown in Listing 6.3. Listing 6.3. Detailed view of the default process heap 0:000> dt _HEAP 00080000 +0x000 Entry : _HEAP_ENTRY +0x008 Signature : 0xeeffeeff +0x00c Flags : 0x50000062 +0x010 ForceFlags : 0x40000060 +0x014 VirtualMemoryThreshold : 0xfe00 +0x018 SegmentReserve : 0x100000 +0x01c SegmentCommit : 0x2000 +0x020 DeCommitFreeBlockThreshold : 0x200 +0x024 DeCommitTotalFreeThreshold : 0x2000 +0x028 TotalFreeSize : 0xcb +0x02c MaximumAllocationSize : 0x7ffdefff +0x030 ProcessHeapsListIndex : 1 +0x032 HeaderValidateLength : 0x608 +0x034 HeaderValidateCopy : (null) +0x038 NextAvailableTagIndex : 0 +0x03a MaximumTagIndex : 0 +0x03c TagEntries : (null) +0x040 UCRSegments : (null) +0x044 UnusedUnCommittedRanges : 0x00080598 _HEAP_UNCOMMMTTED_RANGE +0x048 AlignRound : 0x17 +0x04c AlignMask : 0xfffffff8 +0x050 VirtualAllocdBlocks : _LIST_ENTRY [ 0x80050 - 0x80050 ] +0x058 Segments : [64] 0x00080640 _HEAP_SEGMENT +0x158 u : __unnamed +0x168 u2 : __unnamed +0x16a AllocatorBackTraceIndex : 0 +0x16c NonDedicatedListLength : 1 +0x170 LargeBlocksIndex : (null) +0x174 PseudoTagEntries : (null) +0x178 FreeLists : [128] _LIST_ENTRY [ 0x829b0 - 0x829b0 ] +0x578 LockVariable : 0x00080608 _HEAP_LOCK +0x57c CommitRoutine : (null) +0x580 FrontEndHeap : 0x00080688 +0x584 FrontHeapLockCount : 0 +0x586 FrontEndHeapType : 0x1 '' +0x587 LastSegmentIndex : 0 '' Once again, you can see that the _HEAP structure is fairly large with a lot of information about the heap. For this exercise, the most important members of the _HEAP structure are located at the following offsets: +0x050 VirtualAllocdBlocks : _LIST_ENTRY Allocations that are greater than the virtual allocation size threshold are not managed as part of the segments and free lists. Rather, these allocations are allocated directly from the virtual memory manager. You track these allocations by keeping a list as part of the _HEAP structure that contains all virtual allocations. +0x058 Segments : [64] The Segments field is an array of data structures of type _HEAP_SEGMENT. Each heap segment contains a list of heap entries active within that segment. Later on, you will see how we can use this information to walk the entire heap segment and locate allocations of interest. +0x16c NonDedicatedListLength As mentioned earlier, free list[0] contains allocations of size greater than 1016KB and less than the virtual allocation threshold. To efficiently manage this free list, the heap stores the number of allocations in the nondedicates list in this field. This information can come in useful when you want to analyze heap usage and quickly see how many of your allocations fall into the variable sized free list[0] category. +0x178 FreeLists : [128] _LIST_ENTRY The free lists are stored at offset 0x178 and contain doubly linked lists. Each list contains free heap blocks of a specific size. We will take a closer look at the free lists in a little bit. +0x580 FrontEndHeap The pointer located at offset 0x580 points to the front end allocator. We know the overall architecture and strategy behind the front end allocator, but unfortunately, the public symbol package does not contain definitions for it, making an in-depth investigation impossible. It is also worth noting that Microsoft reserves the right to change the offsets previously described between Windows versions. Back to our sample application—let's continue stepping through the code in the debugger. The first call of interest is to the GetProcessHeap API, which returns a handle to the default process heap. Because we already found this handle/pointer ourselves, we can verify that the explicit call to GetProcessHeap returns what we expect. After the call, the eax register contains 0x00080000, which matches our expectations. Next are two calls to the kernel32!HeapAlloc API that attempt allocations of sizes 16 and 1500. Will these allocations be satisfied by committing more segment memory or from the free lists? Before stepping over the first HeapAlloc call, let's try to find out where the heap manager will find a free heap block to satisfy this allocation. The first step in our investigation is to see if any free blocks of size 16 are available in the free lists. To check the availability of free blocks, we use the following command: dt _LIST_ENTRY 0x00080000+0x178+8 This command dumps out the first node in the free list that corresponds to allocations of size 16. The 0x00080000 is the address of our heap. We add an offset of 0x178 to get the start of the free list table. The first entry in the free list table points to free list[0]. Because our allocation is much smaller than the free list[0] size threshold, we simply skip this free list by adding an additional 8 bytes (the size of the _LIST_ENTRY structure), which puts us at free list[1] representing free blocks of size 16. 0:000> dt _LIST_ENTRY 0x00080000+0x178+8 [ 0x80180 - 0x80180 ] +0x000 Flink : 0x00080180 _LIST_ENTRY [ 0x80180 - 0x80180 ] +0x004 Blink : 0x00080180 _LIST_ENTRY [ 0x80180 - 0x80180 ] Remember that the free lists are doubly linked lists; hence the Flink and Blink fields of the _LIST_ENTRY structure are simply pointers to the next and previous allocations. It is critical to note that the pointer listed in the free lists actually points to the user-accessible part of the heap block and not to the start of the heap block itself. As such, if you want to look at the allocation metadata, you need to first subtract 8 bytes from the pointer. Both of these pointers seem to point to 0x00080180, which in actuality is the address of the list node we were just dumping out (0x00080000+0x178+8=0x00080180). This implies that the free list corresponding to allocations of size 16 is empty. Before we assume that the heap manager must commit more memory in the segment, remember that it will only do so as the absolute last resort. Hence, the heap manager first tries to see if there are any other free blocks of sizes greater than 16 that it could split to satisfy the allocation. In our particular case, free list[0] contains a free heap block: 0:000> dt _LIST_ENTRY 0x00080000+0x178 [ 0x82ab0 - 0x82ab0 ] +0x000 Flink : 0x00082ab0 _LIST_ENTRY [ 0x80178 - 0x80178 ] +0x004 Blink : 0x00082ab0 _LIST_ENTRY [ 0x80178 - 0x80178 ] The Flink member points to the location in the heap block available to the caller. In order to see the full heap block (including metadata), we must first subtract 8 bytes from the pointer (refer to Figure 6.8). 0:000> dt _HEAP_ENTRY 0x00082ab0-0x8 +0x000 Size : 0xab +0x002 PreviousSize : 0xb +0x000 SubSegmentCode : 0x000b00ab +0x004 SmallTagIndex : 0xee '' +0x005 Flags : 0x14 '' +0x006 UnusedBytes : 0xee '' +0x007 SegmentIndex : 0 '' It is important to note that the size reported is the true size of the heap block divided by the heap granularity. The heap granularity is easily found by taking the size of the _HEAP_ENTY_STRUCTURE. A heap block, the size of which is reported to be 0xab, is in reality 0xb8*8 = 0x558 (1368) bytes. The free heap block we are looking at definitely seems to be big enough to fit our allocation request of size 16. In the debug session, step over the first instruction that calls HeapAlloc. If successful, we can then check free list[0] again and see if the allocation we looked at prior to the call has changed: 0:000> dt _LIST_ENTRY 0x00080000+0x178 [ 0x82ad8 - 0x82ad8 ] +0x000 Flink : 0x00082ad8 _LIST_ENTRY [ 0x80178 - 0x80178 ] +0x004 Blink : 0x00082ad8 _LIST_ENTRY [ 0x80178 - 0x80178 ] 0:000> dt _HEAP_ENTRY 0x00082ad8-0x8 '' Sure enough, what used to be the first entry in free list[0] has now changed. Instead of a free block of size 0xab, we now have a free block of size 0xa6. The difference in size (0x5) is due to our allocation request breaking up the larger free block we saw previously. If we are allocating 16 bytes (0x10), why is the difference in size of the free block before splitting and after only 0x5 bytes? The key is to remember that the size reported must first be multiplied by the heap granularity factor of 0x8. The true size of the new free allocation is then 0x00000530 (0xa6*8), with the true size difference being 0x28. 0x10 of those 0x28 bytes are our allocation size, and the remaining 0x18 bytes are all metadata associated with our heap block. The next call to HeapAlloc attempts to allocate memory of size 1500. We know that free heap blocks of this size must be located in the free list[0]. However, from our previous investigation, we also know that the only free heap block on the free list[0] is too small to accommodate the size we are requesting. With its hands tied, the heap manager is now forced to commit more memory in the heap segment. To get a better picture of the state of our heap segment, it is useful to do a manual walk of the segment. The _HEAP structure contains an array of pointers to all segments currently active in the heap. The array is located at the base _HEAP address plus an offset of 0x58. 0:000> dd 0x00080000+0x58 l4 00080058 00080640 00000000 00000000 00000000 0:000> dt _HEAP_SEGMENT 0x00080640 +0x000 Entry : _HEAP_ENTRY +0x008 Signature : 0xffeeffee +0x00c Flags : 0 +0x010 Heap : 0x00080000 _HEAP +0x014 LargestUnCommittedRange : 0xfd000 +0x018 BaseAddress : 0x00080000 +0x01c NumberOfPages : 0x100 +0x020 FirstEntry : 0x00080680 _HEAP_ENTRY +0x024 LastValidEntry : 0x00180000 _HEAP_ENTRY +0x028 NumberOfUnCommittedPages : 0xfd +0x02c NumberOfUnCommittedRanges : 1 +0x030 UnCommittedRanges : 0x00080588 _HEAP_UNCOMMMTTED_RANGE +0x034 AllocatorBackTraceIndex : 0 +0x036 Reserved : 0 +0x038 LastEntryInSegment : 0x00082ad0 _HEAP_ENTRY The _HEAP_SEGMENT data structure contains a slew of information used by the heap manager to efficiently manage all the active segments in the heap. When walking a segment, the most useful piece of information is the FirstEntry field located at the base segment address plus an offset of 0x20. This field represents the first heap block in the segment. If we dump out this block and get the size, we can dump out the next heap block by adding the size to the first heap block's address. If we continue this process, the entire segment can be walked, and each allocation can be investigated for correctness. 0:000> dt _HEAP_ENTRY 0x00080680 +0x000 Size : 0x303 +0x002 PreviousSize : 8 +0x000 SubSegmentCode : 0x00080303 +0x004 SmallTagIndex : 0x9a '' +0x005 Flags : 0x7 '' +0x006 UnusedBytes : 0x18 '' +0x007 SegmentIndex : 0 '' 0:000> dt _HEAP_ENTRY 0x00080680+(0x303*8) +0x000 Size : 8 +0x002 PreviousSize : 0x303 +0x000 SubSegmentCode : 0x03030008 +0x004 SmallTagIndex : 0x99 '' +0x005 Flags : 0x7 '' +0x006 UnusedBytes : 0x1e '' +0x007 SegmentIndex : 0 '' 0:000> dt _HEAP_ENTRY 0x00080680+(0x303*8)+(8*8) +0x000 Size : 5 +0x002 PreviousSize : 8 +0x000 SubSegmentCode : 0x00080005 +0x004 SmallTagIndex : 0x91 '' +0x005 Flags : 0x7 '' +0x006 UnusedBytes : 0x1a '' +0x007 SegmentIndex : 0 '' ... ... ... '' Let's see what the heap manager does to the segment (if anything) to try to satisfy the allocation request of size 1500 bytes. Step over the HeapAlloc call and walk the segment again. The heap block of interest is shown next. '' Before we stepped over the call to HeapAlloc, the last heap block was marked as free and with a size of 0xa6. After the call, the block status changed to busy with a size of 0xbf (0xbf*8= 0x5f8), indicating that this block is now used to hold our new allocation. Since our allocation was too big to fit into the previous size of 0xa6, the heap manager committed more memory to the segment. Did it commit just enough to hold our allocation? Actually, it committed much more and put the remaining free memory into a new block at address 0x000830c8. The heap manager is only capable of asking for page sized allocations (4KB on x86 systems) from the virtual memory manager and returns the remainder of that allocation to the free lists. The next couple of lines in our application simply free the allocations we just made. What do we anticipate the heap manager to do when it executes the first HeapFree call? In addition to updating the status of the heap block to free and adding it to the free lists, we expect it to try and coalesce the heap block with other surrounding free blocks. Before we step over the first HeapFree call, let's take a look at the heap block associated with that call.7 '' +0x006 UnusedBytes : 0x18 '' +0x007 SegmentIndex : 0 '' 0:000> dt _HEAP_ENTRY 0x000830c8-(0xbf*8)-(0x5*8)-(0xb*8) +0x000 Size : 0xb +0x002 PreviousSize : 5 +0x000 SubSegmentCode : 0x0005000b +0x004 SmallTagIndex : 0 '' +0x005 Flags : 0x7 '' +0x006 UnusedBytes : 0x1c '' +0x007 SegmentIndex : 0 '' 0:000> dt _HEAP_ENTRY 0x000830c8-(0xbf*8) '' The status of the previous and next heap blocks are both busy (Flags=0x7), which means that the heap manager is not capable of coalescing the memory, and the heap block is simply put on the free lists. More specifically, the heap block will go into free list[1] because the size is 16 bytes. Let's verify our theory—step over the HeapFree call and use the same mechanism as previously used to see what happened to the heap block.4 '' +0x006 UnusedBytes : 0x18 '' +0x007 SegmentIndex : 0 '' As you can see, the heap block status is indeed set to be free, and the size remains the same. Since the size remains the same, it serves as an indicator that the heap manager did not coalesce the heap block with adjacent blocks. Last, we verify that the block made it into the free list[1]. I will leave it as an exercise for the reader to figure out what happens to the segment and heap blocks during the next call to HeapFree. Here's a hint: Remember that the size of the heap block being freed is 1500 bytes and that the state of one of the adjacent blocks is set to free. This concludes our overview of the internal workings of the heap manager. Although it might seem like a daunting task to understand and be able to walk the various heap structures, after a little practice, it all becomes easier. Before we move on to the heap corruption scenarios, one important debugger command can help us be more efficient when debugging heap corruption scenarios. The extension command is called !heap and is part of the exts.dll debugger extension. Using this command, you can very easily display all the heap information you could possibly want. Actually, all the information we just manually gathered is outputted by the !heap extension command in a split second. But wait—we just spent a lot of time figuring out how to analyze the heap by hand, walk the segments, and verify the heap blocks. Why even bother if we have this beautiful command that does all the work for us? As always, the answer lies in how the debugger arrives at the information it presents. If the state of the heap is intact, the !heap extension command shows the heap state in a nice and digestible form. If, however, the state of the heap has been corrupted, it is no longer sufficient to rely on the command to tell us what and how it became corrupted. We need to know how to analyze the various parts of the heap to arrive at sound conclusions and possible culprits.
http://www.informit.com/articles/article.aspx?p=1081496&amp;seqNum=3
CC-MAIN-2018-51
refinedweb
6,341
58.01
Comment: Re:A video about MOFs (Score 1) 96 This is a very illustrative video, worth spending a few minutes on if you are new to this topic like I am. This is a very illustrative video, worth spending a few minutes on if you are new to this topic like I am. It might get in the way of computer geeks like you, but won't get the way of most regular computer users. In 12.04, there is a clever mechanism that prevents the launcher from being exposed accidentally. In order to expose the launcher, you have to move the mouse cursor to the left edge, and then sort of press against the edge a bit more. This prevents a single mouse motion, such as the one you do to reach the browser back button from activating the launcher. I've been using it for a while now (on beta releases) and it works really well. With older versions, the launcher behavior was quite annoying, Now it's a real pleasure to use. Well son, my first install was SLS on a 486 (from a bunch of 3.5" floppies) and it ran a pre-1.0 kernel. My first Debian install was also pre-1.0. I kept upgrading a Debian system for longer than 10 years, moving it from computer to computer and from hard disk to hard disk as technology advanced (and money allowed) without ever reinstalling it. I finally ditched it in favor of Ubuntu, and don't regret it at all. I don't want to fiddle with the computer anymore, I want to use it and that's what Ubuntu allows me to do. And, for the record, Unity is not perfect, but isn't an abomination either as many people here want to believe, and I'm currently happily using it on two machines, one netbook and one regular desktop. Now, please draw your own conclusions from this as well... Here in Does the "average" user who picks up a washing machine expect it to be capable of more than what it does out of the box? Does the "average" user who picks up a frying pan expect it to be capable of more than what it does out of the box? Does the "average" user who picks up a screwdriver expect it to be capable of more than what it does out of the box? The answer is a big "no". Now, people here will tell me that computers are way more flexible than washing machines, frying pans and screwdrivers. For a motivated tinkerer with proper mechanical and/or electrical abilities, though, washing machines, frying pans and screwdrivers may appear as full of interesting alternative uses as computers appear to us. So this is not the point, either. Most people aren't looking for flexibility, and they'll happily will trade it for ease of use and convenience as soon as they can. ...and because apt-get install gimp isn't too great a hurdle for anyone who does need it. or opening the "Ubuntu Software Center", typing GIMP in the search box, and pressing the "Install" button, just in case you don't feel so comfortable with command line. You're right! If Venezuela were to attack Columbia, Columbia would wipe the floor with Venezuela, that's for sure! On the other hand, if they were to attack Colombia things may turn out to be different. Still, as a Colombian (that is, from Bogotá, not from Washington) I think this is a very unlikely event. Chávez barks very often about deploying his shiny new war toys against Colombia, but reality is that nobody knows how long he'd be able to keep his war gear running, given the current sad state of Venezuela's finances. But probably the main reason why a war wouldn't make any sense is that Colombia and Venezuela share their history and culture to a large extent. We have really no reason to atack each other, and Chávez's delusions of grandeur aren't going to change this. People like you, who obviously seem to have fun at dealing with things such as ALSA, nVidia drivers, Ratpoison, FreeBSD, upstart, fstab, disk mounting, and GRUB won't probably like Ubuntu. People who don't want to deal with such things, will probably like Ubuntu, because it does a decent job of hiding the technical details from them in such a way that they can actually use the system. So, what you seem to perceive as a lack of transparency in the system design, is deliberate and seen by many as a feature instead of as a defect. It isn't simply a matter of people being superficially drawn to a "nice shiny Gnome". It's actually that they want to use their computer without having to understand the gory technical details of the software installed in it. If a dictator is a miserable failure, thats OK too, since its all open source it just works. This doesn't sound like my actual experience with Debian (yes, back in the days, I used to be a Debian maintainer). Doing anything that requires several packages to be modified in a consistent fashion was always very hard, because a single maintainer who didn't like the idea or who simply wasn't responsive enough was able to stop the whole effort on its tracks. As a government model, Debian looks a lot more like a feudal system, with a myriad of lords who are absolute rulers in their tiny feuds, and who only owe some symbolic allegiance to a distant, and often not very powerful king. Making any significant changes in such a country is of course very difficult, and even traveling there could become a real problem. I once wanted to help Debian become a serious desktop distribution, but for the reasons I mentioned above, this proved to be an exercise in frustration. I ended up becoming inactive as a maintainer and finally moved to Ubuntu as soon as it became available. I haven't looked back ever since. Of course you aren't ever allowed to say any thing wrong about Ubuntu or Canonical after all the times they have virtually claimed to have invented Linux from scratch. [Citation needed] Global variables, lack of namespaces and block scopes are nuances that can be worked around with proper coding practices and a good understanding of the language. Why would you go through all this work when there are languages that provide all of this and much more and are as flexible a JavaScript? Great post! If you'd replace "its" by "it's", it'd be perfect... What this country needs is a good five dollar plasma weapon.
http://slashdot.org/~Martin+Soto/tags/bertoni
CC-MAIN-2014-42
refinedweb
1,131
66.27
Is there any way to combine 2 item number boxes for a repeat region? attached is an example of what I would like my BOM to look like. I would like one item number for two different part numbers. Merging of cells in repeat region is not possible. You could do something close with a little leg work, but no, you can't merge repeat region cells. There are a couple of ways to do this: 1. Use comment cells, add a column to the table that is included in the repeat region, but is reporting no parameters, then from the repeat region menu manager, select "Comments" and pick the first cell in that blank column. You can then right click / properties on each cell in that column and manually add an index to be whatever you want. 2. You can create a relation in the repeat region so you can set the index to whatever you want, including having multiple objects with the same index. From the repeat region menu manager, select Relations and click on the repeat region. Then start a series of if / else statements like: if asm_mbr_part_no == "12345" [the "asm_mbr_" part is required, then add the parameter name, ie "part_no] my_index = "1" else if asm_mbr_part_no == "12346" my_index = "1" else ... endif endif [you need one endif for each if] Then edit the repeat region, so instead of showing rpt.index, change it to rpt.rel.my_index. It's not an elegant solution, doing this for large assemblies would be a pain, and if you change the assembly, you must change the relation also. Either way, you can't merge the cells, but you can give more than one item the same index number. Hope this helps, David This is AUTOCAD not Creo
https://community.ptc.com/t5/Detailing-MBD-MBE/Combining-Bill-of-Material-Columns/m-p/342244
CC-MAIN-2020-29
refinedweb
295
70.02
It's July, and that means our second major release of 2016 has been released into the wild. You'll find some fantastic new controls and a lot of great enhancements. -! - Platform News See What's New in Release 2.0, released July 2016 Top News FlexChart for UWP, WPF, and WinForms We're in the process of a full-scale refactor of all our top controls, and FlexChart (already available in MVC, Wijmo, and Xuni) is now officially released for WPF, UWP, and WinForms. (It's been in beta since May.) Why FlexChart? - Flexible: FlexChart supports our trademark flexibility, allowing you to take the key feature set and customize to fit any requirement. Read more about customizations. - Fast: FlexChart has been engineered to perform faster and better than C1Chart. - Small footprint: FlexChart's assembly tops out at 229 KB for WinForms, 183 KB for WPF, and 218 KB for UWP. - Key Feature set: It includes all the top chart types and elements you'd expect from world-class chart control. Explore chart types and elements. - Universal API: FlexChart has a shared object model; you'll be able to code across platforms with virtually no learning curve. WPF FlexChart's Financial Chart features Read more about FlexChart C1Word Library for UWP, WPF, and WinForms Our C1Word Library for desktop allows you to create, read, and update Word and RTF documents in your apps, through the code. We released the beta version back in March. Add graphics and shapes with C1Word Library Why C1Word? - Extensive APIs to explore all elements of Microsoft Word documents - Formats (Title, Paragraph, Heading, Text) - All fonts and settings - Tables - Images and graphic objects - Work with some shapes - Save content in DOCX or RTF format - Retain page size settings - Draw UI object trees (UWP, WPF) or metafiles (WinForms) - Add bookmarks and hyperlinks - View the generated file in all versions of MSWord and industry-standard document viewers - Ideal for: - Read and edit document content within an app - Generate custom free-flow reports in Microsoft Word - Send data in a standard editable file to non-users of your app Read more about C1Word Library FlexViewer for UWP We continue to grow our reporting and documents offerings, and today we're launching FlexViewer document viewer for UWP. You can display your FlexReports and C1Reports in your app, and we support a variety of features, including: - Built-in parameters - Built-in document pane for bookmarks and pages - Touch support - Full print support - Pixel-perfect rendering - DirectX rendering in desktop and Windows 10 mobile devices - SVG rendering in MVC (currently available in beta) - Rich viewer feature set - Search - Thumbnails - Parameters - Document map - Export to: - HTML - RTF - Excel - Open XML - Word/Excel - TIFF - BMP - PNG - JPEG - GIF FlexViewer for UWP Read more about FlexViewer UWP Licensing Model has Changed UWP Edition licensing model has been changed. Since 2016 v2 release, each application that uses UWP Edition controls requires a unique license key (either evaluation one or fully licensed key). Read more about app-based licensing. Platform Features & Enhancements WinForms New Controls - FlexChart charting control has launched out of beta. Read more about FlexChart.View how to get started. - C1Word Library allows users to read, create, and update RTF and Word files through code. Read more about C1Word Library for WinForms. - A new Map control has been added to WinForms Edition! Read more about Maps. - TreeView for WinForms has been released as a beta control. Read more about TreeView. - The Beta version of FinancialChart control supports eight different specialized financial chart types. Read more about FinancialChart. New Features - C1Report - Added German, Italian and Spanish localizations for most end user-visible strings. - Command - C1TopicBar: Added new property C1TopicLink.Pressed: the value indicates whether the link was pressed. - FlexPivot - It is now possible to use a single field multiple times in any role, in Values, Rows, Columns, Filters. Main uses of this feature are to apply different subtotal functions to a single field at the same time (adding the field to Values) and to group by the same field more than once using different formats (adding the field to Rows or Columns), for example, to see subtotals by year and by quarter using the same date field. - Added Show As feature. It allows to show results as difference or percentage with respect to the previous row or column. Great for showing how measured values are changing from previous year or quarter, compare different measures, and other tasks like that. To specify a Show As calculation, use the new Show As tab of the Field Settings dialog on a value field. - FlexPivot grid now has a context menu with Copy, Show Detail, Field Settings. - Added TotalsBeforeData property. It is False by default, which means that subtotals rows and columns appear after data rows and columns. If it is set to True, subtotals will appear before data. - Weighted group operations (aggregations, subtotals) are now supported in DataEngine. Previously, they were only supported for the DataSource data option. Weighted subtotals are specified using the "Weigh by" combo box on the Subtotals tab of the Field Settings dialog. - Cancelling current calculation is faster now. Current operation is cancelled if the user changes view settings while the engine is calculating. Previously, the engine had to finish the current operation (not necessarily the entire calculation; a calculation usually consists of multiple operations), which in some cases could take considerable time. Now, cancel is virtually immediate in all cases. - DataEngine queries now support custom operations. Both group operations (aggregation) and simple operations can now be custom, user-specified. Programmers can write arbitrary code in a custom class, that will constitute the body of a custom operation. Actions or calculations performed on the data are no longer limited to the stock operations, and performance is kept on the same lightning-speed level because loop over data, including indexing, is performed by DataEngine using the same optimizations as in the stock operations. - Read more about FlexPivot - FlexReport - Added parameterized constructors for TextField class. - Added properties: - float TextFieldBase.TextAngle { get; set; } - float Field.TextAngle { get; set; } - Gets or sets the angle of text rotation within the field. - double TextFieldBase.LineSpacing { get; set; } - double Field.LineSpacing { get; set; } - Gets or sets the line spacing between text lines in the field, in percent. The default is 100 which corresponds to normal line spacing. - TextFitMode TextFieldBase.TextFitMode { get; set; } - Gets or sets a value indicating how the text is fit into field's bounds. - Behavior change: previously, if the type of a field could not be resolved while loading a report, an exception occurred. Now, instead of the exception, a text field is created, with the following text: Unknown field type [XXX]. This field type may not be supported in the current edition of FlexReport. - Read more about FlexReport - FlexGrid - Added C1SuperErrorProvider property to show customizable error tips. - TrueDBGrid - Added BorderColor property and BorderColorChanged event. - GanttView - Added Task.SplitTask(double[] durations) public method. - Added a possibility to change the display format of Duration column in the grid of C1GanttView. - Added C1GanttView.Schedule.CalendarWeekRule property. - Input - Added ComboBoxDataBinding sample. Get the sample. - C1ComboBox: Improved RTL handling. Text in non-RTL languages doesn't change words order when shown with RTL layout. - InputPanel - InputControlHost can be saved to XML and loaded from XML at runtime. - Added the ControlHostFromXmlNode event to C1InputPanel. It allows to detect user's ControlHost in XML tree. - Added the ControlHostNodeName property and Load/SaveControlHostProperties virtual methods to InputControlHost. - Added InputPanelDeserialized and ItemDeserialized events to C1InputPanel. - Ribbon - RibbonControlHost can be saved to XML and loaded from XML at runtime (if supported by ControlHost developer). - Added the ControlHostFromXmlNode event to C1Ribbon and C1StatusBar. It supports detection of user's ControlHost in XML tree. - Added the ControlHostNodeName property and Load/SaveControlHostProperties virtual methods to RibbonControlHost. - Added a few *Deserialized events to C1Ribbon and C1StatusBar to allow subscribing to event handlers after loading from XML. - Schedule - Improved RTL handling. Text in non-RTL languages doesn't change words order when shown with RTL layout. - SuperTooltip - Improved RTL handling. Text in non-RTL languages doesn't change words order when shown with RTL layout. - Added RightToLeft property. Default property value is RightToLeft.Inherit, which means that tooltip will be shown with the same layout as associated control. - TrueDBGrid - Added Add(int[] rows) method for C1TrueDBGrid.SelectedRows collection. This method is used for adding several rows at once for selection. - FlexChart - Added FinancialChart control for visualisation of financial data(BETA license). - Added FinancialChartExplorer sample. - Added TrendLine class for plotting trend lines. It can be used with FlexChart/FinancialChart. - Added Axis.TitleStyle property for customization of axis title appearance. - Added Legend.Orientation property for setting legend orientation. - Added Legend.Title/TitleStyle properties for customization of legend's title. - Added FlexChart.SeriesVisibilityChanged event. The event fires when series visibility was changed. - Added Series.AltStyle property that allows to specify alternative data point appearance. - Read more about FlexChart Breaking Changes - Due to an added reference to the C1.Win assembly, the following controls will experience breaking changes: - GanttView - Input - InputPanel - Ribbon - Schedule - SplitContainer - SuperToolTip - Due to an added reference to the C1.Win.C1SuperTooltip assembly, the following controls will experience breaking changes: - InputPanel - Ribbon - Schedule - SplitContainer - FlexReport - ImageEntry class has been moved to C1.Win.C1SuperTooltip assembly, affecting the following controls: - Ribbon - FlexReport breaking changes - All export filters (classes derived from C1.Win.FlexReport.ExportFilter) were moved to C1.Win.C1Document.4 assembly. The namespace for all those classes has changed to C1.Win.C1Document.Export. The following classes were affected by this change: - FlexReport.GraphicsFilter -> C1.Win.C1Document.Export.GraphicsFilter - FlexReport.ImageFilter -> C1.Win.C1Document.Export.ImageFilter - FlexReport.RasterImageFilter -> C1.Win.C1Document.Export.RasterImageFilter - FlexReport.JpegFilter -> C1.Win.C1Document.Export.JpegFilter - FlexReport.PdfFilter -> C1.Win.C1Document.Export.PdfFilter - ...and so on. - Static properties on C1FlexReport returning static registered instances of supported export providers were moved to the ExportProvider class. (The reason for this change is the addition of the new C1PdfDocumentSource component which uses the same export filters as C1FlexReport.) UWP - UWP Edition licensing model has been changed. Since 2016 v2 release, each application that uses UWP Edition controls requires a unique license key (either evaluation one or fully licensed key). Read more about app-based licensing. New Controls - FlexChart charting control has been released for UWP. Read more about FlexChart. - C1Word Library allows users to read, create, and update RTF and Word files through code. Read more about C1Word Library for UWP. - FlexViewer flexible report viewer has been released. Read more about FlexViewer for UWP. - FlexReport for UWP has been released! This powerful report engine will allow UWP developers to create lightning-fast reports across all Windows 10 devices. Read more about FlexReport for UWP. - The Beta version of the FinancialChart control supports eight different specialized financial chart types. Read more about FinancialChart.. WPF New Controls - FlexChart charting control has been released for WPF. Read more about FlexChart. - C1Word Library allows users to read, create, and update RTF and Word files through code. Read more about C1Word Library for WPF. - Sparkline for WPF offers a new type of chart to track change over time. Read more about Sparkline. - The Beta version of GanttView control has been added to WPF Edition! Read more about GanttView for WPF. - The Beta version of FinancialChart control supports eight different specialized financial chart types. Read more about FinancialChart. New Features & Enhancements - DataGrid - Add methods to get page images in a background thread. - Improved performance when C1DataGrid.ColumnWidth property is AutoStar (default value). Added DataGridColumn.DefaultAutoWidth property which determines default column width used in AutoStar sizing. Read more about the performance of DataGrid for WPF. ASP.NET MVC ASP.NET Core 1.0 Compatible MVC Edition controls are now ASP.NET Core 1.0 compatible. Explore all the Core demos! FlexViewer Beta - The FlexViewer control continues to evolve. - View FlexReport and C1Reports using FlexViewer for MVC - Available in ASP.NET 4.0 and ASP.NET Core 1.0. - In ASP.NET Core you can use HtmlHelpers or TagHelpers. - See the FlexReport Explorer demo. - Use Visual Studio ItemTemplate to rapidly integrate FlexViewer and FlexReport Web API in the same project. This template allows you to quickly integrate FlexReport Web API and FlexViewer in MVC5 applications. In ASP.NET Core, MVC3, and MVC4, it allows configuring FlexViewer control according to the separately hosted FlexReport Web API. - Read more about FlexViewer for MVC. Input New Control: InputDateTime control supports entering and editing date and time values using a single control (as opposed to using an InputDate and an InputTime). Try the InputDateTime Demo. Read the documentation. New Properties: - AutoExpandSelection in DropDown controls determines whether input controls should automatically select whole words/numbers when clicked. This applies to all controls that derive from DropDown, and makes it easier to edit dates, times, colors, etc. Read more. - HeaderPath in ComboBox control allows decoupling the values shown in the combo's input element from the values shown in the drop-down list. Read more. FlexGrid - New Properties: - FlexGrid.IMEEnabled supports IME modes while the grid is not in edit mode. This property benefits sites and applications in Japanese, Chinese, Korean and other languages that require IME support. Read more. - DropDownCssClass makes it easier to style the drop-down list used to edit cells in columns that have DataMaps. Try the multi-column datamap demo. FlexChart - New Properties: - ShowAnimation enables animation in FlexChart. FlexChart now supports over two dozen animation modes. Try the demo. - SupportGestures enables panning and zooming in FlexChart. This property exposes relevant MouseAction property that allows setting either Zooming or Panning along chart axis. Try the demo. - New Scaffolder: - Quickly add FlexChart to the application using scaffolder and configure properties. The scaffolder generates relevant controller and view code to set up FlexChart. FlexSheet - New Sample: - FlexSheet 101: Intro sample for MVC shows you how to get started. - New Scaffolder: - Easily add FlexSheet to applications using a guided wizard that allows you to set different properties of the control. The scaffolder generates relevant controller and view code to set up FlexSheet. Client API IntelliSense In 2016 V1.5, we added TypeScript IntelliSense for MVC controls, and now we have added client side JavaScript IntelliSense capability for the controls. The IntelliSense not only provides code completion but also displays relevant documentation for each property. Read more. ASP.NET Web API Excel - New features: - Add/delete column in Excel inside storage - Add/delete rows in Excel files in storage - Hide/unhide columns and rows of Excel file in storage - Group/ungroup columns of Excel file in storage - Split Excel files into multiple files - Add posted Excel file to storage. - Find text in Excel. Return all sheet names and cell index. - Replace text in Excel sheet - Generate Excel from given template and data DataEngine Beta - Added DataEngine Web API that supports analyzing large number of records using Wijmo5 OLAP. This feature is currently provided as a sample. Try the demo.
https://www.grapecity.com/blogs/componentone-studio-whats-new-in-v2-2016/
CC-MAIN-2019-30
refinedweb
2,482
50.23
Gyrex/Concepts/Http Applications The OSGi HTTP service allows registering servlets and resources which can then be accessed over HTTP. Gyrex makes heavy use of the OSGi HTTP service. All offered services are made available over HTTP. Additionally, an admin interface will be provided which can also be accessed over HTTP(S). In order to support good flexibility and scalable operation the concept of HTTP applications was created. This article describes the concept. Contents HTTP Applications Gyrex allows the definition of HTTP applications. Applications may be defined programmatically using an OSGi service or in a declarative way using the Equinox extension registry to support lazy loading of applications and their resources. Technically speaking, a HTTP application is a collection of servlets and resources. The main advantage compared to dealing with the OSGi HTTP Service directly is that Gyrex HTTP applications define their own URL space. Thus, servlets and resources are not mounted directly into the global namespace but into the namespace of the application. Applications operate in a tenant-specific context. A separate instances of an application will be created per context. This allows operating multiple versions of the same application in parallel. For example, each tenant can run its own version and a tenant can also run different instances to allow concepts like staging/production. Mount Points Gyrex offers applications which run in a tenant-specific context. Thus, multiple instances of the same application may be running. Each instance may expose differences in its behavior and functionality depending on the context it is running in. When a HTTP request is received the platform must be able to quickly detect (a) the application and (b) the context. In order to achieve this, the concept of mounts will be used. A mount is the binding of an URL to an application instance. The URL typically consists of a protocol, domain name, port and a path (eg.). Path and port may be optional. If no path is provided, the "root" path (i.e. "/") will be used. If no specific port is provided, it will accept all ports. Everything below a mount point is intended to be controlled by the application. The allowed URL protocols are http and https. An application typically consists of two mount points – a confidential and a non-confidential mount point. The confidential mount point guarantees that data be transmitted so as to prevent other entities from observing the contents of the transmission. Gyrex will analyze incoming HTTP requests to read the protocol, domain name, port and the path for discovering the application instance bound to a specific context. The path matching will happen after domain matching. A prefix matching is applied following the behavior of the HTTP Service specification. For domain names, a suffix matching will be applied. This allows to capture requests to sub-domains. The longest matching domain wins. For example, an application mount to "shop.somedomain.com" will also receive requests to the "" sub-domain if there is no other application mounted to that sub-domain. A network operator must ensure that all requests targeted at a HTTP application instance will reach the Gyrex cluster. A network operator must also ensure that confidential guarantees are preserved when routing the request to the Gyrex cluster. HTTP Integration HTTP Headers Gyrex may support HTTP headers which allow to specify the original incoming URL if any system in front of Gyrex does not allow passing the original request. The following headers shall be supported. X-Gyrex-OriginalURL X-Gyrex-ClientIP X-Gyrex-Key X-Gyrex-OriginalURL .. the original, complete URL. X-Gyrex-ClientIP .. the IP address of the client. X-Gyrex-Key .. the key which identifies the source submitting the HTTP header. If no key or an invalid key is provided, Gyrex may reject the request or ignore the headers. HTTP Service Scenarios Gyrex will support the following HTTP Service scenarios. - Single HTTP Service - Multiple HTTP Services Single HTTP Service .. a single HTTP Service instance is running and receiving all requests (eg. Servlet Bridge or single Jetty instance). Multiple HTTP Services .. multiple HTTP Service instances are running and each instance is receiving a specific set of requests (eg. HTTPS for different domains). Typically, this scenario may be used to provide better encapsulation between different contexts. In both scenarios a single request handling servlet is registered with the service instance. The request handler is registered at the root alias. It is also assumed that the service may be used exclusively by Gyrex. However, this assumption is not strictly enforced. Gyrex may support the administration/configuration of HTTP Services using very specific service implementations (eg. the Equinox Jetty based HTTP Service). It may also possible to offer a very deep integration with HTTP containers for best performance. However, it’s out of scope of this document to describe such implementation details. HTTPS The main issue with TLS/SSL is that it requires a channel (separate IP/port combination) for each domain. This makes administration not easier. Only recommendations can be given at this time. For example, to make things easier wildcard certificates may be used. But this topic is more related to service administration and may not even touch the platform if a third-party system (eg. SSL Accelerator proxy) is placed in front of Gyrex to handle the issue. However, Gyrex will support the integration with those systems to assist network operators with the operation in those environments. HTTP Session The final goal is to provide complete session isolation between applications. An extensible session manager will allow to provide application specific session handling. For example, one application may want to persist session state into a repository. Another application may not need sessions at all for scalability purposes.
https://wiki.eclipse.org/Gyrex/Concepts/Http_Applications
CC-MAIN-2017-04
refinedweb
948
50.43
#include <deal.II/lac/sparse_vanka.h> Point-wise Vanka preconditioning. This class does Vanka preconditioning on a point-wise base. Vanka preconditioners are used for saddle point problems like Stokes' problem or problems arising in optimization where Lagrange multipliers occur and the Newton method matrix has a zero block. With these matrices the application of Jacobi or Gauss-Seidel methods is impossible, because some diagonal elements are zero in the rows of the Lagrange multiplier. The approach of Vanka is to solve a small (usually indefinite) system of equations for each Langrange multiplier variable (we will also call the pressure in Stokes' equation a Langrange multiplier since it can be interpreted as such). Objects of this class are constructed by passing a vector of indices of the degrees of freedom of the Lagrange multiplier. In the actual preconditioning method, these rows are traversed in the order in which the appear in the matrix. Since this is a Gauß-Seidel like procedure, remember to have a good ordering in advance (for transport dominated problems, Cuthill-McKee algorithms are a good means for this, if points on the inflow boundary are chosen as starting points for the renumbering). For each selected degree of freedom, a local system of equations is built by the degree of freedom itself and all other values coupling immediately, i.e. the set of degrees of freedom considered for the local system of equations for degree of freedom i is i itself and all j such that the element (i,j) is a nonzero entry in the sparse matrix under consideration. The elements (j,i) are not considered. We now pick all matrix entries from rows and columns out of the set of degrees of freedom just described out of the global matrix and put it into a local matrix, which is subsequently inverted. This system may be of different size for each degree of freedom, depending for example on the local neighborhood of the respective node on a computational grid. The right hand side is built up in the same way, i.e. by copying all entries that coupled with the one under present consideration, but it is augmented by all degrees of freedom coupling with the degrees from the set described above (i.e. the DoFs coupling second order to the present one). The reason for this is, that the local problems to be solved shall have Dirichlet boundary conditions on the second order coupling DoFs, so we have to take them into account but eliminate them before actually solving; this elimination is done by the modification of the right hand side, and in the end these degrees of freedom do not occur in the matrix and solution vector any more at all. This local system is solved and the values are updated into the destination vector. Remark: the Vanka method is a non-symmetric preconditioning method. This little example is taken from a program doing parameter optimization. The Lagrange multiplier is the third component of the finite element used. The system is solved by the GMRES method. At present, the local matrices are built up such that the degree of freedom associated with the local Lagrange multiplier is the first one. Thus, usually the upper left entry in the local matrix is zero. It is not clear to me (W.B.) whether this might pose some problems in the inversion of the local matrices. Maybe someone would like to check this. <float> and <double>; others can be generated in application programs (see the section on Template instantiations in the manual). Definition at line 34 of file sparse_vanka.h. Declare type for container size. Definition at line 137 of file sparse_vanka.h. Constructor. Does nothing. Call the initialize() function before using this object as preconditioner (vmult()). Constructor. Gets the matrix for preconditioning and a bit vector with entries true for all rows to be updated. A reference to this vector will be stored, so it must persist longer than the Vanka object. The same is true for the matrix. The matrix M which is passed here may or may not be the same matrix for which this object shall act as preconditioner. In particular, it is conceivable that the preconditioner is build up for one matrix once, but is used for subsequent steps in a nonlinear process as well, where the matrix changes in each step slightly. If conserve_mem is false, then the inverses of the local systems are computed now; if the flag is true, then they are computed every time the preconditioner is applied. This saves some memory, but makes preconditioning very slow. Note also, that if the flag is false, then the contents of the matrix M at the time of calling this constructor are used, while if the flag is true, then the values in M at the time of preconditioning are used. This may lead to different results, obviously, of M changes. The parameter n_threads determines how many threads shall be used in parallel when building the inverses of the diagonal blocks. This parameter is ignored if not in multithreaded mode. Destructor. Delete all allocated matrices. If the default constructor is used then this function needs to be called before an object of this class is used as preconditioner. For more detail about possible parameters, see the class documentation and the documentation of the SparseVanka::AdditionalData class. After this function is called the preconditioner is ready to be used (using the vmult function of derived classes). Do the preconditioning. This function takes the residual in src and returns the resulting update vector in dst. Apply transpose preconditioner. This function takes the residual in src and returns the resulting update vector in dst. Return the dimension of the codomain (or range) space. Note that the matrix is of dimension \(m \times n\). Return the dimension of the domain space. Note that the matrix is of dimension \(m \times n\). Apply the inverses corresponding to those degrees of freedom that have a true value in dof_mask, to the src vector and move the result into dst. Actually, only values for allowed indices are written to dst, so the application of this function only does what is announced in the general documentation if the given mask sets all values to zero The reason for providing the mask anyway is that in derived classes we may want to apply the preconditioner to parts of the matrix only, in order to parallelize the application. Then, it is important to only write to some slices of dst, in order to eliminate the dependencies of threads of each other. If a null pointer is passed instead of a pointer to the dof_mask (as is the default value), then it is assumed that we shall work on all degrees of freedom. This is then equivalent to calling the function with a vector<bool>(n_dofs,true). The vmult of this class of course calls this function with a null pointer Determine an estimate for the memory consumption (in bytes) of this object. Compute the inverses of all selected diagonal elements. Compute the inverses at positions in the range [begin,end). In non-multithreaded mode, compute_inverses() calls this function with the whole range, but in multithreaded mode, several copies of this function are spawned. Compute the inverse of the block located at position row. Since the vector is used quite often, it is generated only once in the caller of this function and passed to this function which first clears it. Reusing the vector makes the process significantly faster than in the case where this function re-creates it each time. Make the derived class a friend. This seems silly, but is actually necessary, since derived classes can only access non-public members through their this pointer, but not access these members as member functions of other objects of the type of this base class (i.e. like x.f(), where x is an object of the base class, and f one of it's non-public member functions). Now, in the case of the SparseBlockVanka class, we would like to take the address of a function of the base class in order to call it through the multithreading framework, so the derived class has to be a friend. Definition at line 367 of file sparse_vanka.h. Pointer to the matrix. Definition at line 297 of file sparse_vanka.h. Conserve memory flag. Definition at line 302 of file sparse_vanka.h. Indices of those degrees of freedom that we shall work on. Definition at line 307 of file sparse_vanka.h. Number of threads to be used when building the inverses. Only relevant in multithreaded mode. Definition at line 313 of file sparse_vanka.h. Array of inverse matrices, one for each degree of freedom. Only those elements will be used that are tagged in selected. Definition at line 319 of file sparse_vanka.h. The dimension of the range space. Definition at line 324 of file sparse_vanka.h. The dimension of the domain space. Definition at line 329 of file sparse_vanka.h.
http://www.dealii.org/developer/doxygen/deal.II/classSparseVanka.html
CC-MAIN-2017-43
refinedweb
1,508
62.98
A. In most applications, the RTC is used primarily to preserve a valid time even during periods where the primary power supply is unavailable. For this reason, these systems include some type of backup battery (usually a CR2032) driving the RTC. In this case you obviously can’t derive the RTC clock from HSE/HSI as these clocks aren’t active when the primary power source isn’t available. The LSI oscillator comes for free with the device, however it has a major problem that most users aren’t aware of: It has extraorbitant tolerance values: According to the STM32F407 datasheet (Table 34: LSI oscillator characteristics), the actual crystal frequency ranges from 17 to 47 kHz with a nominal value of 32 kHz. This is equivalent to a tolerance of -53.1 / +46.8 percent points, or more than 460000 ppm. I can’t think of any real world application that can deal with this magnitude of tolerance. Although the tolerance given is over the full -40 to +105° temperature range, I can confirm that is higher than +-25% at room temperature. The LSE oscillator is the only option left. So remember to include a 32.768 kHz crystal in your design. For this specific use I believe that crystal oscillators are not the right choice because of their relatively high power consumption. There are some major problems left: How to initially get the current timestamp onto the device (depends on your deployment process and is usually not an issue) and how to keep the device synced with an external clock source. The latter is especially relevant when multiple devices need to be kept in sync and/or a near-monotonic clock source is required. Even with only one percent clock drift, the RTC datetime will drift by more than three days over a single year. For applications connected to the internet or to any other computer network, the lwIP contrib repository provides a full SNTP client. SNTP is a less accurate version of the NTP protocol which can still be used with any normal NTP server. However, the library is lacking the most basic documentation. Therefore, I provide an example of how to use it in conjunction with the ChibiOS RTCD1 driver. The header shown here replaces the sntp.h header that comes with the library. It includes the compile-time configuration required to work with the RTCD1 driver. For this example I chose the NTP server swisstime.ethz.ch because it has a good ping from my location. I recommend you select an appropriate server from the NTP pool. #ifndef __SNTP_H__ #define __SNTP_H__ #ifdef __cplusplus extern "C" { #endif //Custom configuration #include <hal.h> #include <chrtclib.h> #define SNTP_SERVER_ADDRESS "82.197.164.46" /* swisstime.ethz.ch */ #define SNTP_UPDATE_DELAY 90000 /* SNTP update every 90 seconds */ //ChibiOS RTC drivers #define SNTP_SET_SYSTEM_TIME(sec) rtcSetTimeUnixSec(&RTCD1, (sec)) #define SNTP_GET_SYSTEM_TIME(sec, us) \ do{uint64_t time = rtcGetTimeUnixUsec(&RTCD1);\ (sec) = time / 1000000;\ (us) = time % 1000000;}while(0) void sntp_init(void); void sntp_stop(void); #ifdef __cplusplus } #endif #endif /* __SNTP: Simon Goldschmidt (lwIP raw API part) * Modified by Uli Koehler for ChibiOS (2014) */ The configuration is pretty basic and sntp.c supports some quite useful features that aren’t configure here — most notably, support for multiple NTP servers. The second step is to configure lwIP properly. This is not a tutorial on lwIP and I assume the reader already knows how the stack works (if not, this article is probably not the best place to start). In order to avoid issues with significant deviations from ideal monotonic clocks, this sample sends SNTP requests every 90 seconds, overriding the default 60 minutes. Which one is better suited entirely depends on your application. There are two common pitfalls that might be encountered, both of which are located in the lwipopts.h header: Firstly, the SNTP client permanently consumes an UDP PCB. Make sure to appropriately increase the MEMP_NUM_UDP_PCB value. Needless to say, you need to enable UDP in order for SNTP to work. Secondly, the SNTP client calls the send function repeatedly by using the lwIP sys_timeout() feature. The default options for the number of supported concurrent timeouts is quite limited and will probably not be sufficient. I recommend to increase the MEMP_NUM_SYS_TIMEOUTvalue by at least one. Once these requirements are met, simply call sntp_init(); after initializing the lwIP thread and event loop. If your configuration is correct, the RTC will be updated when the SNTP responses are received. DO NOT call sntp_init() repeatedly, it will call the send function using the lwIP eventloop by itself.. Note that STM32F4 devices have a millisecond-accuracy RTC. SNTP will only rarely provide an accuracy of better than 1 millisecond. Therefore, the millisecond RTC value might not be significant. If the application crashes, it’s likely that some lwIP limits have been exceeded. In this case, refer to this previous TechOverflow articledescribing in detail how to add ARM hardware breakpointing to ChibiOS and LWIP assertions.
https://techoverflow.net/2014/11/01/using-the-lwip-sntp-client-with-chibios/
CC-MAIN-2018-05
refinedweb
822
55.24
12 January 2012 22:42 [Source: ICIS news] WASHINGTON (ICIS)--?xml:namespace> The department said retail spending last month was at a seasonally adjusted pace of $400.6bn (€316.5bn), just 0.1% higher than the November level. The flat sales figures for December were seen as disappointing by economists, many of whom had predicted a 0.3% bump in consumer buying amid the peak holiday shopping period of the year. Consumer spending is the principal driving force of the Although the December numbers were well below expectations, the department noted that retail sales during the critical last three months of the year were up by 7% from the same period in 2010. Citing the three-month year-end figures, the National Retail Federation (NRF) said the data was “welcome news for an economic recovery that continues to be sluggish”. NRF president Matthew Shay said while “the economy still has a critical hold on consumers’ purchase decisions, this strength in spending could continue into 2012”. (
http://www.icis.com/Articles/2012/01/12/9523413/us-retail-sales-flat-in-dec-but-full-year-spending-rises-by-7.7.html
CC-MAIN-2014-52
refinedweb
165
53.92
gnutls_record_set_max_empty_records — API function #include <gnutls/gnutls.h> is a gnutls_session_t structure. is the desired value of maximum empty records that can be accepted in a row. Used to set the maximum number of empty fragments that can be accepted in a row. Accepting many empty fragments is useful for receiving length−hidden content, where empty fragments filled with pad are sent to hide the real length of a message. However, a malicious peer could send empty fragments to mount a DoS attack, so as a safety measure, a maximum number of empty fragments is accepted by default. If you know your application must accept a given number of empty fragments in a row, you can use this function to set the desired:
https://man.linuxexplore.com/htmlman3/gnutls_record_set_max_empty_records.3.html
CC-MAIN-2021-31
refinedweb
122
62.68
Xacobeo::UI::Window - Main window of Xacobeo. use Gtk2 qw(-init); use Xacobeo::UI::Window; my $xacobeo = Xacobeo::UI::Window->new(); $xacobeo->signal_connect(destroy => sub { Gtk2->main_quit(); }); $xacobeo->show_all(); Gtk2->main(); The application's main window. This widget is a Gtk2::Window. The following properties are defined: The source view where the document's content is displayed. The widget displaying the results of a search The UI Manager used by this widget. The widget displaying the namespaces of the current document. The entry where the XPath expression will be edited. The window's statusbar. The notbook widget at the bottom of the window. The button starting a search. A reference to the main configuration singleton. The UI Manager used by this widget. The following methods are available: Creates a new instance. This is simply the parent's constructor. Load a new file into the application. The new document will be parsed and displayed in the window. Parameters: The file to load. The type of document to load: xml or html. Defaults to xml if no value is provided. Load a new document into the application. The document will be parsed and displayed in the window. Parameters: The document to load. Set the XPath expression to display in the XPath text area. The expression is not evaluated. Parameters: The XPath expression to set.
http://search.cpan.org/~potyl/Xacobeo-0.15/lib/Xacobeo/UI/Window.pm
CC-MAIN-2016-44
refinedweb
222
63.15
Hello, I'm trying to have a STL set of pointer-to-member-functions in my class. I already know how to declare and define pointers-to-functions and use them with an ordinary array, but using the STL containers has proven problematic. It kind of works with vectors if I choose to use .push_back(), but .insert() gives me errors. That said, I need to use set. So can anyone tell me how to fix this sample code? ThanksThanksCode:#include <iostream> #include <set> using namespace std; class test{ public: test(){ p.insert( &test::g ); } int f(){ cout << " f() " << endl; } int g(){ cout << " g() " << endl; } int h(){ cout << " h() " << endl; } set< int(test::*)() > p; }; int main(int argc, char *argv[]){ test a_test; ((a_test).*(a_test.begin()))(); }
https://cboard.cprogramming.com/cplusplus-programming/110041-set-pointer-methods.html
CC-MAIN-2017-43
refinedweb
124
82.75
The Python runtime sees all Python objects as variables of type PyObject*. A PyObject is not a very magnificent object - it just contains the refcount and a pointer to the object's ``type object''. This is where the action is; the type object determines which (C) functions get called when, for instance, an attribute gets looked up on an object or it is multiplied by another object. I call these C functions ``type methods'' to distinguish them from things like [].append (which I will call ``object methods'' when I get around to them). So, if you want to define a new object type, you need to create a new type object. This sort of thing can only be explained by example, so here's a minimal, but complete, module that defines a new type: #include <Python.h> staticforward PyTypeObject noddy_NoddyType; typedef struct { PyObject_HEAD } noddy_NoddyObject;; } static void noddy_noddy_dealloc(PyObject* self) { PyObject_Del */ }; static PyMethodDef noddy_methods[] = { {"new_noddy", noddy_new_noddy, METH_VARARGS, "Create a new Noddy object."}, {NULL, NULL, 0, NULL} }; DL_EXPORT(void) initnoddy(void) { noddy_NoddyType.ob_type = &PyType_Type; Py_InitModule("noddy", noddy_methods); } Now that's quite a bit to take in at once, but hopefully bits will seem familiar from the last chapter. The first bit that will be new is: staticforward PyTypeObject noddy_NoddyType; This names the type object that will be defining further down in the file. It can't be defined here because its definition has to refer to functions that have no yet been defined, but we need to be able to refer to it, hence the declaration. The staticforward is required to placate various brain dead compilers. typedef struct { PyObject_HEAD } noddy_NoddyObject; This is what a Noddy object will contain. In this case nothing more than every Python object contains - a refcount and a pointer to a type object. These are the fields the PyObject_HEAD macro brings in. The reason for the macro is to standardize the layout and to enable special debugging fields to be brought in debug builds. For contrast typedef struct { PyObject_HEAD long ob_ival; } PyIntObject; is the corresponding definition for standard Python integers. Next up is:; } This is in fact just a regular module function, as described in the last chapter. The reason it gets special mention is that this is where we create our Noddy object. Defining PyTypeObject structures is all very well, but if there's no way to actually create one of the wretched things it is not going to do anyone much good. Almost always, you create objects with a call of the form: PyObject_New(<type>, &<type object>); This allocates the memory and then initializes the object (sets the reference count to one, makes the ob_type pointer point at the right place and maybe some other stuff, depending on build options). You can do these steps separately if you have some reason to -- but at this level we don't bother. We cast the return value to a PyObject* because that's what the Python runtime expects. This is safe because of guarantees about the layout of structures in the C standard, and is a fairly common C programming trick. One could declare noddy_new_noddy to return a noddy_NoddyObject* and then put a cast in the definition of noddy_methods further down the file -- it doesn't make much difference. Now a Noddy object doesn't do very much and so doesn't need to implement many type methods. One you can't avoid is handling deallocation, so we find static void noddy_noddy_dealloc(PyObject* self) { PyObject_Del(self); } This is so short as to be self explanatory. This function will be called when the reference count on a Noddy object reaches 0 (or it is found as part of an unreachable cycle by the cyclic garbage collector). PyObject_Del() is what you call when you want an object to go away. If a Noddy object held references to other Python objects, one would decref them here. Moving on, we come to the crunch -- the type */ }; Now if you go and look up the definition of PyTypeObject in object.h you'll see that it has many, many more fields that the definition above. The remaining fields will be filled with zeros by the C compiler, and it's common practice to not specify them explicitly unless you need them. This is so important that I'm going to pick the top of it apart still further: PyObject_HEAD_INIT(NULL) This line is a bit of a wart; what we'd like to write is: PyObject_HEAD_INIT(&PyType_Type) as the type of a type object is ``type'', but this isn't strictly conforming C and some compilers complain. So instead we fill in the ob_type field of noddy_NoddyType at the earliest oppourtunity -- in initnoddy(). 0, XXX why does the type info struct start PyObject_*VAR*_HEAD?? "Noddy", The name of our type. This will appear in the default textual representation of our objects and in some error messages, for example: >>> "" + noddy.new_noddy() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: cannot add type "Noddy" to string sizeof(noddy_NoddyObject), This is so that Python knows how much memory to allocate when you call PyObject_New. 0, This has to do with variable length objects like lists and strings. Ignore for now... Now we get into the type methods, the things that make your objects different from the others. Of course, the Noddy object doesn't implement many of these, but as mentioned above you have to implement the deallocation function. noddy_noddy_dealloc, /*tp_dealloc*/ From here, all the type methods are nil so I won't go over them yet - that's for the next section! Everything else in the file should be familiar, except for this line in initnoddy: noddy_NoddyType.ob_type = &PyType_Type; This was alluded to above -- the noddy_NoddyType object should have type ``type'', but &PyType_Type is not constant and so can't be used in its initializer. To work around this, we patch it up in the module initialization. That's it! All that remains is to build it; put the above code in a file called noddymodule.c and from distutils.core import setup, Extension setup(name = "noddy", version = "1.0", ext_modules = [Extension("noddy", ["noddymodule.c"])]) in a file called setup.py; then typing $ python setup.py build%$ at a shell should produce a file noddy.so in a subdirectory; move to that directory and fire up Python -- you should be able to import noddy and play around with Noddy objects. That wasn't so hard, was it? See About this document... for information on suggesting changes.See About this document... for information on suggesting changes.
http://python.org/doc/2.2/ext/dnt-basics.html
crawl-002
refinedweb
1,094
62.78
I'm thinking of building a 24 1TB disk NAS box, but I'm not sure what the best drive configuration is. I'm looking at using the areca ARC-1280ML-2G controller, and hanging all 24 drives off of it. I'd like it all to be mounted as one volume, due to the type of data we're storing on it. One crazy idea we had was to configure 6 4-disk RAID 5 volumes, then do software RAID 5 over those 6 volumes. That would mean any one volume could die on us and we'd still not lose data. I should note that this is an R&D project, we've got an upcoming application where we'll be needing tens of terabytes of storage to be fast and highly available. But for the initial R&D phase we can accept some risk. What is the best solution to this type of configuration? With 24 1 TB disks, it's likely that more than one will fail at the same time (or within the time it takes to rebuild the volume after a first failure), so I'm having trouble finding a good solution. There is already a RAID level for what you want; it's called RAID. So, for every scan of your passes of your 24Tb drive, statistically you will encounter at least 2 single bit errors. Each of those errors will trigger a RAID5 rebuild, and worse, during rebuild a second error will cause a double fault. This is precisely my everyday work... building Linux storage servers. wow, RAID5 over RAID5? Want to discuss performance problems? You'll have tons. The host you hang those off of will have kittens computing parity, writing that parity to 3 drives and then computing the parity of THAT parity and writing it to the 4th drive of that set. WOW! Lets talk about RAID10. It's essentially RAID 1, but you divide up your drives in half and mirror that. It's fault tolerant in that you can lose 2 drives and still be fine, plus the performance is outstanding. If you don't need an insane amount of space, but you've got a 24TB array sitting around with nothing better to do, but it absolutely positively has to be up, then you might consider RAID60. It's essentially RAID6 using mirrored sets of drives. You'll lose around half your drives, and performance will be bad, but you will be nearly guaranteed that the data will be there. Really, I'd go with RAID10. It performs well and works fine. I second Evan's opinion that you probably shouldn't make giant RAID sets out of that many disks, because as he says, things like fsck and chkdsk will take forever, and but more importantly in my mind, because the statistical likelihood of a read error goes up as individual disk size does. I'd recommend 7-10 disks per set. You could create 3 very decently sized RAID volumes with that number of spindles. Whichever you pick, remember to leave a couple of disks at hot spares, so that you can start rebuilding immediately, rather than having the array wait for you to replace them. As soon as a disk dies, the clock starts ticking for another one to go. Why not RAID 1+0? It's all handled at the controller level... I know that you said "R&D", but you also said "highly available". I would question the "savings" of a DIY solution versus purchasing off-the-shelf SAN gear to do this. When things go wrong with your DIY solution you're going to be in the unenviable position of having no one to contact for help. What does downtime cost you per hour? You can eat up the cost of some medium-tier SAN gear pretty quickly in downtime expense, ignoring the expense associated with out-right loss of data. Regardless of what you do about the underlying disk, I wouldn't create a single filesystem that large. Filesystem corruption is a real possibility (RAID controller issue, OS bugs, etc). In a volume that large, a filesystem check is going to take forever. I'd highly recommend using multiple volumes that can be logically combined to appear as a single filesytem (through various means-- you didn't mention the OS, so I can't give you specific ideas). If you have some filesystem corruption you will lose part of the logical volume, but you'll still be "up". As an example: In a Windows world, running CHKDSK on a 20TB NTFS volume filled with files is going to be SLOW. In that kind of environment, I'd create multiple smaller NTFS volumes and logically combine them into a single namespace with DFS. wazoox, answers are good I don't have the rep to give him more plus points, but I would add the following. RAID 6 or at least 2 live parity discs per 10 discs, 16 at most that is if you can take around a day when performance will be impacted by your raid rebuild. If you can't live with the degradation then its going to have to be mirrored stripes. If you are going the linux route, I would either use a hardware raid card ( with battery backup ) or have a raid controller in the disc enclosure. I agree that xfs is the filesystem of choice on Linux, however be aware that filesystems of around 50TB on xfs take more than 16GB of RAM if you need to run xfs_check. I would seriously consider a good NAS box such as a NetApp as they are a lot less work long term, it depends how much your/the storage admins time is worth to the company. Getting nfs/samba to perform well is a bit of a dark art, Are you going to be using 10GB ether or just aggregations of 1GB/sec ? ( Do not get Broadcomm cards especially 10GB ones ). LVM2 is a no brainer but don't use the snap shotting as it is not fast. Remember backups of this will take some time. Test the way the system can fail before it goes into production and have it written up where you and your colleagues can find the docs when all goes wrong. It depends on your read/write ratio. We use a lot of HP MSA70 external 25-disk SAS drive enclosures and always create them as a single RAID6 array as our read to write ratio is 99%:1% so we don't care that R6 is about the slowest at writing (still pretty quick, just not that good compared to others). This way we have 23 disks worth of data available to us, have very good, as in VERY good, random read and overall read bandwidth benefits and can survive two disk failures. As a rough guide a RAID5 array shouldn't have more than about 14 disks in one array, whilst a RAID6 should be fine with up to 54 disks or so - obviously the bigger the array the bigger the gulf between read and write performance and the slower rebuilds will take but it CAN be a good trade-off. I would add two standby disks for a start. RAID 5 or 6 is OK for random reads or large sequential reads and writes. If you are going to get lots of small writes go with RAID 10 since RAID 5+ takes a 4 x hit on small writes. If you're going to turn on write cache remember to back it with a
http://serverfault.com/questions/30362/raid-configuration-for-large-nas
crawl-003
refinedweb
1,276
77.47
Hi folks. Recent meditations on sorted hash implementations reminded me of a module that I hacked together about a year ago and never did much with. I dug it out and did a little bit of extra stuff on it to make it complete, wrote some tests for it (not enough as yet alas) and now i'm presenting here. Partially becuase I think some people might find it interesting, partially because I want some critique. I actually debated posting it to SOPW, but as I think the module illustrates a number of interesting concepts, and is also quite large having it in meditations means it can be altered and changes posted to it without having to repost the entire thing. (Also I have lost some of the links that I should include so until I find them I want the node editable.) Interesting concepts!? Thats a mess, not an interesting concept. Well, *ahem*, yes. :-) I wrote this module as a learning excerise. I wanted to understand how the "Random Treap" algorithm worked. You see I have this weakness for self organizing data structures, especially tree based ones. Binary tress, 2-3 trees, huffman trees, B+Trees, etc all fascinate me. And when I discover a new one and can find the time I like to implement them to really grok how they work. In fact when I learn a new language I tend to make doing a 2-3 tree implementation one of the first pieces of code that I write. Its a tricky but cool algorithm that I find requires you to become aquainted with most aspects of the core of a language in a single project. And so when I found out about treaps1 as soon as I had time I downloaded a good paper on them1 and started coding. At the same time I was playing with other ideas, such as custom imports and namespace games, as well as being extremely unhappy with the interface of the well known Heap:: modules of "Mastering Algorithms in Perl". So naturally I rolled them all into one. Before we get to details of the code, lets briefly disucss what a Treap is. To grok Treaps you will need to think a moment about a tree organized in heaporder, and a tree organized in inorder. A tree in heap order is one where the node invariant is that the parents value is in some relation to both children. For instance if the ordering is from lowest to highest then the relation is such that the parent is less than either of its children, regardless of which side. This means there is no direct relationship between the two children, except that they are both greater than the parent. A tree that is organized in inorder maintains a different relationship between the parent and each child, and therefore an implied direct relationship between each child as well. In the case where inorder is defined from lowest to highest, the left child shall be less than the parent and the parent will be less than the right child. This of course implies that the left child is less than the right. Now, a Treap is a data structure where each node has two values, and where the resulting tree is maintained InOrder by one value and in HeapOrder by the other. For convenience we will use letters for the InOrder relationship and numbers for the HeapOrder relationship. The insert procedure is actually quite simple. We insert the node as a leaf just as we would if it were a binary tree obeying only the InOrder rule. Once inserted as a leaf we rotate the node up the tree until heap order is restored. If the node as inserted is already in heap order we do nothing extra. Similarly if we want to delete a node, we simply give it a temporary infinite heap weight, and rotate it down the tree in such a way that the heap order of the tree is maintained until its a leaf node and then delete it. (The normal binary tree trick of exchanging with the predecessor or successor if its an internal node can also be used so long as the new node is then rotated into heap order afterwards.) There are a number of interesting extensions to the standard binary tree strucutres that can be employed quite usefully to make implementing tree based Tie::Hash interfaces more efficient and easier to code. The two variants that I played with are Threading, And Left-Right Parent pointers. Threading involves adding a flag or two to the data structure and then reusing null child pointers. Lets take right threading as an example. Right threading means we add a flag to the node indicating if the right child pointer in fact points to a child or points to the successor to the node. When an insert occurs it always happens at a leaf, so when the new pointer is being assigned the old value is passed down to the new node. This means iterating the tree inorder can be done iteratively by simply following the right child. Left threading works similarly, except the predecessor is stored in unused left references instead of the successor. Originally my Treap implmentation was fully threaded. I then converted it to use Left-Right Parent pointers. Left-Right Parent pointers are a different mechanism. In this case two additional references are stored per node, the so called Left and Right parent pointers. To understand this properly let us define an extra term, "the left|right spine" of a node as being the node itself and all nodes that can be reached by traversing only left|right from it respectively. A node is the left parent of its right childs left spine, and the right parent of its lefts childs right spine. Thus in the earlier InOrder example B is the right parent of A and the left parent of C, A's left parent is null, and C's right parent is null. This relationship may sound a bit odd, but it does allow the same features as threading, plus allows some interesting possibilities in searching (finger searches). This is the model I ended up using. Well it turns out that Treaps have some interesting possibilites. For any given set of key-value pairs there is only one Treap that can store them. More interestingly by setting the value to a random value on store means that the search time for keys becomes near optimal, in effect the tree stays nearly balanced, making for efficient lookups. Maintaining this balance is on average cheaper in terms of rotations than many other self balancing trees. This can be a useful property when the tree structure is hybrid and rotations can incur expensive additional cost due to outside factors. A class called Random::Treap is included in the module that provides a sorted tied hash implementation that uses this technique. The heap API chews big time IMO. I've never like using it, I dont like to have to subclass its nodes to store what I need. It's just too clumsy and counter intuitive and frankly just too much work for my taste. So I wanted something different. Something where I could put a little elbow grease in just the one time, and then have an easy time of it ever after. I believe thats called Lazyness. :-) So what I did was predetermine the nodes structure that would be used for all implementations of the tree. Instead of subclassing the nodes you subclass the base class. There are three methods that need to be overriden to change the ordering of the tree (there probably should only be two). They are sub heap_lt { $_[1] < $_[2] }; sub key_lt { $_[1] lt $_[2] }; sub key_gt { $_[1] gt $_[2] }; [download] To change the behaviour of the algorithm you subclass it and override those methods as appropriate and you are done. In hindsight requiring only two methods, heap_cmp and key_cmp would have been better and I'll probably change it at some point. I dont remember the reason I went this way now, probably that it made the code a little easier to deal with. Package namespace games get involved because I think that Algorithm::Treap is the correct name for the module in terms of the CPAN namespace heirarchy, but I dont like to have to write Algorithm more than once in a program. Id much rather be able to talk about Treap's and not Algorithm::Treap's. So the package looks like this: package Algorithm::Treap; sub import { goto &Treap::import } 1; package Treap; #... [download] This means that when you use Algorithm::Treap you are actually using Treap, but perl knows to look in a different place. This can be a handy trick for dealing with annoyingly long package names while still having a deep file heirarchy and not a flat one. Now we get to the custom import bit. One of the things I wanted was an easier way to do the subclassing. I also was playing around with losing the method call to do the ordering of the class (in what I recall was an attempt at additional efficiency. I now see this argument as probably misguided, and probably a form of premature optimization. But the technique is interesting and useful so Ive left it in for now. Plus it works. And you know what they say... :-) The idea is that import() acts as a source code filter and class factory. When you use the module with no options it simply loads as would any module. However if you give it arguments you are actually asking it to generate a subclass for you that doesnt use method calls for determining the order functions. Instead it uses the code you provide to modify the class as a template. (It actually does override the methods too, but they are only for utility purposes.) Thus any subclasses generated this way no longer have the ability to have their ordering behaviour overriden, as the relevent method calls have been replaced by hardcoded evaluations. While this is maybe not the best use of this technique, it was an interesting experience putting it together. The easiest way is to use the tied hash interace, which can be easily obtained by using the class method Tied_Hash, which returns a reference to a tied hash of the appropriate class. The base class keeps the keys of the hash InOrder and the values of the hash in HeapOrder, and expects the values to be numeric. use Algorithm::Treap; my $default=Treap->Tied_Hash(A => 121, B => 674, C => 970, D => 82, E +=> 658, F => 957); $default->{D}=600; $default->{A}=500; [download] A more interesting example is the Random::Treap class which keeps the keys inorder, and provides for random values on store for the heaporder. The values can then be anything. use Algorithm::Treap; my $rand=Random::Treap->Tied_Hash(); $rand->{ja}="just another\n"; $rand->{ph}="perl hacker\n"; [download] And then theres the class factory interface: use Algorithm::Treap IntKey => #DEBUG=>1, key_lt => '$1 < $2', key_gt => '$1 > $2', heap_lt => '$1 < $2', ; my $inttreap=Treap::IntKey->Tied_Hash(); $inttreap->{1}=10; $inttreap->{2}=5; $inttreap->{10}=5; print join(", ",keys %$inttreap),"\n"; [download] Other uses are available through sub classing directly etc. Im a visual person and when I code something like this I like to be able to see whats going on. So there are a number of methods that are available for getting a look see as to what happening under the hood. The first is the dump_tree() method which will in void context print out the treap in ascii form, or in non-void return a string representation of it. For instance the $default hash can be viewed by tied(%$default)->dump_tree; [download] Which outputs A=500- +--------------------+ -D=600- +-------------+------+ B=674- E=658- +------+ +------+ C=970 F=957 [download] Review the code and youll find a few other ways to look at things too. You can iterate through the nodes efficiently by getting a node from the treap then calling succ or pred on the node returned as required. The nodes have the methods key, weight, and value, which can be used. It is not correct to change key or weight directly, but value can modified as you desire. This means that you can have multiple iterators on the same data structure simultaneously without them interfering with each other. The treap object however, in order to meet the requirementes of the Tie::Hash interface only allows one iterator. I really aught to take the time to fully document this module and upload it to CPAN. For now, I hope the monastery finds it interesting... And can offer some constructive criticism for its improvement. Code follows in a reply, as this node itself has grown quite large. :-) [1] I'll follow these up with links as I can find them again. This is the code for Algorithm::Treap. If you run it as perl treap.pm then it will self test/demonstrate. Also included is a test snippet that I have been using. This should be installed as ./Algorithm/Treap.pm somewhere reachable by @INC. (I set PERL5LIB to a development module tree for stuff I work on, and this is where this module lives. Warning: Large. Test script for the module. This should be runnable if the Algorithm treap is correctly located in @INC. :-) perl treap.pm Subroutine import redefined at Treap.pm line 67. Subroutine heap_lt redefined at Treap.pm line 127. Subroutine key_lt redefined at Treap.pm line 128. Subroutine key_gt redefined at Treap.pm line 129. Subroutine new redefined at Treap.pm line 131. Subroutine find_path_to_node redefined at Treap.pm line 184. Subroutine find_node redefined at Treap.pm line 209. Subroutine _shift_up redefined at Treap.pm line 241. Subroutine _shift_down redefined at Treap.pm line 316. Subroutine Store redefined at Treap.pm line 410. Subroutine Delete redefined at Treap.pm line 484. Subroutine Exists redefined at Treap.pm line 517. Subroutine Clear redefined at Treap.pm line 526. Subroutine Firstkey redefined at Treap.pm line 551. Subroutine Nextkey redefined at Treap.pm line 565. Subroutine Fetch redefined at Treap.pm line 579. Subroutine FetchUser redefined at Treap.pm line 586. Subroutine DESTROY redefined at Treap.pm line 598. Subroutine count redefined at Treap.pm line 611. Subroutine left redefined at Treap.pm line 614. Subroutine right redefined at Treap.pm line 617. Subroutine root redefined at Treap.pm line 620. Subroutine _sub_as_list redefined at Treap.pm line 622. Subroutine breadth_first redefined at Treap.pm line 631. Subroutine in_order redefined at Treap.pm line 676. Subroutine rev_order redefined at Treap.pm line 690. Subroutine heap_order redefined at Treap.pm line 705. Subroutine _heap_order_recurse redefined at Treap.pm line 715. Subroutine top redefined at Treap.pm line 764. Subroutine extract_top redefined at Treap.pm line 774. Subroutine print_order redefined at Treap.pm line 788. Subroutine __dump redefined at Treap.pm line 810. Subroutine dump_vert redefined at Treap.pm line 817. Subroutine __center redefined at Treap.pm line 821. Subroutine dump_tree redefined at Treap.pm line 840. Subroutine Tied_Hash redefined at Treap.pm line 913. Subroutine FETCH redefined at treap.pm line 924. Subroutine STORE redefined at treap.pm line 929. function 'new' already defined in package Treap::_Node at treap.pm line 950 BEGIN failed--compilation aborted at treap.pm line 958. Uh oh (what's going on?): I dont know. This doesnt make sense to me. Obviously it doesnt happen here, and at least one other person has had the code pass all tests. Can you double check that you copied the code correctly? One question and one suggestion. The question: Why would I use a Treap and what benefits (and costs) would result as compared to using a normal hash for that (those) same applications? The Suggestion: If you get around to modifying the interface to take a single custom comparator rather than the two as now (which I think makes a lot of sense), then you might also consider making the standard alpha comparator (cmp) a settable option in place of the default numeric comparator. That is to say, have a new()/tie() time option that can be set to indicate that the caller wants an alpha-sort order used rather than a numeric and then use cmp rather than <=> internally to the module rather than requiring the user to supply a comparator function that does this. The main reason is that callbacks can be expensive. The best demonstration of this is the GRT. Even though performing a numeric sort using a GRT requires stringifying the numeric (part of the) values to be sorted, into numerically orderable strings (ie. fixed width with leading zeros), this pre-sort overhead is more than compensated for by performance gained by avoiding the need to callback into user code for the comparisons during the sort. I think that the overhead of an if or trinary conditional in the module code to determine which operator to use when inserting and/or balancing (is that the right term with a Treap?) would be easily offset by the benefit of not invoking a callback for the common cases of a 'trivial comparator', ie. numeric or alpha. As an aside. I've long wished that perl had a numeric sort option built in (would one extra built-in called sortn be any great burden?), so that many cases where sorting numerically currently requires the overhead of a trivial callback or user block, or resorting to the GRT (or tyes recently posted variation on the theme) would become unnecessary.] $ (145 votes), past polls
http://www.perlmonks.org/index.pl?node_id=289584
CC-MAIN-2014-41
refinedweb
2,959
75
Hi, On Fri, Sep 09, 2011 at 01:57:38AM +0200, Michael Niedermayer wrote: > > One decoder breaks with this patch: mpegaudio. It seems to do weird things > > with two get bit context and switching them while decoding. I will try to > > have a look at it (unless someone would volunteer to explain me what it is > > doing :) > > well, iam not sure i remember all details but > mp3 frames are made of 2 parts the first part is just a bunch of > simply readable bitstream. The second part has to be appended to a > buffer out of which the actual decoding happens, that is possibly > from parts of past mp3 frames. This allows cbr mp3 to have somewhat > variable internal framesize. > What our code now does is it tries to avoid copying this bitstream > as a whole into the buffer (saving some memcpy cpu cycles) and thus > it has to switch the buffers > combining this with pretty good error recovery capability and > support for a few broken mp3 encoders results in the mess we have. Ok, thanks. I will have a closer look. > > @@ -311,7 +331,12 @@ static inline unsigned int get_bits1(GetBitContext *s){ > > result <<= index & 7; > > result >>= 8 - 1; > > #endif > > +#ifndef UNCHECK_BITSTREAM_READER > > + if (index < s->size_in_bits) > > + index++; > > +#else > > index++; > > +#endif > > i think this will break error detection of some files with some > decoders because they detect it by an overread having happened > > also it might lead to infinite loops or other unexpected things > as some decoders depend on them > hitting zero padding after the buffer which is guranteed to lead to > vlc decoding failures for them as they have no valid all 0 vlc code I see. A simple way could be to simply add 8 * PADDING_SIZE to the check. I will add that locally. -- fenrir
http://ffmpeg.org/pipermail/ffmpeg-devel/2011-September/114580.html
CC-MAIN-2016-22
refinedweb
296
58.96
python day 26: When i was in Partial Differential Equation class, my deskmate would take out a notebook and play five-in-a-row with me. Many years have passed by, I bearly recall anything about PDE, but i still remember the little definite joy when i was late to class, I knew my deskmate would have the board ready and waiting for me. Today we will use Python to construct a classical game, Tic Tac Toe, which is an easier version of Five-in-a-row. Lyo: Only double three counted as Winning for me. 四子不算赢,只有双三才算赢。我从来不靠别人看不到来赢。 Like all the chess-like games, Tic-Tac-Toe/Five-in-a-row has First-hand advantage, but i still struggle to pick go first or second. Chinese always says, 人生如棋,落子无悔。 Life is like Chess, once set, no regret! Up to now, I regret frequently about my decisions, however, as time goes by, i think l also learned try to let the things be, and set myself free. 我慢慢学会放过我自己了! Python Tic Tac Toe Code: import os def print_board(board): print(board['TL'] + '|' + board['TM'] + '|' + board['TR']) print('-+-+-') print(board['ML'] + '|' + board['MM'] + '|' + board['MR']) print('-+-+-') print(board['BL'] + '|' + board['BM'] + '|' + board['BR']) def tit_tac_toe(): init_board = { 'TL': ' ', 'TM': ' ', 'TR': ' ', 'ML': ' ', 'MM': ' ', 'MR': ' ', 'BL': ' ', 'BM': ' ', 'BR': ' ' } begin = True while begin: curr_board = init_board.copy() begin = False turn = 'x' counter = 0 os.system('clear') print_board(curr_board) while counter < 9: move = input('%s Please make a move: ' % turn) if curr_board[move] == ' ': counter += 1 curr_board[move] = turn if turn == 'x': turn = 'o' else: turn = 'x' os.system('clear') print_board(curr_board) choice = input('One more?(yes|no)') begin = choice == 'yes' tit_tac_toe() | | -+-+- | | -+-+- | | | | -+-+- |x| -+-+- | | | | -+-+- o|x| -+-+- | | | | -+-+- o|x|x -+-+- | | o| | -+-+- o|x|x -+-+- | | o| | -+-+- o|x|x -+-+- x| | o| |o -+-+- o|x|x -+-+- x| | o|x|o -+-+- o|x|x -+-+- x| | o|x|o -+-+- o|x|x -+-+- x|o| o|x|o -+-+- o|x|x -+-+- x|o|x Happy studying! Ref:
https://fangya18.com/2020/08/15/python-with-tic-tac-toe/
CC-MAIN-2021-17
refinedweb
322
66.78
The following Error Message shows up in the last 'Plot' procedure: In Z(Q), 'numpy.float64' object is not iterable. I would like Z(Q) returns value that sum each i in the range (0, len(p)), which is a function with variable Q. And finally the plot is Q(X Axis) and Z(Q)(Y Axis) for each Q it can be plotted. How can I modify Z(Q)? Thank you! Code: import numpy as np import scipy.stats as stats from scipy.stats import poisson, norm cs = 100 co = 300 mu = 4.7 G = poisson(mu) p = G.pmf(np.arange(3*mu)) def Z(Q): for i in range(len(p)): return sum(p[i]csmax((Q-i), 0) + p[i]comax((i-Q), 0)) import pylab as pl x = [] y = [] for Q in range(0, 12): x.append(Q) y.append(Z(Q)) pl.plot(x, y, '-o') pl.show() It looks like you're new here. If you want to get involved, click one of these buttons!
https://programmersheaven.com/discussion/438393/how-to-change-this-define-function
CC-MAIN-2019-22
refinedweb
172
86.5
What are Observables in Angular? In this tutorial, I am going to explain What is Observable and Where/When we use it. We use Observable to perform asynchronous operations and handle asynchronous data. Another way of handling asynchronous is using promises. We can handle asynchronous operations using either Promises or Observables. What are asynchronous operations and asynchronous data? We already know that JavaScript is a single-threaded language. That means the code is executed line by line and once the execution of one code is complete then only the next code of the program will be executed. When we make a request to the HTTP server that will take more time. So the next statement after the HTTP request has to wait for the execution. It will only get executed when the HTTP request completes. We can say that the synchronized code is blocked in nature. This is the way the asynchronous programs came into the picture. Asynchronous code executing in the background without blocking the execution of the code in the main thread. Asynchronous code is non-blocking. That means we can make HTTP requests asynchronously. Using an asynchronous program we can perform long network requests without blocking the main thread. There are 2 ways in which we can do that. - Using Observables - Using Promises What is the difference between Promises and Observables? Let’s say we are requesting a list of users from the server. From the browser, we are sending a request to the server and the server will get the data from the database. Let’s say the data which we are requesting is huge. In that case, the server will get some time to get the data from the database. Once the data is ready the data will send from the server to the client-side. Here server gathered all the data and when the data is ready that will send back to the client-side. This is how gets the Promise work. It promises to provide data over a period of time. Promise provides us the data once the complete data is ready. The data can be the actual data that we requested or it can also be an error. If there is no internet connection. In that case, also promises to return some data. That data will be the error message or an error object. Observables are not waiting for the complete data to be available. An Observable streams the data. When the data is available partially it will send to the client. Promises - Helps you run functions asynchronously, and use their return values (or exceptions), but only once when executed. - Not lazy. - Not cancellable (there are Promise libraries out there that support cancellation, but ES6 Promise doesn’t so far). The two possible decisions are Reject and Resolve. - Cannot be retried (Promises should have access to the original function that returned the promise to have a retry capability, which is a bad practice) - Provided by JavaScript language. Observables - Helps you run functions asynchronously, and use their return values in a continuous sequence (multiple times) when executed. - By default, it is lazy as it emits values when time progresses. - Has a lot of operators which simplifies the coding effort. - One operator retry can be used to retry whenever needed, also if we need to retry the observable based on some conditions retryWhen can be used. - Not a native feature of Angular or JavaScript. Provide by another JavaScript library which is called Rxjs. An Observable is a function that converts the ordinary stream of data into an Observable stream of data. You can think of Observable as a wrapper around the Ordinary stream of data. Rxjs(Reactive Extensions for JavaScript) is a javascript library, that allows us to work with the asynchronous data stream. You can find everything related to Rxjs from here, Rxjs has two main causes. - Observable — Stream of Data - Observer — Which is going to use the data In order to make Observer use the data emitted by the Observable. For that Observer has to subscribe to the Observable. Let’s create an Observable. To create an Observable we need to import Observable from the Rxjs library in our Angular application. When we create a new Angular project this library automatically gets installed on the project. You don’t need to install Rxjs separately. Here I created a simple project called “my-app” and in the app.component.ts we need to import Obseravle from the Rxjs library. Then I created a new Observable object using the Observable constructor. In the constructor, we need to pass the callback function. The callback function will receive an argument which will be the Observer. This argument will be injected by the Rxjs library. This observer is the subscriber who is waiting for the data. Inside the callback function, I am going to log a message and emit some data. To emit the data we can use observer.next(). I am going to emit 5 times data. This is the data that the observable is going to emit. Now we need a subscription. This observable only emits the data if there is a subscriber. If there is no subscriber it will not be going to emit the data. Create a subscriber for the observable. In the ngOnInit, I am going to implement the subscriber. Subscriber takes 3 optional parameters. These 3 parameters are callback functions. - error - complete All these 3 parameters are optional. this.myObservable.subscribe(next, error, complete); This next parameter which is a callback function is executed every time the next method in the observable returns a value. In this example, the “next” callback function will call 5 times because we are going to emit data 5 times. Basically, the next callback function will receive the data which the observable has returned or emitted. Let’s go to the webpage and open the developer console. Now you can see the data emitted by the observable and it has been logged here. import {Component, OnInit} from '@angular/core'; import {Observable} from 'rxjs';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'my-app'; myObservable = new Observable((observer) => { console.log('Observable Starts'); observer.next('1'); observer.next('2'); observer.next('3'); observer.next('4'); observer.next('5'); }); ngOnInit(): void { this.myObservable.subscribe((val) =>{ console.log(val); }); } } This data has been streamed one by one. Let’s emit data from a certain time interval. For that we can use setTimeout() function. I have added 1 second as the time interval. myObservable = new Observable((observer) => { console.log('Observable Starts'); setTimeout(() => { observer.next('1'); }, 1000); setTimeout(() => { observer.next('2'); }, 2000); setTimeout(() => { observer.next('3'); }, 3000); setTimeout(() => { observer.next('4'); }, 4000); setTimeout(() => { observer.next('5'); }, 5000);}); Now you can see the data one by one has been emitted after a certain time interval(1 second). I hope you got a better understanding and knowledge of the Observables and the process of them in Angular. There are other ways of creating Observables and Let’s find them and learn them from the next tutorial. Thank You!
https://kasunprageethdissanayake.medium.com/what-are-observables-in-angular-5e89d159a4e6?source=user_profile---------0----------------------------
CC-MAIN-2022-40
refinedweb
1,184
59.6
showell30@yahoo.comBAN USER @tpcz, How is this problem not inherently exponential? The numbers from positions i to j can generate 3 ^ (i+j-1) different sums, depending on where you put the minus signs and/or omit numbers. How does your DP matrix look for the use case of target 12 and elements 9999, 9998, 11? Aren't there 27 booleans at play here? I originally downvoted this question, because it's pretty poorly specified, but I upvoted it back. The author doesn't really make it clear what constitutes a "distinct" solution. For example, why is 6 + 8 - 2 = 12 considered a solution, but 8 + 6 - 2 = 12 isn't? Are we allowed to use a negative sign in front of the first element? How about other operators? If the target number is 0, then can we say that our solution is to add up none of the numbers? My inference is that the problem boils down to this. For each number, it can either contribute itself to the sum, its negative to the sum, or nothing to the sum. So there are 3^N possibilities to consider. I would do simple recursion with these pseudo-coded relationships: f([], 0) = 1 f([], a) = 0 whenever a is not zero f([x|rest], n) = f(rest, n+x) + f(rest, n) + f(rest, n-x) In my notation [x|rest] means you have a list of at least length 1 where x is head and "rest" denotes the remainder of the elements in the list. I think the problem is ambiguously defined if either your target is zero or your list is empty, but setting up the degenerate cases correctly makes the recursion work. Here's the implementation, by the way: def test(): # test the string from the web page s = '986561517416921217551395112859219257312' assert 36 == get_equal_sum_substring(s) # test with a longer string s = '9' + ('5' * 8000) + '9' + ('6' * 7999) + '8' assert 8002 == get_equal_sum_substring(s) def get_equal_sum_substring(s): s = map(int, s) S = [0] sum = 0 for i in s: sum += i S.append(sum) def sub_sum(low, high): return S[high] - S[low] #)-2*slen): lsum = sub_sum(i, i+slen) rsum = sub_sum(i+slen, i+slen*2) if lsum == rsum: return 2 * slen slen -= 1 return 0 test() @Anonymous, If you do center-inward the naive way, then it's no better than the center-outward approach, because you're not traversing the sums in a way that allows you to terminate early. Now you can do a center-inward search in a breadth-search manner, and keeping the outward sums would allow you to quickly compute the next-inward sums when you got back to them in a breadth search, but then you're facing a lot of work. The whole idea of caching the long sums so that you could subtract off elements to get the next-longest sums, rather than recomputing a long sum, is what got me to the S() function epiphany in the first place. If you use the S() function, then you get all these advantages: 1) You only ever compute n sums. 2) You can iterate through the results in descending order. 3) To evaluate each potential result you merely compute a difference between two S() values in constant time. 4) You don't have to maintain any complicated data structures. It's just O(N) storage for the values of S(). Python Solution for Subsequence (non-contiguous) Many of the solutions on this page are solving the trivial problem of contiguous runs in a list. A subsequence can actually have gaps, which makes this a bit more challenging, but you can do it NlogN time. My solution is actually N-squared, but the linear search can be fairly trivially converted to a binary search. # This solves the LSS problem--longest sorted subsequence. def test(): a = [7,8,1,5,4,6,9] assert LSS(a) == [1,4,6,9] def LSS(a): if len(a) == 0: return [] # candidate_maxes is an array of # the max value of a sorted subsequence # of length n, where n is the index # of the current element candidate_maxes = [a[0]] predecessor = {} for elem in a[1:]: if elem > candidate_maxes[-1]: # This is the case where our new element # extends the longest subsequence so far. predecessor[elem] = candidate_maxes[-1] candidate_maxes.append(elem) else: # Do a linear search to see if we # can make one of our previous subsequences # easier to extend. For a large N, we could # convert this to a binary search. for i in range(len(candidate_maxes)): if elem < candidate_maxes[i]: candidate_maxes[i] = elem if i > 0: predecessor[elem] = candidate_maxes[i-1] break i -= 1 elem = candidate_maxes[-1] result = [elem] while elem in predecessor: elem = predecessor[elem] result.append(elem) result.reverse() return result test() Isn't there a race condition between releasing id2's read lock and opening id2's write lock? During that time somebody else could adjust a2's balance, only to have it wiped out by the assignment to temp. Good luck! I came upon the clever shortcut trying to think along DP lines--basically, structuring your computations so that recursive relations make things really simple--but I really struggled for a while. I think I've probably seen this technique in some other context, because it was obviously lurking in my subconscious. In some ways it's analogous basic Calculus--compute the integral function so that computing the sum of diffs across a range becomes simple subtraction. Like I said, I think the problem is a bit contrived. For a really simple use case, it's probably more than sufficient to simply synchronize TransferAccount, as you're probably gonna have bottlenecks elsewhere. And as soon as you start introducing real world problems like connecting to databases that might be down, etc., the problem gets more complex than simply ordering locks. But you're right, I'm a little off topic. :) I just upvoted the lock ordering solution. Python Successor Approach This is a mostly iterative approach toward generating the permutations. It introduces a successor function, which perhaps simulates better how a human would approach the problem--we have a number, and we want to find the next viable candidate. # Generating permutations is a fun challenge, # but it's also nice to have a successor function # that can just give you the next permutation. def permutations(num_digits): n = 0 for i in range(num_digits): n = n * 10 + i bitmap = make_bitmap(num_digits, n) while n: yield n n = successor_helper(num_digits, n, bitmap) # This is for one stop shopping. def successor(num_digits, n): bitmap = make_bitmap(num_digits, n) return successor_helper(num_digits, n, bitmap) # If you want successive permutations, call the # successor_helper with a bitmap. def successor_helper(num_digits, n, bitmap): ones = n % 10 tens = n / 10 bitmap[ones] = False for ones in range(ones+1, 10): if not bitmap[ones]: bitmap[ones] = True return tens * 10 + ones # we overflowed if num_digits == 1: return None tens = successor_helper(num_digits-1, tens, bitmap) if not tens: return None for ones in range(10): if not bitmap[ones]: bitmap[ones] = True return tens * 10 + ones return None def make_bitmap(num_digits, n): bm = [False] * 10 for i in range(4): bm[n % 10] = True n /= 10 return bm def test(): def test_successor(n, exp_new_n): bm = make_bitmap(4, n) new_n = successor_helper(4, n, bm) assert new_n == exp_new_n assert bm == make_bitmap(4, new_n) test_successor(123, 124) test_successor(132, 134) test_successor(139, 142) test_successor(189, 192) test_successor(198, 213) test_successor(1987, 2013) assert 213 == successor(4, 198) assert successor(4, 9876) is None assert 9 * 10 == len(list(permutations(2))) assert 7 * 8 * 9 * 10 == len(list(permutations(4))) test() @Anonymous, yeah, the only drawback of the centers-outward approach is that you can't start by evaluating the longest possible candidates first, and therefore exiting early as soon as you find a match. If the likelihood of palindromes is fairly high, it's a significant benefit to proceed in reverse order. For the centers-outward approach, you are basically committed to evaluating all N*(N-2) sums. If the likelihood of a palindrome is reasonably high, this is inefficient. With the precompute solution, your best-case scenario (the whole string is equally balanced) will run in linear time. P.P.S. See my response to @tpcz for a more efficient way to speed up the sum-of-range computation than using a cache. @sonesh, I'm joking. I'm playing off the pseudo-misspelled-as-sudo pun. Don't blame me, Anonymous started it. :) A simple way to make the sum-of-a-range computation work in constant time is to precompute the function S(n) for all values n in linear time, where S(n) represents the sum of all elements to the left of an element: S(n) = a[0] + a[1] + a[2] + ... + a[n-1] so S(n) = S(n-1) + a[n-1] Then to compute the sum of the range a[low:high], you take S(high) - S(low), using the Python convention that high is the first number NOT in the range. P.S. In actual wall time it's hard to outperform the naive algorithm with a caching strategy, because the "constant" time of a cache hit is significantly higher than just summing up numbers over a small range. It's also tricky to optimize for cache hits, because your strategy for breaking down sums can lead to overlapping ranges, so you would probably prefer some kind of DP-ish strategy that primes the cache, or use some sort of skip-list scheme. It's N cubed. You have two outer loops around an O(N) sum. To make this faster you need to avoid recomputing partial sequences, by using a cache or some kind of precomputed matrix (DP). See "Python Solution with Cache" for a caching approach. N cubed gets slow real fast. Try coding your naive algorithm for N=1000. A super naive algorithm is to count from 0000 to 9999, and just skip over any number with duplicate digits. Over half of the numbers (5040) are valid candidates, so it's not horribly wasteful. Then you think about it some more, and you realize every number from 7700 to 7799 is a "bad" number, so you can detect numbers of the form nn00, and immediately skip past 100 values. Pretty soon you'll converge on what's essentially an odometer algorithm. When you roll the odometer, instead of incrementing the current digit, increment to the next digit not already used by a higher digit. You can micro-optimize digit detection by having a length ten map of which numbers are available. The correctness argument goes something like this. Let's say the heads of X, Y, and Z are 10, 5, and 20, so that y=5 is the min. Consider all tuples (x, 5, z). Since X is sorted we know that x >= 10 for all x, and likewise all z >= 20. So now we know any solution involving y=5 has the form (x >= 10, 5, z >= 20). Since y=5 is less than 10 and 20, we clearly know the optimal solution for that form has to be (10, 5, 20), which we just evaluated. Therefore, since we have proven that we've already considered the optimal solution for y=5, we can advance the Y pointer beyond y=5 to find more optimal solutions over (X, Y, Z). It's also pretty easy to convince ourselves that the algorithm terminates in linear time, since we always exclude one element from one of the lists. (To be precise, it's O(Nm) time, where m=3, but we can treat as m as a constant in the current formulation.) Even though it's pretty easy to prove the correctness of the algorithm, there is still risk in messing up the implementation. Fortunately, this problem has a trivial O(N^3) solution as well, so you can use your slow implementation to validate the fast implementation for a bunch of randomly generated small lists. This won't conclusively prove that the faster algorithm works, but it can help identify bugs in the implementation. This is a classic phone screen question. Leo's solution is the classic answer. If the first element isn't drawn on the first iteration, you want to keep it as a candidate, hence the swap. (And the swap also effectively removes the just-chosen number as a candidate, and adds it to the result set, effectively killing three birds with one stone.) If you can process each number on the fly (by outputting them, using them directly, yielding them from a coroutine, appending to a passed in collection, or calling back a callback function), then replace the swap with a simple assignment of a[r] = a[i], since you won't need to revisit the value of a[i] after emitting it. How about a sudoku random number? After all, repeats are disallowed in any square, any row, and any column. Problem solved! Yep, I would only go the fancy solution if space was severely constrained. Overflow's a fiddly issue, but it's relatively straightforward to manage big integers with a simple multi-byte integer class, since sums and squares are pretty straightforward. Why use a hash map instead of a bit vector or simple array of booleans? You know that the numbers range from 1 to N and are unique. Why pay the price of collisions in a hash table? The problem with an XOR solution for the two-numbers-missing problem is that 1 xor 2 is the same as 5 xor 6 and 13 xor 14. It's not clear to me that you've actually resolved that conundrum. Maybe show some tests? In a banking scenario, you often have these conditions: 1) Individual accounts have very little activity. 2) Accessing accounts has very high latency. A small problem to avoid is the race where the same account is being incremented/decrement at the exact same millisecond. This can be handled with a simple mutex. The bigger problem is that additions/subtractions to an account can't actually be committed until the remote account confirms the trade. From a practical standpoint, the bank wants to err on the side of rejecting transactions prematurely. In other words, it wants to avoid ever promising funds from an account that has uncommitted credits, but it is also wants to avoid promising funds where provisional debits would lessen the balance upon commit. So let's say Alice agrees to transfer $100 to Bob's account, and the transaction is initiated from a data center remote to both banks. The financial soundness of the transaction only hinges on Alice having sufficient funds in her account, so the remote data center notifies Alice's bank of the desired transfer. If Alice's provisional balance is too low, the transaction is immediately rejected. Otherwise, her available balance is immediately debited, and you make sure the transaction can be committed on Bob's end (i.e. his account is active, the network is available, etc.). At this point, the transaction is sound from a financial standpoint, but you can't commit it until Bob eventually gets the money in his bank. So, then you post the transfer to Bob's account, and if he confirms it, you then commit the transfer on Alice's end. Remember that I said that individual accounts have very little activity, so for each account, you can inexpensively manage a data structure of all the uncommitted transfers. In some cases uncommitted transfers will be explicitly rolled back by the other party, but you also have to account for data failures, so you will have expiration logic. Here, you need to be very careful managing funds availability. Alice's bank can't release funds for her until it's certain that Bob hasn't been credited. On the other hand, Bob's bank can roll back his credit after a timeout. Asking this problem in terms of Java is kind of contrived, because this is really more of a systems engineering question than a coding question. With a single data center, you would be more likely to using a locking model than a phased commit model, but bank transactions typically involve lots of latency between banks. Python Solution with Cache This Python code iterates through all the possibilities in descending order of length, and it avoids recomputing partial substrings by caching intermediate sums. def test(): # test the string from the web page s = '986561517416921217551395112859219257312' assert 36 == get_equal_sum_substring(s) # test with a longer string s = '9' + ('5' * 500) + '9' + ('6' * 499) + '8' assert 502 == get_equal_sum_substring(s) def get_equal_sum_substring(s): # Turn string of digits to an array of ints. s = map(int, s) # For a small s, the substring_cache is not # really worth it, but for longer strings it # makes sense. substring_cache = {} def sub_sum(low, high): if low + 1 == high: return s[low] n = substring_cache.get((low, high), None) if n is not None: return n n = s[low] + sub_sum(low+1, high) substring_cache[(low, high)] = n return n #)): if i+slen*2 > len(s): break lsum = sub_sum(i, i+slen) rsum = sub_sum(i+slen, i+slen*2) if lsum == rsum: return 2 * slen slen -= 1 return 0 test() @tpcz, agreed, I'm in the same place on this. The naive approach that I first considered is actually O(n^3), when you simply iterate all O(n^2) possible substrings and then compute the suitability of each solution in O(N) time. But you can then back to O(N^2) by precomputing a matrix of substring sums using DP. For the iteration, my first thought is to try to consider the long lists first, since you can at least return early as soon as you find a substring that satisfies the condition. So, for a 6-digit input, consider the substrings in this order: 123456 1234 2345 3456 12 23 34 45 56 I don't see a clever way to prune the iteration. For example, among the foursomes, does something about one foursome's result allow you to eliminate other foursomes? I'm not seeing it yet. Iterate through the digits from left to right. When you encounter the broken key digit, decrement it and then turn all the subsequent digits to 9. But wait! The edge cases are 0 and 9. If your 0 key is broken, then you need to backtrack one digit before doing the decrementing and 9-replacement steps. If your broken key is 9, then you need to use 8 for the subsequent digits. I would first code this to work for digits 1 through 8, and have a little test suite. Then I'd introduce the 0/9 edge cases, adding tests for those as well. Also, Gayle, tell me truthfully that you wouldn't look kindly upon a security candidate who had obsessive backup plans for broken light bulbs in her house. Good security people and sys admins have an obsessiveness that borders upon an outright personality disorder. Gayle, it obviously depends on the interviewer. I take it as a given that every interview question tests your problem solving skills to some extent, but within that context, some are more about your chops (do you know basic data structures?) and others are more subjective (what's your first instinct in a crisis?). I agree with you 100% that you need to get to the diagnosis aspect pretty quickly. My reaction to a burnt out light bulb would be two steps. First, I presumably need light. So, I find the flashlight, light a candle, turn on another light switch, use my phone as a make-shift flashlight, etc. Once I'm in the diagnosis phase, I start analyzing possible causes. The last time the lights went out in my apartment, it was the circuit breaker, and it was completely obvious, because the TV also shut off. But most of the time, it's the light bulb. If a light bulb goes out, sometimes you can clearly tell that the filament blew, but for some times of bulb, you go into the scientific method. I hypothesize that the light bulb's broken, and if I have a handy spare, I can validate the hypothesis by swapping in the spare. If the spare doesn't work, then I consider other theories. It could be that the original light bulb AND the spare are broken, but it's more likely that I'm dealing with a more systemic problem. Etc. It's a strange question, but I assume it's a conversation starter. Possible reactions to a light bulb not working: 1) Lazy response: do nothing. 2) Paranoid response: Assume intruder is in your home, immediately call police. 3) Quick workaround: Immediately go to kitchen, grab flashlight out of drawer. 4) Quick diagnosis: Assume it's just the light bulb, immediately try replacing the light bulb. 5) Deep analysis: See if other lightbulbs are out. Consider hypotheses that you have experienced a local blackout (circuit breaker) or general blackout (neighbors light's are out). 6) Follow up: If it's the light bulb, consider cost/analysis benefits of buying a more hearty light bulb, making flashlight easier to find in a crisis. This is just a personality question. If I were hiring a security person, I would want somebody who is really Type A, with a healthy sense of paranoia, but also some level of pragmatism. People who are into security need to account for extreme possibilities, so they're the type of people who have backups of every light bulb in their house, a flashlight in every drawer, and a schematic of their house's wiring conveniently laminated on the wall next to their circuit breaker. I am downvoting this answer, because there are lots of ways to in-place sort a list, but this brief answer doesn't explain why heapsort would be superior to, say, quicksort, given the partial ordering. Of the most common divide-and-conquer sorts, mergesort is the one that breaks down the problem by recursively creating two sorted lists, so it would seem like the most appropriate sort to adopt for this problem. Unfortunately, it's really hard to do a mergesort efficiently on array-based lists when you don't have contiguous storage at your disposal for the merged result. If the original list were a linked list instead of an array, then you could do it pretty trivial with no extra storage, but the problem explicitly says this an array. @nishit, It's not that simple--you need to sort on the anagrams of the values, not the values themselves. I didn't downvote it (in fact, I upvoted it back to zero), but I would offer one small critique. Why are you computing the anagrams in your compare method? This is gonna cause them to be computed multiple times in the outer sort, i.e. roughly logN times. Why not use the decorate-sort-undecorate idiom, otherwise know as the Schwartzian transform? @xankar, agreed. My comment was mostly directed at the treemap solution, which is neither simple or clever. If you're gonna use a map, then you should take advantage of the main constraint--all integers from 1 to N--and implement your map as a simple array of booleans, or, better yet, a bitmap. Other folks have since posted the clever solution. Sum the numbers, and sum the squares of the numbers, find the shortages in both, then use simple algebra to deduce the two missing values. It's kind of a parlor trick, but I would definitely be thrilled if an interview candidate knew it. Nice solution. It's efficient, and your comments strike a nice balance of explaining things that aren't immediately obvious, without being overly verbose. @xankar, To keep things simple, let's simplify the problem to say that the original seating arrangement is ABCDE, but our players are finicky about where they sit: A: wants seat 3 B: wants seat 2 C: wants seat 4 D: wants seat 1 E: wants seat 3 Hopefully you can see how this maps to desired rotations from our original seating arrangement: A: wants to move 2 clockwise B: wants to move 0 clockwise C: wants to move 1 clockwise D: wants to move 2 clockwise (actual rotation) E: wants to move 3 clockwise(actual rotation) After we compute each person's desired shift, we update this data structure: 0 clockwise: 1 vote (from B) 1 clockwise: 1 vote (from C) 2 clockwise: 2 votes (from A, D) 3 clockwise: 1 vote (from E) 4 clockwise: 0 votes Note that our data structure doesn't keep track of the voters; it's just the counts. At the end we iterate through our vote tallies and find that 2-clockwise makes the most people happy (2). Once you understand this scenario, it's a pretty small mental leap to account for the original seating arrangement being something other than ABCDE. This problem is trivial when the list is sorted, so let's assume it's not. Even for an unsorted list, it's trivial to solve in linear time, so it's not worthwhile to sort the list first. When only one number is missing, you can compute the sum of the list and compare it to the sum of the first N integers (N*(N+1)/2), and the difference is the missing number. If more than one number is missing, then the clever trick doesn't help a whole lot, since there are multiple pairs of numbers that could account for the shortage. So, without clever tricks, let's eliminate fancy data structures too. Just allocate an array of N booleans, and set them all to false. In your first pass, go through the input array, take the number and set the array of booleans to false for that index. Then, in a second pass, iterate through your array of booleans to find which numbers were left out. Overall running time is O(N), and because you're not using a fancy data structure like a hash or a tree, it's reliably linear, even for a worst case ordering. @alex, It's a simple iteration with bookkeeping. Keep track of the max contiguous product seen so far, as well as active prefixes for a new contiguous product. Negative numbers add the twist that you want pre_min as well as pre_max, since a negative number can temporarily flip a sequence to be negative, but you don't want to abandon it, in case a subsequent negative number flips the product back to positive. If you set aside negative numbers for a bit, then this is the core logic for each iteration: new_max = pre_max*elem pre_max = max([elem, new_max]) ans = max([ans, pre_max]) Every iteration updates the best in-progress answer as well as the best overall answer to date (which could be still in progress or just getting started or encountered earlier in the list, before a zero or small fraction). The problem allows you to use more than two numbers in the product, as long as they're contiguous. Also, it's not explicitly stated, but I'm assuming that a range of one integer can be considered to have a "product" of itself. Multiplication is commutative, so 5*7*2*3 is not ambiguous. Also, multiplication has an identity element, so it's reasonable to consider product([42]) to be 42*1, although you'd clarify that with the interviewer. Last but not least, you need clarify whether the product of an empty range is considered to be 1 or undefined. A mathematician would probably choose 1, but the engineering context might make undefined be more appropriate. @algos, This is a good start, but if you're not told the insertion point in advance, then you'll need to do the bookkeeping on where the insertion happened. Also, while not explicitly stated in the problem, you can probably expect multiple inserts, so you're gonna want a data structure that scales beyond one insert. This is the correct approach. You want to maintain a list of offsets. See "Python Solution with Paged Lists" for a full implementation of this concept. @Geet, If you're doing a large number of inserts, then you might not want a linked list to store the offset. Better to have an array that allows you to do a binary insert to find the pages. If you're doing this in C, you need to be careful about memory management. You'll want your list of pages to also indicate whether pages were created via malloc() or carved out of a previously malloc'ed page. If you throw deletes into the equation, then you might want to consider a data structure that uses a fairly small page size. Having more pages will slow down random access, but that can be mitigated with a binary search for offsets, and your insertions/deletions will be faster. Python Solution with Paged Lists: def test(): arr = BigArray() chunk_size = 10000 for i in range(100): new_elems = range(i*chunk_size, (i+1)*chunk_size) arr.insert_elems(i*chunk_size, new_elems) assert 43999 == arr[43999] assert 500000 == arr[500000] arr.insert_elems(900000, range(3000)) assert 0 == arr[900000] assert 1001 == arr[901001] assert 900001 == arr[903001] arr.insert_elems(903001, [1,2,3]) assert 1 == arr[903001] assert 2 == arr[903002] assert 3 == arr[903003] assert 900001 == arr[903004] class BigArray: def __init__(self, page_size = 1000): # Keep a list of pages, with an empty page # at the end for convenience. self.page_offsets = [0] self.pages = [[]] self.page_size = 1000 def debug(self): for i in range(len(self.pages)): print i, self.page_offsets[i], len(self.pages[i]) def __getitem__(self, i): if i > self.page_offsets[-1]: raise IndexError, "n too large" page = self._get_page(i) page_i = i - self.page_offsets[page] return self.pages[page][page_i] def insert_elems(self, n, lst): # insert elements from lst into BigArray # starting at index n if n > self.page_offsets[-1]: raise IndexError, "n too large" if n == self.page_offsets[-1]: return self.append_elem(lst) # Find the page where insertion starts. page = self._get_page(n) cnt = len(lst) # Split the page after the insertion point. This # might create a small page, but we don't worry # about it for simplicity sake. We can refine # this later by trying to balance our new elements # better. self._split_page(page, n) self._update_offsets_for_insertion(page, cnt) low = 0 # See how much room we have in current page # to avoid needlessly creating new pages. We # may luck out with a partial page from a previous # insert. room = self.page_size - len(self.pages[page]) if room > 0: # We might have extra room if room > cnt: room = cnt # Extend our current page self.pages[page].extend(lst[0:room]) low = room # Now create new pages as needed. if low >= cnt: return new_pages = [] new_offsets = [] while low < cnt: page_size = min([cnt - low, self.page_size]) new_pages.append(lst[low:low+page_size]) new_offsets.append(n+low) low += page_size self.pages[page+1:page+1] = new_pages self.page_offsets[page+1:page+1] = new_offsets def append_elem(self, lst): # TODO: For now, we always create new pages, but # we could try to look at the last nonempty # page and see if there's room. cnt = len(lst) n = self.page_offsets[-1] # remove empty page temporarily self.page_offsets.pop() self.pages.pop() low = 0 while low < cnt: page_size = min(self.page_size, cnt - low) self.page_offsets.append(n + low) self.pages.append(lst[low:low+page_size]) low += page_size # put back empty page self.page_offsets.append(n+cnt) self.pages.append([]) def _update_offsets_for_insertion(self, page, cnt): # update offsets of all the pages to the # right of the insertion point (if any) for i in range(page+1, len(self.pages)): self.page_offsets[i] += cnt def _get_page(self, n): # This should be a binary search, but # doing it as a linear search for clarity. for page in range(len(self.page_offsets) - 1): if n < self.page_offsets[page+1]: return page # the last page is unbounded, and it's usually # an empty page return len(self.page_offsets) - 1 def _split_page(self, page, n): if n >= self.page_offsets[page+1]: return self.page_offsets.insert(page+1, n) offset = n - self.page_offsets[page] self.pages.insert(page+1, self.pages[page][offset:]) self.pages[page] = self.pages[page][:offset] test() The Banker's algorithm solves a much more complicated problem. Read the question again and then read the wikipedia article on the Banker's algorithm. It only does three passes. One pass to initialize the array, one pass to increment it for each person, and one pass to find the max. It's O(N). The naive approach is basically N-squared, where you take try all N rotations and count all N people during each pass. Do you understand what I'm doing differently here? Each person has a distance that they wish to be rotated. Calculate this distance as a positive number in the clockwise distance, so it will be a number from 0 to 4. Initialize an array from 0 to 4 with counts of zero, and the array will represent the number of people that are happy with each rotation distance. For each person, increment the appropriate slot in the array. At the end, iterate through the array to see which one has the largest count. So the trick of the Bloom filter is that you only want each word to set a few bits in the filter. If each word leads to an average of ten bits being set in the filter, it doesn't take too many words until every bit in the shared bitmap is 1, at which time you effectively get positive guesses every time, which means way too many false positives. See the solution from @Gohawks to see how to solve P2+P3=n on a sorted list in O(n) time. You start with P2 as the min and P3 as the max, and then each iteration you either increment P2 or decrement P3, depending on whether P2+P3 is too small or too big, respectively. The magic here is that once P2+P3 >= n, you can stop finding pairs for P3, since all the remaining P candidates will be greater than P2 by virtue of the list being sorted. This is what prevents the inner loop of this algorithm from being N-squared. I'm assuming the requirements break down like this: 1) We're dealing with big data, not huge data, so millions of values, not billions. 2) We obviously need bulk inserts to be fast. 3) I'm gonna assume a read-mostly context, so we want random access to be at least log(N) fast, so a simple linked list won't cut it. 4) I'm gonna assume inserts are always bulk, so we can amortize the cost or live with the slowness for small inserts. Given these constraints, I'd create a 2-level tree of integers, with roughly 1000 pages of 1000 integers each. The outer list (i.e. top of the tree) would have the offsets for the inner lists. For random access, you'd binary search the outer list to find your page table and then do an O(1) lookup in the page to get your value. This is essentially how BigTable works, except BigTable has a few more levels. To do a bulk insert, you find the page where the insertion point belongs, split that page, then simply create a new page for your new data, and then you only need to update the outer table to accomodate the two new pages and recalculate offsets, which has a worst case of about 2000 operations. If you're doing lots of bulk inserts over time, then you'll eventually want some compaction algorithm to consolidate pages. Also, after you split pages to make room for your new insertion, then if the first part of the split page is pretty small, you should consider simply appending your values to it, rather than creating a new page. Data structure that use a paging scheme usually have some flexibility on page size, so that you try to be a certain size, but you can go up to double that size to be lazy about re-organizing your data structure. This same question was asked pretty recently. Here is my solution: def max_product(a): ans = pre_max = pre_min = a[0] for elem in a[1:]: new_min = pre_min*elem new_max = pre_max*elem pre_min = min([elem, new_max, new_min]) pre_max = max([elem, new_max, new_min]) ans = max([ans, pre_max]) return ans assert 0 == max_product([0,0,-2,0,0,0]) assert 8 == max_product([-2,1,1,8]) assert 18 == max_product([-2,-3,1,3]) assert 12 == max_product([-3,-4,0,1,2,3]) assert 720 == max_product([1,-1,10,-8, -9, 0]) assert 2 == max_product([-50, 0.5, 2]) assert 2 == max_product([-50, 2, 0.5]) I don't know of any obvious way to do this faster than N squared time. To do it in N squared time, first create a reverse mapping of numbers to the index(es) of the array containing that number. Then do an N-squared pass on pairs of numbers, take their sum, then look in the reverse mapping to find the index of the additive inverse of the pair's sum. You can prune the outer edges of the list by finding the most negative number and most positive number (in linear time), and then during your N-squared pass exclude numbers on the other side of the zero that have double the magnitude. For example, if your largest positive number is 6, then you can immediately reject -13 as being part of the solution, since you'd need at least one number > 6.5 to get back to zero. @laxman601, I think you should try to collapse the following lines of code to one or two lines of code, and avoid all the special casing. If you can use zero-based indexing, then this idiom is fairly common: desired_rotation = (desired_chair + num_chairs - chair) % num_chairs If you are dealing with a language that computes modulus correctly for negative numbers (e.g. in Python, -5 % 7 == 2, which is correct, but JS is stupid about it and gives you the mathematically awkward answer of -5 ), then go with this: desired_rotation = (desired_chair - chair) % num_chairs - showell30@yahoo.com March 19, 2013
https://careercup.com/user?id=14941696
CC-MAIN-2021-49
refinedweb
6,435
60.14
This action might not be possible to undo. Are you sure you want to continue? 8827 Credit For Prior Year Minimum Tax—Corporations Attach to the corporation’s tax return. OMB No. 1545-1257 Department of the Treasury Internal Revenue Service Name Employer identification number Minimum Tax Credit for 1992 1 2 3 Alternative minimum tax for 1991. Enter the amount from line 16 of the 1991 Form 4626 Carryforward of minimum tax credit from 1991. Enter the amount from line 9 of the 1991 Form 8827 Enter any 1991 unallowed credit for fuel produced from a nonconventional source and any 1991 unallowed orphan drug credit (see instructions) Add lines 1, 2, and 3 Enter the corporation’s 1992 regular income tax liability minus allowable tax credits (see instructions) Enter the amount from line 15 of the 1992 Form 4626 Subtract line 6 from line 5. If zero or less, enter -0Minimum tax credit. Enter the smaller of line 4 or line 7. Also enter this amount on the line provided on the corporation’s income tax return (e.g., if you are filing Form 1120 for 1992, enter this amount on line 4f, Schedule J). If the corporation had a post-1986 ownership change, see the specific instructions for line 8 below 1 2 3 4 5 6 7 4 5 6 7 8 8 Minimum Tax Credit Carryforward to 1993 9 Subtract line 8 from line 4 (see instructions) incurred in prior tax years and to compute any minimum tax credit carryforward that may be used in future years. 9 General Instructions (Section references are to the Internal Revenue Code. ) Line 5 Enter the corporation’s regular income tax liability (as defined in section 26(b)) minus any credits allowed under Subchapter A, Part IV, subparts B, D, E, and F of the Internal Revenue Code (e.g., if you are filing Form 1120 for 1992, subtract any credits on lines 4a through 4e, Schedule J, from the amount on line 3, Schedule 1 hour. If you have comments concerning the accuracy of this time estimate or suggestions for making this form more simple, we would be happy to hear from you. You can write to both the IRS and the Office of Management and Budget at the addresses listed in the instructions of the tax return with which this form is filed. Who Should File Form 8827 should be completed by corporations that had: ● An AMT liability in 1991; ● A minimum tax credit carryforward from 1991 to 1992; or ● A 1991 unallowed nonconventional source fuel credit or a 1991 unallowed orphan drug credit (see Line 3 below). Recordkeeping.—Use Form 8827 each year to see if the corporation has a minimum tax credit and to keep a record of any credit carryforward. Line 8 If the corporation had a post-1986 “ownership change” (as defined in section 382(g)), section 383 may limit the amount of prechange minimum tax credits that can be applied against the corporation’s tax for any tax year ending after the ownership change. If this limit applies, attach the computation of the allowable minimum tax credit, enter that amount on line 8, and write “Sec. 383” on the dotted line to the left of the line 8 entry space. In addition, see section 384 for the limit on the use of any preacquisition excess credit of one corporation to offset recognized built-in gains of another corporation. Specific Instructions Line 3 Enter the unused portion of the 1991 credit for fuel produced from a nonconventional source that was not allowed solely because of the limit under section 29(b). Also include on this line the unused portion of any 1991 orphan drug credit not allowed solely because of the limit under section 28(d)(2)(B). Cat. No. 13008K Purpose of Form Form 8827 is used by corporations to compute the minimum tax credit, if any, for alternative minimum tax (AMT) Line 9 Keep a record of this amount because it can be carried forward and used in future years. Form 8827 (1992) This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/document/542766/US-Internal-Revenue-Service-f8827-1992
CC-MAIN-2016-50
refinedweb
724
55.27
CONTENTS. Is there a Windows version of Salome? 1.3.2. Where I can check if there a version of Salome for my operating system? 1.3.3. Can I have Salome platform ported to my operating system? 1.3? 4.11.6. How to do local mesh refinement in the Salome V3.2.1? 4.11.7. How to export/import groups to UNV? 4.11.8. How to mesh two solids that share a face? 4.11.9. How to create a sub mesh with local hypothesis? 4.11.10. How to create a mesh using TUI? 4.11.11. Is it possible to use Mesh algorithms from Salome in Open Cascade? 4.12. How to use MED module? 4.12.1. What is Med Format? 4.12.2. What is a difference between Med file and MEDMEM (MED module)? 4.13. How to use Post-pro module? 4.13.1. How to import ASCII file in Post-Pro? 4.13.2. Is it possible to visualize Gauss points in SALOME? 4.14. How to use Supervisor module? 4.15. What is Dump Study? SALOME is free software that provides a generic platform for Pre and Post-Processing for numerical simulation. It is based on an open and flexible architecture made of reusable components available as free software. It is open-source (LGPL), and you can download both the source code and the executables from the site. Salome Platform: · Supports interoperability between CAD modeling and computation software (CAD-CAE link) · Makes easier the integration of new components on heterogeneous systems for numerical computation · Sets the priority to multi-physics coupling between computation software · Provides a generic user interface, user-friendly and efficient, which helps to reduce the costs and delays of carrying out the studies · Reduces training time to the specific time for learning the software solution which has been based on this platform · All functionalities are accessible through the programmatic integrated Python console SALOME platform is distributed under LGPL license (GNU Lesser General Public License). Please see Possessing the source code of the platform, you can freely modify it for your internal purposes. However, you can copy and distribute such modifications only provided that you meet the conditions stated in the LGPL license: · The modified work must itself be a software library. · You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. · You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. Yes, you can. However, you can charge the price only for your module, while SALOME itself is free. You must give prominent notice with each copy of the distribution that Salome is used in it and that Salome and its use are covered by LGPL license. All products required by SALOME are distributed under LGPL license (or similar) or “free for non commercial usage” licenses. No, there is no solver which comes with SALOME platform, but there are some solvers which can be used with it transparently. For example Code_Aster (please visit). Also there is a site which provides a special Linux distribution including SALOME, Code_Aster and other free solvers. Currently there is no public Windows version of SALOME platform. Release notes for SALOME provide a list of platforms where SALOME is qualified. Also there is some useful information about SALOME porting on other Linux systems on Salome forum () Please contact our support team through to have more information about available services. Yes, SALOME platform is qualified on Mandriva 2006 64 bit Linux. You can download the Installation Wizard with binary distribution from section. Install Wizard (see 2.1) includes the sources of SALOME platform. There is runInstall script in the root folder of the Installation Wizard archive. This script runs GUI interface of the installation procedure or runs batch installation. There is a README file with useful information on how SALOME is built, run, etc., in the root folder of the Installation Wizard archive. Another README file describing the Installation Wizard itself, the launching procedure and the meaning of optional parameters is located in /doc/ folder. Successful compilation and execution of Salome platform requires quite a number of third party products, including, but not limited to: gcc, tcltk, Python, Qt&msg2qm, Sip, PyQt, Boost, Swig, Open CASCASDE Technology, Qwt, OmniORB, Hdf, Med, Vtk, Numeric, Graphviz, Doxygen, NETGEN and docutils. All these products are free software and distributed together with Salome platform. More information about the versions of the products required for a particular Salome version can be found in section. Naturally, all prerequisites are necessary and should be installed on your PC. You can easily install them using SALOME Install Wizard Execution of Salome platform requires tcltk, Python, Qt, PyQt, Boost, Swig, Open CASCASDE Technology, Qwt, OmniORB, Hdf, Med, Vtk and NETGEN. ~ 600Mb of disk space, but during the installation you will need 1Gb of free disk space. Salome is permanently tested on Mandriva 2006 32bit; Mandriva 2006 64bit; Debian Sarge 3.1 and Mandrake 10.1 platforms. Salome is not tested but is known to run successfully on RedHat Enterprise 4; RedHat Scientific 4.2 and RedHat Scientific 4.3 platforms. is absent. It is necessary to install it additionally. If you compile SALOME from sources, it may use other FORTRAN compiler, native for your system, for example gfortran on Mandriva 2006 64 bit._HELLO or RANDOMIZER) Module can publish their data in SALOME study to provide access to them for other components. Also publishing in the Study provides persistence of such data (not in all cases, persistence of complex data is provided by special methods). When a developer develops a new module, it inherits lunch python scripts. Many SALOME functionalities are mapped to python. If you develop a simple pre—post processor which does not need standard SALOME modules, like Geometry, Mesh, etc., but you have a GUI based on qt, you can organize it as a light SALOME module. These modules provide some samples of how to write your own components based on SALOME. These are HELLO_SRC (C++ SALOME component), PYHELLO_SRC (Python SALOME component), LIGTH_SRC (light module of SALOME), SIERPINSKY_SRC and RANDOMIZER_SRC. The latter two are C++ and python components, which show interaction between modules. After the SALOME installation, the procedure creates two environment files “salome.sh” $HOME, for example, .SalomeApprc.3.2.6. There are “embedded” and “standalone” xml tags, where the necessary servers are placed. By default CORBA naming server starts in port 2810. However if this port is busy, the launh procedure finds the next free port. It is necessary to call “killSalome.py” procedure to kill all running servers and services (like omniNames etc) after you exit from GUI session. “killSalomeWIthPort.py” should be used if you have several sessions running on different ports. You should input the name of the port as argument. In this case only the processes corresponding to the configuration of the port are shut down and other processes are still being executed. To launch Salome without GUI, use “runSalome –t” command: only the necessary servers are launched (without GUI) and the python console is also active enabling to load TUI scripts. To launch a group of chosen Salome modules, use the command “runSalome –modules=XXX, YYY”, where XXX and YYY are modules.: To activate Geometry module run SALOME via "runSalome -t" command, then type in the terminal (start python interpreter): import salome, GEOM; salome.salome_init() geom = salome.lcc.FindOrLoadComponent("FactoryServer", "GEOM") geom = geom._narrow(GEOM.GEOM_Gen) To activate Mesh module run SALOME via "runSalome -t" command, then type in the terminal (start python interpreter): import salome, SMESH; salome.salome_init() mesh = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH") mesh = mesh._narrow(SMESH.SMESH_Gen) To activate Post-Pro module run SALOME via "runSalome --gui" command, then type in the terminal (start python interpreter): import salome, VISU; salome.salome_init() visu = salome.lcc.FindOrLoadComponent("FactoryServer", "VISU") visu = visu._narrow(VISU.VISU_Gen) To activate Supervisor module run SALOME via "runSalome -t" command, then type in the terminal (start python interpreter): import salome, SUPERV; salome.salome_init() superv = salome.lcc.FindOrLoadComponent("FactoryServer", "SUPERV")), IGS (up to 5.3 version) and STL formats. There is also a commercially available CATIAV5 plug-in. The term point presents the lowest level of abstraction in geometry, an entity that has a location in space or a plane but no extent. The term vertex means a corner of · an angle: the point where two line segments join or meet, where two lines cross (intersect), or any appropriate combination of rays, segments and lines that result in two straight "sides" meeting at one place. · a polygon: any point on the polygon where two sides (line segments) meet and connect. · a polyhedron: any point where three or more edges meet and connect to each other. The edges are the connections (line segments as shared sides) of two or more faces (polygons). · for curves a vertex is a point on the curve with a local minimum or maximum of curvature. In Salome most 2D and 3D objects can be defined through a number of vertices. This function serves for testing purposes; select in the Main Menu New Entity - > Basic - > Working Plane or click the corresponding button in the toolbar. There are several algorithms of working plane creation. Firstly, it is possible to design a Plane, a Planar Face or a Local Coordinate System as a Working Plane. Secondly, a Working Plane can be defined by two vectors. Finally, you can select one of three basic projections of XYZ coordinate system as a Working Plane..
http://www.salome-platform.org/faq/
crawl-001
refinedweb
1,601
56.55
The Windows Phone SDK includes the launcher “MarketplaceReviewTask” that launches the Windows Phone Marketplace client App and shows the review page for the current Application . To add the Marketplace ReviewTask in Windows Phone , follow the below steps 1. Add the namespace MIcrosoft.Phone.Tasks to your Code Behind file . 2. Include the following code to your App to start the Marketplace Review for the current App . MarketplaceReviewTask review = new MarketplaceReviewTask(); review.Show(); Note that if you are trying to run this in an emulator or Device from Visual Studio, you will get the following error message with the message code “Marketplace error code: 805a0194”. Try to publish the App to the marketplace and then start the MarketPlaceReview , it should work … The reason we get the error message is because the App is not yet published to the marketplace and hence we cannot review or rate the App 🙂
http://developerpublish.com/marketplace-reviewtask-in-windows-phone/
CC-MAIN-2018-13
refinedweb
147
53.21
This extension adds information about the code block to each closing bracket of your code. This helps you understand the code faster, as you don't need to search for the opening bracket first.. Header information for each block of code Icons for each type of condition/header. Eg: public class , do while , ... Fast navigation to the header of the code block by clicking the tag Only show tags when header not visible option (recommended for best result) This feature was inspired by VSCommands. Sadly, this extension isn't available for VisualStudio 2015 with the CodeBlogTagger. So i decided to implement it myself.
https://marketplace.visualstudio.com/items?itemName=KhaosPrinz.CodeBlockEndTag
CC-MAIN-2021-43
refinedweb
103
56.96
Hi Stefan, just a few things : 1) as we are using Junit4, you don't need to specify that the class extends TestCase 2) you just need to add the @Test annotation in front of each test method : @Test public void testEqualsForDifferent() throws ParseException 3) To do so, you will have to add those imports : import org.junit.Test; 4) For setUp and tearDown, add @Before and @After in front of them 5) The metjod names don't anymore have to start with 'test', but I think it's a good politic to keep this prefix 6) For assertXXX, just add import static org.junit.Assert.assertXXX; (static is important) 7)SimpleDateFormat is not synchronized. In case JUnit launch tests in // (not really the case right now, but in the next version ...), you might be surprised ;) Emmanuel PS: I guess that a page on the developper wiki about Junit4 usgae could have helped ... -- Regards, Cordialement, Emmanuel Lécharny
http://mail-archives.apache.org/mod_mbox/directory-dev/200709.mbox/%3Cd45b08f00709301431t1c4f9fb3p62630f8c1918a6c8@mail.gmail.com%3E
CC-MAIN-2016-18
refinedweb
157
63.32
Parent Directory | Revision Log Again with a more up to date copy Updating all the dates I changed some files. Updated copyright notices, added GeoComp. It begins Round 1 of copyright fixes Data.cpp: Removed some namespace ambiguities which fixes doxygen warnings, some cleanup and reindent. *: doxygen fixes. First pass of updating copyright notices Fixed some minor doxygen issues. Don't panic. Updating copyright stamps Merging version 2269 to trunk Fixed some more typos add 4 missing ESCRIPT_DLL_API that prevented linking. Merged noarrayview branch onto trunk. Branch commit Merged changes from trunk version 1695 up to and including version 1779. Branch commit: Updated the doxyfile for deprecated/modified options (eg encoding is set to UTF-8). Also set it not to scan directories called .svn or deprecated. Removed #includes of DataArrayView.h Moved DataArrayView into a new deprecated directory Commented out setTaggedValue in DataExpanded which still referred to DataArrayView Fixed some of the doxygen comments in DataMaths.h, DataTypes.h, DataTagged.h Removed the empty JoelMods.cpp_ Unit tests appear to indicate that this branch is now "no more broken" than the version I branched from.. Branch commit. Moved getSliceRegionLoopRange and checkShape into DataTypes.h Some work on methods to set/addTaggedValues without using DataArrayView. To do this I added copyFromNumArray() on DataVector (It buggy at the moment). This build passes the tests but only because copyFromNumArray is not used. Branch commit Moved getSliceRegion() and getSliceRange() into DataTypes Data.cpp - modified not to rely on operator() from DataArrayView - Used more const& to avoid copies Branch). Branch. Branch commit DO NOT PANIC. Moved shapeToString and noValues from DataArrayView to DataTypes{.h,.cpp} Moved ValueType, ShapeType, RegionType, RegionLoopRangeType and maxRank From DataArrayView.h to DataTypes.h This is a simple rename but did require modifying a lot of files. This form allows you to request diffs between any two revisions of this file. For each of the two "sides" of the diff, enter a numeric revision.
https://svn.geocomp.uq.edu.au/escript/branches/subworld2/escriptcore/src/DataTypes.h?view=log&amp;pathrev=5505
CC-MAIN-2019-18
refinedweb
324
60.31
Hi everyone, I have been working on this for about a week, looking at examples from all over the place and pouring through datasheets, but I cannot get this to work(or many ARM Features for that matter) I have worked with AVRs for a while and I love them, but I wanted to move up to ARM. I know a reasonable amount of C, and no assembler. I don't really want to get this example working as much as I want to learn what im not doing right. I really want to learn how to be able to do ARM programs on my own and not rely on forums to help me, so any tutorials or books would be greatly appreciated. So, I am trying to get the ADC working so it will print the 10-bit value of ADC0.3 over uart0 at 19200 baud. Here is my code: #include "LPC214x.h" #define ADC_CLK 1000000 /* set to 1Mhz */ #include "serial.h" #include "rprintf.h" #include "target.h" void delay_ms(int x); int main(void) { init_serial0(19200); rprintf_devopen(putc_serial0); rprintf("Hello!\n\n"); PINSEL0 = 0x10000000; AD0CR = (0x01 << 0) | (1 << 3) | //Turn analog 3 on (( Fpclk / ADC_CLK - 1 ) << 8) | (0 << 16) | // BURST = 0, no BURST, software controlled (0 << 17) | // CLKS = 000, 11 clocks/10 bits (0 << 18) | //^ (0 << 19) | //^ (1 << 21) | // PDN = 1, normal operation (0 << 22) | // TEST1:0 = 00 (0 << 24); // START = 0 A/D conversion stops while(1) { AD0CR |= (1 << 24); //Start Conversion delay_ms(1); //Give it time to convert(I doubt this is necessary?) rprintf("%luH", ((AD0DR3 >> 6) & 0x000003ff) * 0x40); AD0CR &= (1 << 24); //Stop Conversion delay_ms(50); } } void delay_ms(int x) //Rough, not meant to be accurate { int a,b; for(a=0;a<x;a++){ for(b=0;b<3000;b++); } } And when I run the code this is all I get: Hello! ÿ Any ideas for what I am doing wrong? Thanks! After I posted this I thought I should mention that I am using an LPC2148, on the Olimex Header Board. I am compiling with GCC. I also just noticed you prefer code attached. Sorry for the large paste above. Your delay loop is not going to work if you compile with optimization enabled (-Ox), because the compiler will detect an empty loop and remove it. Use volatile variables for the counter, then it won't get removed. If your controller hangs, the reason is usually an exception caused by an invalid memory access. Do you have a JTAG debugger? If yes, try to find out what the controller is doing after you have received the output (it is probably hanging at the abort handler), then rerun and use single step to locate the statement that's causing it. If you don't have a debugger, you can for example comment out lines until you have found the problem. - Strange output might just be caused by missing functionality in rprintf. Since rprintf is not shown it's difficult to analyse. Test with a known uint32_t value first, see rprintf source and check for "l", test with "L", test with cast to uin32_t. Try to use sprintf from the newlib. - add volatile to counters definition (a,b) in delay-function. You can try to read the Logomatic-v2 code from sparkfun electronic. It use the LPC2148 ADC, I have tested and it works very well with Uart output. Link to the Logomatic-v2 product info:?... There is a link to get the source code (main firmware) Thank you everyone! I do not have an ARM JTAG, dongle, but I do have a USB Xilinx FPGA one, would that work? I played around with it some more, commenting out lines until I got it working. I found that PINSEL0 = 0x10000000; was the problem, and by removing it it will now actually print the ADC value. The problem is, it always prints zero. I know that the ADC is actually reading zero because I did a test with if(adcval == 0), and it always returned true. I did like mthomas suggested as use sprintf from newlib, but unfortunately this did not help. I have attached the code and all other files I include(except the standard ones). Any help is greatly appreciated. Thank you! Neal Le Moult: I looked at the Logomatic Code, but the ADC Part seemed really jumbled in with everything else, and what I am really looking for is learning how to use the ADC, which is hard when its combined with interrupts and timers and the like. Thanks anyway! Here is an application note from Nxp about LPC21xx ADC
http://embdev.net/topic/130731
CC-MAIN-2017-04
refinedweb
767
71.34
#include <MFnKeyframeDeltaTangent.h> A MFnKeyframeDeltaTangent function allows API programmers to read changes in keyframe tangent values. It captures changes in tangent type, as well as, changes in tangent time/value pair. MFnKeyframeDeltaTangents are generated by a MAnimMessage::addAnimKeyframeEditedCallback. Because a key's tangent may be unbroken. It is possible to receive to MFnKeyframeDeltaTangent values per key -- one for the incoming tangent and one for the outgoing tangent. The API programmer should use the isInTangent method to determine if the tangent change affects the in-bound tangent or out-bound tangent. Constructor. Class constructor that initializes the function set to the given MObject. Constructor. Class constructor that initializes the function set to the given MObject. Function set type. Return the class type : MFn::kKeyframeDeltaTangent Reimplemented from MFnKeyframeDelta. Class name. Return the class name : "MFnKeyframeDeltaTangent" Reimplemented from MFnKeyframeDelta. Returns the previous tangent type. Returns the current tangent type that the key represents. Get the values of the previous time/value position of the tangent for this key. Get the values of the current time/value position of the tangent for this key. Key's have two tangents, in-bound and out-bound. A MFnKeyframeTangent object can created once for each tangent. Use this method to determine which tangent was modified.
http://download.autodesk.com/us/maya/2009help/API/class_m_fn_keyframe_delta_tangent.html
crawl-003
refinedweb
208
60.41
Table of Contents - Introduction - Quick Start Guide - I want to know more! Introduction Welcome to the official Mixpanel Flutter SDK. The Mixpanel Flutter SDK is an open-source project, and we'd love to see your contributions! We'd also love for you to come and work with us! Check out Jobs for details Quick Start Guide Check out our official documentation for more in depth information on installing and using Mixpanel on Flutter. 1. Install Mixpanel Prerequisites Steps - Depend on it Add this to your package's pubspec.yaml file: dependencies: mixpanel_flutter: ^1.0.0 # set this to your desired version - Install it You can install packages from the command line: $ flutter pub get - Import it Now in your Dart code, you can use: import 'package:mixpanel_flutter/mixpanel_flutter.dart'; 2. Initialize Mixpanel To start tracking with the SDK you must first initialize with your project token. To initialize the SDK, first add import 'package:mixpanel_flutter/mixpanel_flutter.dart'; and call Mixpanel.init(token); with your project token as it's argument. You can find your token in project settings. import 'package:mixpanel_flutter/mixpanel_flutter.dart'; ... class _YourClassState extends State<YourClass> { Mixpanel mixpanel; @override void initState() { super.initState(); initMixpanel(); } Future<void> initMixpanel() async { mixpanel = await Mixpanel.init("Your Mixpanel Token", optOutTrackingDefault: false); } ... Once you've called this method once, you can access mixpanel throughout the rest of your application. 3. Send Data Once you've initialized the SDK, Mixpanel will automatically collect common mobile events. You can enable/disable automatic collection through your project settings. With the mixpanel object created in the last step a call to track is all you need to send additional events to Mixpanel. // Track with event-name mixpanel.track('Sent Message'); // Track with event-name and property mixpanel.track('Plan Selected', properties: {'Plan': 'Premium'}); You're done! You've successfully integrated the Mixpanel Flutter SDK into your app. To stay up to speed on important SDK releases and updates, star or watch our repository on Github.? To preserve battery life and customer bandwidth, the Mixpanel library doesn't send the events you record immediately. Instead, it sends batches to the Mixpanel servers every 60 seconds while your application is running, as well as when the application transitions to the background. You can call flush() manually if you want to force a flush at a particular moment. mixpanel.flush();.
https://pub.dev/documentation/mixpanel_flutter/latest/
CC-MAIN-2021-31
refinedweb
391
50.23
add constraints to a route. For example, the following route maps browser requests to a controller named Blog and an action named Archive: routes.MapRoute( "BlogArchive", "Archive/{entryDate}", new { controller = "Blog", action = "Archive" } ); This route, named BlogArchive, maps three parameters. The controller parameter is assigned the value Blog and the action parameter is assigned the value Archive. Finally, the entryDate parameter gets its value from the entryDate parameter in the URL. Unfortunately, this route matches too many requests. It matches: · /Archive/12-25-1966 · /Archive/12 · /Archive/apple · /Archive/12-25-1966 · /Archive/12 · /Archive/apple You don’t want entryDate to get values like 12 or apple. These values cannot be converted into a date. You can fix this problem with the BlogArchive route by adding a constraint to the entryDate parameter like this: routes.MapRoute( "BlogArchive", "Archive/{entryDate}", new { controller = "Blog", action = "Archive" }, new { entryDate = @"\d{2}-\d{2}-\d{4}" } ); This new version of the BlogArchive route includes a constraint on the entryDate parameter. The constraint requires that the entryDate parameter matches a date pattern that looks like 12-25-1966. A URL like /Archive/apple won’t satisfy this constraint and the route won’t be matched. The URL Routing framework recognizes two different types of constraints. When you supply a constraint, you can either supply a string or you can supply a class that implements the IRouteConstraint interface. If you supply a string for a constraint then the string is interpreted as a regular expression. For example, the entryDate constraint that we discussed in the previous section is an example of a regular expression constraint. The other option is to create a custom constraint by creating an instance of a class that implements the IRouteConstraint interface. The URL Routing framework includes one custom constraint: the HttpMethod constraint. You can take advantage of the HttpMethod constraint to prevent a controller action from being invoked unless the action is invoked with a particular HTTP method. For example, you might want a controller action named Insert() to be invoked only when performing an HTTP POST operation and not when performing an HTTP GET operation. Here’s how you can use the HttpMethod constraint: routes.MapRoute( "Product", "Product/Insert", new { controller = "Product", action = "Insert"}, new { httpMethod = new HttpMethodConstraint("POST") } ); The last argument passed to the MapRoute() method represents a new HttpMethod constraint named httpMethod. If you post an HTML form to the /Product/Insert URL, then the Product.Insert() controller action will be invoked. However, if you simply request /Product/Insert with an HTTP GET, then this route won’t be matched. By the way, the name of the constraint is not important. Only the value is important. For example, the following code works just as well as the previous code: routes.MapRoute( "Product", "Product/Insert", new { controller = "Product", action = "Insert"}, new { Grendal = new HttpMethodConstraint("POST") } ); In this code, the HttpMethodConstraint is named Grendal. You can name the constraint anything you want and the constraint will still work. You create custom constraints by implementing the IRouteConstraint interface. This interface has one method that you must implement: the Match() method. For example, the code in Listing 1 represents a custom constraint that prevents unauthenticated access to a URL: Listing 1 – AuthenticatedConstraint.cs using System.Web; using System.Web.Routing; public class AuthenticatedConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { return httpContext.Request.IsAuthenticated; } } Notice that Listing 1 contains a class that implements the IRouteConstraint interface. The Match() method checks whether the current user is authenticated and returns either True or False. Here’s how you can use the AuthenticatedConstraint when creating a route: routes.MapRoute( "Admin", "Admin/{action}", new { controller = "Admin", action = "Index" }, new { authenticated= new AuthenticatedConstraint()} ); This constraint prevents requests from anonymous users from being mapped to the Admin route.: routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); For this reason, you should explicitly exclude the Admin pages from the Default route with an explicit constraint. The easiest way to exclude one set of pages from matching a particular route is to take advantage of the custom route constraint in Listing 2. Listing 2 – NotEqualConstraint.cs using System; using System.Web; using System.Web.Routing; public class NotEqual : IRouteConstraint { private string _match = String.Empty; public NotEqual(string match) { _match = match; } public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { return String.Compare(values[parameterName].ToString(), _match, true) != 0; } } Here’s how you can use the NotEqual constraint to exclude the /Admin pages from the Default route: routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }, new { controller = new NotEqual("Admin") } ); This route won’t match any request when the controller parameter gets the value Admin. For example, this route won’t match the URLs /Admin/DeleteAll or /Admin/Index. You also can create a custom constraint that prevents a request from matching a URL unless the request is made from the local machine. This type of constraint can be useful for restricting access to website administrative pages. Listing 3 contains the code for the LocalConstraint class. Listing 3 – LocalConstaint.cs using System.Web; using System.Web.Routing; public class LocalConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { return httpContext.Request.IsLocal; } } The LocalConstraint simply checks whether the current request is a local request by taking advantage of the Request.IsLocal property. This property returns the value True when the host is either equal to localhost or 127.0.0.1. So how do you test route constraints? Easy, fake the HttpContext. The test in Listing 4 can be used to verify that the Product route includes an HttpMethod constraint. Listing 4 – A Unit Test for the HttpMethod Constraint [TestMethod] public void TestInsertIsPost() { // Arrange var routes = new RouteCollection(); GlobalApplication.RegisterRoutes(routes); // Act with POST request var fakeContext1 = new FakeHttpContext("~/Product/Insert", "POST"); var routeData1 = routes.GetRouteData(fakeContext1); // Assert NamedRoute matchedRoute1 = (NamedRoute)routeData1.Route; Assert.AreEqual("Product", matchedRoute1.Name); // Act with GET request var fakeContext2 = new FakeHttpContext("~/Product/Insert"); var routeData2 = routes.GetRouteData(fakeContext2); // Assert NamedRoute matchedRoute2 = (NamedRoute)routeData2.Route; Assert.AreNotEqual("Product", matchedRoute2.Name); } The unit test in Listing 4 consists of two tests. First, the URL /Product/Insert is requested by performing a POST operation. The Product route should be matched in the route table. Next, the same URL is requested while performing a GET operation. The Product route should not be matched when performing a GET. The unit test in Listing 5 demonstrates how you can test the AuthenticatedConstraint. Listing 5 – Unit Test for AuthenticatedConstraint [TestMethod] public void TestAdminRouteIsAuthenticated() { // Arrange var routes = new RouteCollection(); GlobalApplication.RegisterRoutes(routes); // Act with authenticated request var fakeUser = new FakePrincipal(new FakeIdentity("Bob"), null); var fakeContext1 = new FakeHttpContext(new Uri(""), "~/Admin/Index", fakeUser); var routeData1 = routes.GetRouteData(fakeContext1); // Assert NamedRoute matchedRoute1 = (NamedRoute)routeData1.Route; Assert.AreEqual("Admin", matchedRoute1.Name); // Act with anonymous request var fakeContext2 = new FakeHttpContext(new Uri(""), "~/Admin/Index"); var routeData2 = routes.GetRouteData(fakeContext2); // Assert Assert.IsNull(routeData2); } This unit test also consists of two tests. First, a fake user is created with the help of the FakeIdentity class. When the /Admin/Index URL is requested with the fake identity in context, the Admin route should be matched. When the same URL is requested anonymously, on the other hand, no route should be matched. In this tip, you learned how to create custom route constraints. We created three custom route constraints: the AuthenticatedConstraint, the NotEqualConstraint, and the LocalConstraint. I also showed you how you can build unit tests for routes that include custom constraints. Download the Code Excellent! Thanks Walther Yeah, Thanks very much Beautiful... I'm going to use this in a presentation I'm doing on MVC in October. This is a fantastic example of why MVC rocks! :) Thanks again, -Timothy Khouri Error 2 'System.Web.Routing.RouteValueDictionary' does not contain a definition for 'Keys' and no extension method 'Keys' accepting a first argument of type 'System.Web.Routing.RouteValueDictionary' could be found (are you missing a using directive or an assembly reference?) C:\MVC Framework\Tip30\CS\Tip30\RouteDebugger\Controllers\RouteDebuggerController.cs 63 43 RouteDebugger Excellent Walther. Thanks!! Your tips have been an invaluable resource, thanks for posting. Not so much of a constraint issue, but how are we going to be able to great routes that run over SSL (HTTPS)? OMG - awesome sauce! This has been one of the best MVC tips in your series, Walther. So kewl! hope these constraints will be included in the 1.0 release .. cause they look VERY useful! Pingback from Custom Route Constraints (ASP.NET MVC) « Jim 2.0’s Blog If you set debug=false in web.config Route don't work correct with same action names. I have 2 controllers Home and News Each has Index action. Create links using Html.ActionLink you get two links "/" and "/News" cause index is deafult action i suppose. Click on those links and page does not change. But if you set debug=true in config then it works fine. Any Ideas? I see that the problem with views having same name and debug=false option is being corrected in next release. See forums.asp.net/.../2604641.aspx for more info. Hi, I have come across in a situation where I definitely need to use SSL (https) in our MVC web application. I dont find any useful links for using https in MVC apart from Steve Sanderson's blog blog.codeville.net/.../adding-httpsssl-support-to-aspnet-mvc-routing. It works in a sense to convert all links in the page but route module convert them back to normal http once you are actually on that page. Thanks Faisal
http://weblogs.asp.net/stephenwalther/archive/2008/08/06/asp-net-mvc-tip-30-create-custom-route-constraints.aspx
crawl-002
refinedweb
1,621
50.02
The original version wasn't passing anymore because of new test cases that cause overflow. So now we're avoiding computing the differences below if the result will be negative. This avoids overflow in cases where the rectangles are far apart. It looks like this is basically the same thing that @shw1500 was suggesting, but you don't need the extra max function on the outside. The return statement is based on comments from @StefanPochmann. We want to avoid forming the sum area(R1) + area(R2). This avoids overflow in cases where area(R1) + area(R2) will overflow, but area(R1) + area(R2) - overlap(R1, R2) fits in an int. There aren't any test cases for this. Add some maybe? Edit: There are test cases for this, but the overflow didn't matter. New version- avoids overflow when area(R1) + area(R2) overflows but the answer shouldn't.) - overlap_width * overlap_height) + (G - E) * (H - F); // order avoids overflow } }; Second version- avoids overflow when rectangles are far apart) + (G - E) * (H - F) - overlap_width * overlap_height; } }; Old version- overflows for some inputs where the rectangles are far apart. class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int overlap_width = max(min(C, G) - max(A, E), 0), overlap_height = max(min(D, H) - max(B, F), 0); return (C - A) * (D - B) + (G - E) * (H - F) - overlap_width * overlap_height; } }; Nice solution but are you making following assumption? - (C - A) * (D - B) + (G - E) * (H - F) won't cross range of int - Rectangles are parallel to x and y axis Yes, I'm basically making these assumptions. I think we're only considering rectangles parallel to the axes. If they weren't, the formula would be a little more complicated but the basic idea would be similar. With regard to overflow, it's possible that (C - A) * (D - B) + (G - E) * (H - F) would overflow, but the final result shouldn't. In general we can't enforce the order in which the compiler evaluates the terms in the sum, but we could probably write a different expression to avoid overflow... adding some judgment can help pass all cases; class Solution { public: int max(int a,int b){ return a>b?a:b; } int min(int a,int b){ return a>b?b:a; } int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int w=max(min(C,G)>max(A,E)?min(C,G)-max(A,E):0,0),h=max(min(D,H)>max(B,F)?min(D,H)-max(B,F):0,0); return (C-A)*(D-B)+(G-E)*(H-F)-w*h; } }; That is utterly unreadable. I even have to scroll a lot just to see it all. Not good. Of course they're axis-parallel. If not, then not only the formula would be more complicated but also the input! @deck: You can enforce any order by writing it in that order. All those operations are evaluated left-to-right. Also, while the above overflow doesn't matter, your solution doesn't get accepted (anymore) because of overflow in the overlap calculation. Try submitting it again. What I was thinking about when I made the comment about order was the last expression. Here I was kind of lazy but this is not the best way to do it. It is possible that area(R1) + area(R2) overflows, but area(R1) + area(R2) - overlap(R1, R2) fits in an int (or whatever type you're using). We can't rely on the compiler to evaluate terms in that sum in any particular order. We really should avoid "double counting" the overlap and then subtracting it. So we should add the pieces of R1 not in the overlap, the pieces of R2 not in the overlap, and then add the overlap. I haven't worked out the expression yet but maybe someone else wants to take a shot? The evaluation order is specified in the standard, why do you say we can't rely on it? And area(R1) - overlap(R1, R2) + area(R2), i.e., first subtracting the overlap, is safe from overflows during those two operations. Unless you're right about the evaluation order not reliably being left-to-right, which I doubt. But even then, simply (area(R1) - overlap(R1, R2)) + area(R2) should really guarantee it. Don't tell me the compiler ignores parentheses :-) Relying on some order of evaluation causes a lot of bugs. In general you can't. Here's what Stroustrup has to say about it in The C++ Programming Language 4th Edition (page 259): "The order of evaluation of subexpressions within an expression is undefined. In particular, you cannot assume that the expression is evaluated left-to-right. For example: int x = f(2) + g(3) // undefined whether f() or g() is called first Better code can be generated in the absence of restrictions on expression evaluation order. However, the absence of restrictions on evaluation order can lead to undefined results. For example: int i = 1; v[i] = i++; // undefined result The assignment may be evaluated as either v[1] = 1 or v[2] = 1 or may cause some even stranger behavior. Compilers can warn against such ambiguities. Unfortunately, most do not, so be careful not to write an expression that both reads and writes an object, unless it does so using a single operator that makes it well defined, such as ++ and +=, or explicitly express sequencing using , (comma), &&, or ||. The operators , (comma), && (logical and), and || (logical or) guarantee that their left-hand operand is evaluated before their right-hand operand..." So you can rely on , (comma), &&, and || to evaluate their arguments in order, but that's basically it (well, also the conditional expression (? :) and function call operators). You also can't rely on arguments to a function to be evaluated in any particular order, which is another source of bugs and exception unsafe code... The issue is that the subexpressions have equal precedence, so it's not an issue of order of operations. The compiler is granted quite a bit of freedom here. Consequently, the compiler may also optimize away or re-associate parenthesis by default, but there could be compiler options available to prevent this. No. You're reading that wrong. How did you not notice that f(2) + g(3) even only has one operation? He's talking about the order of evaluating the SUBexpressions / operaNDS. Not about the expression and its operators. From page 257 of the same book: Unary operators and assignment operators are right-associative; all others are left-associative. For example, a=b=c means a=(b=c) whereas a+b+c means (a+b)+c. In f(2) - g(3) + h(4) it's undefined in which order f(2), g(3) and h(4) get evaluated, but it is defined that - is evaluated before +. OK I see what you're saying now. The compiler parses the expression f(2) - g(3) + h(4) like (f(2) + g(3)) + h(4). It should whether or not their are parenthesis. So the result of the subtraction has to be available before the addition is happens. I'm going to update the solution... Is there any chance that the parenthesis could be optimized away at some point long after the parse tree is built? I think that's what I'm still worried about, but I can't find a resource on that. As the order is standardized and you're not causing overflow, no, I don't think the correct behavior could be "optimized away". That would be violating the standard. Apparently some C/C++ compilers turn for example x < x+1 into true (or 1) if x is an int because only overflow could make it false and in C/C++, overflow behavior for int isn't defined so the compiler is allowed to do that. So if I use x < x+1 and expect it to be false if x is MAX_INT, then the compiler might mess that up for me. But that's because I'm trying to use something that is undefined. It should never break a safe correct calculation that only relies on defined behavior. I see your answer now says "There aren't any test cases for this. Add some maybe?". You're wrong. There is such a case. You just don't notice it because after the addition overflows, the following subtraction overflows right back, to the correct end result. That's not guaranteed by the standard, but it's pretty much a fact. That's why I earlier said that "[that] overflow doesn't matter". Also see this thread. See this question and its answers and their links for a bit more about integer overflow in C/C++. That's interesting that the test cases worked. Once the signed intermediate result overflows can't we not rely on the answer anymore? It overflows back here, but in general unsigned overflow is undefined as explained in the link. What if we just changed the area computations to unsigned, then returned the requested signed result at the end? Since the unsigned computations are done modulo 2^n overflowing and then subtracting back would seem OK. Well you can't rely on it in the sense of it being guaranteed by the standard, but you pretty much can rely on it in practice. Just don't rely on it for anything critical :-). Like someone said on that StackOverflow page: "undefined behaviour" doesn't mean "doesn't work" With most hardware/compilers, signed integers also work "modulo 2^n". If I'm not mistaken, then in Java it's even "defined" to be that way: If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. Still a bit wide and hard to read, but a lot better :-). Why do you redefine max and min, though? And why do you still max with zero after already having ensured that the value is non-negative? Redefinition of max and min is not necessary.I defined them because I didn't know those two functions are included before. The second question: For two int in a 32 bits machine : A and B. When A>B, A-B is not always non-negative,for example A=1500000000 and B=-1500000000, A-B = -1294967296,so the redundant check is just to prevent overflow. But if you get 1500000000 and -1500000000 there, then the overlap is actually 3000000000 wide (or high), not 0. Zero is wrong (although it doesn't matter). Also, that can only happen if both of the two given rectangles are at least 3000000000 wide (or high), so they must both have height zero because we're told that the result fits in an int. And then h will be zero, so the overflow in w won't matter. That said, my question was bad and you're right in your reply in general. Thanks. Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/15830/simple-0ms-c-solution-using-min-and-max-updated-again-to-avoid-overflow
CC-MAIN-2017-47
refinedweb
1,872
64.1
how to validate if response field is expected to return X and Y. Hello , I want to assert on a a response field(string comparison assert) . But the response field value returns X and Y . Both values are Valid. I want my assertion to pass the test in both cases. I know we can assert on one expected value. can you please advise which assertion to use to validate the same field with two expected values. I am using Parasoft SOA test 9.9 Regards, Neil. Tagged: 0 It sounds like you want to use the "OR Assertion" (XML/JSON Assertor tool). In other words, you create a validation for "X", a second validation for "Y", and then join them with an "OR". Here is how it will look like in the JSON Assertor: Thank you for your feedback. it's very helpful. Hello Andrey, The OR assertion worked when I assert on item[1]... But when I assert of all fields, it's throwing an error. I am trying to assert on a fields(category) in response which occurs multiple times in the response. I want to the test to pass if the value of Category is 'X' or 'Y'.. The assertion should check all the occurrences of Category field in response and pass when it has X or Y. Hi Neil, The simplest approach in this case might be to write a custom assertion where you put the "OR" logic into the custom script. Hello, Can I use JsonSlurper utility? import groovy.json. JsonSlurper if No, Can you give me an example how to read the response values and assert them with expected results. Good morning Neil, sips coffee Another way to complete your scenario is by extracting the repeated element values using a databank and storing them into a writable data source. You could then create a new messaging client containing the writable data to pass the desired values through an OR assertion. Give this a shot I have to add messaging client to just validate a fields which is expected to be 'X' or 'Y' in response. usually to assert http status codes. we can give as below. 200;500 In this case the test will pass if the status code is 200 or 500. anyways I will try what you mentioned above.
https://forums.parasoft.com/discussion/2862/how-to-validate-if-response-field-is-expected-to-return-x-and-y
CC-MAIN-2019-09
refinedweb
387
74.69
AMucha 2009/09/21 Use the excellent little package pdf4tcl. It can directly transform a canvas into a pdf-file. Leave the rest of the hard work for the people from Adobe :-) (See Printing under Windows) # Example printing a canvas with pdf4info package require pdf4tcl ; # Get the package pdf4tcl::new mypdf -paper a4 -margin 15mm ; # make a new pdf-object mypdf startPage ; # make a new page # make and fill a canvas .canv # ... mypdf canvas .canv ; # then put the canvas on your pdf-page mypdf write -file canvas.pdf ; # write to file mypdf destroy ; # clean up # printing: eval exec [auto_execok start] AcroRd32.exe /p /h [list [file normalize canvas.pdf ]] KBK: I've seen a number of requests for ways to print the contents of a canvas under Windows. Alas, there is no graceful way. Nevertheless, there are approaches that work sometimes, and can be useful. For the most part, they work by using the 'postscript' command of the canvas widget to render the canvas as PostScript, and then either sending the result directly to a PostScript printer, or piping it through Ghostscript to interpret it and pushing the result at a Winprinter.One tool that helps a lot is PrFile32.exe, available from: [1]. Without this clever little program, Windows makes it insanely difficult to send a PostScript file to a PostScript printer. With it, it's a simple as saying exec prfile32.exe /q fileName.ps &IDG Prfile is a great utility. In addition to the above, it will automate piping through ghostscript to print PS on non-PS printers, and lets you set up automatic spooling, so that any file written to a designated directory automagically prints.RA Just to make it clear: prfile does not contain a postscript renderer, you have to install that too and configure pfile to use it to let prfile print postscript in the above example.I also find it useful to be able to carve up a canvas that's bigger than a page and print it in overlapping tiles. I often use the following code to do it.The code has obvious bugs that it doesn't allow a user-specified scale factor but rather assumes that the printout should show 150 screen pixels to the inch. It also hard-codes the assumption of US letter-sized paper, although the margins are wide enough that it should work with A4. I present it as a starting point for anyone who wants to try to do better. #------------------------------------------------------------------ # # printcanvas.tcl -- # # Tcl procedure to spool a canvas via PrFile32. # #------------------------------------------------------------------ package provide printcanvas 1.0 namespace eval printcanvas { namespace export printcanvas # CONFIGURATION -- Path name of the PrintFile program. variable prfile {C:\Program Files\PrintFile\PrFile32.exe} } #------------------------------------------------------------------ # # printcanvas::printcanvas -- # # Print the contents of a canvas # # Parameters: # w -- Path name of the canvas # # Results: # None. # # Side effects: # Canvas content is converted to PostScript and spooled via # PrintFile. If the canvas is larger than a printer page, # a file is created and spooled for each page. # #------------------------------------------------------------------ proc printcanvas::printcanvas { w } { variable prfile set name [file join $::env(TEMP) [pid]page] set cmd [list exec $prfile /q /delete] set i 0 foreach { xmin ymin xmax ymax } [$w cget -scrollregion] {} for { set x $xmin } { $x < $xmax } { incr x 1200 } { for { set y $ymin } { $y < $ymax } { incr y 825 } { set fname $name[incr i].ps $w create text [expr { $x+1210 }] [expr { $y+835 }] \ -text "Page $i" -anchor nw \ -tags printCanvasPageNo \ -font {Helvetica -18} eval [list $w create rectangle] \ [$w bbox printCanvasPageNo] \ [list -fill white -outline {} \ -tags printCanvasPageNoBg] $w raise printCanvasPageNo printCanvasPageNoBg $w postscript \ -file $fname \ -colormode gray \ -x $x -y $y -width 1350 -height 975 \ -pageheight 6.5i -pagewidth 9.0i \ -rotate true lappend cmd $fname $w delete printCanvasPageNo $w delete printCanvasPageNoBg } } eval $cmd return } GPS: How does this compare to Tkprint? KBK (7 November 2000): I've never been able to get tkprint to generate output at other than microscopic size; maybe I'm missing something in how it's set up. Also, if you change the value of prfile to the appropriate 'lpr' command, the code works on Unix as well. ClassyTk [2] has support for native printing of the Canvas on Windows. (It is a hack, but works for me) JD: Michael Schwartz's extensions GDI/HDC/Printer [3] provide a general context for modelling a printer as a generic graphics context and sending arbitrary data to it. I think it's the most general solution if you don't mind getting a bit low-level. A canvas printing utility is included (prntcanv.tcl) as a convenience, but does not handle embedded windows (i.e. canvas window objects) - but then again none of the other solutions seem to handle embedded windows either.If you try to generate postscript out of a canvas (via $canvas -postscript) that has embedded windows in win32, you get a nasty error and wish aborts.Update to the above statement: The problem with generating postscript from a canvas with embedded windows has been fixed as of release 8.4.1. The only remaining issue now is that only embedded windows that are mapped to the screen (i.e. visible) are included in the postscript output. But as long as you can fit your output in a single non-scrollable canvas, the canvas -postscript output is the best multiplatform way to print. The PrintFile program + Ghostscript/GSview make a perfect companion under windows.JCG: Not strictly true, apparently. With Tk 8.4.5 under Windows, windows embedded directly within a canvas are printed fine, but if you embed a frame and then a button within the frame the generated PostScript contains a black box instead of the button. We are currently using a BLT graph with an embedded frame or canvas and printing the whole thing with BLT's postscript method (.graph postscript ...) mjk: Contrary to popular(?) belief, using GhostScript to print a canvas under Windows is pretty easy. All you need is a GhostScript [4] package installed.The following example simply opens a pipe to gswin32c.exe, sends PostScript data from the canvas to the pipe and closes the pipe. There is no need for temporary files. The best thing with GS is that it offers printer dialog (native Win32 Common Dialog), where you can select a printer and change printer settings. package require Tk # Path to the gswin32c.exe: set gspath {C:\\Program Files\\gs\\gs8.14\\bin\\gswin32c.exe} # Create a canvas: canvas .test -background white -width 400 -height 400 pack .test # Add something for printing: .test create text 250 250 -text "This is a test." .test create arc 100 100 40 40 .test create rectangle 100 300 150 350 .test create line 300 300 350 350 .test create line 300 350 350 300 # Open pipe to gs: set gs [open "|\"$gspath\" -q -sDEVICE=mswinpr2 -dNOPAUSE -dBATCH -" w] # Print the page: update .test postscript -channel $gs # Close the pipe, sends page to printer: close $gs SVH: Because printing using GhostScript is a very powerfull feature, I created a separate page for it. See Printing a canvas using GhostScript .
http://wiki.tcl.tk/949
CC-MAIN-2014-52
refinedweb
1,177
64.2
Configuration and deployment of an dynamic-server Resin cluster. Resin's cloud support is an extension of its clustering. It is the third generation of Resin clustering, designed for elastic clusters: adding and removing servers from a live cluster. A triple-redundant hub-and-spoke network is the heart of a Resin cluster. The three servers that form the hub are called the 'triad' and are responsible for reliability and for load-balancing clustered services like caching. All other servers can be added or removed without affecting the shared data. Services like clustered deployment, caching, JMS, and load-balancing recognize the new server and automatically add it to the service. When you delete a server, the services will adapt to the smaller network. The triad hub-and-spoke model solves several clustering issues we've discovered over the years. The three primary issues are the need for triple redundancy, managing dynamic servers (particularly removing servers), and giving an understandable user model for persistent storage. Triple redundancy is needed because of server maintenance and load-balancing. When you take down a server for scheduled maintenance, the remaining servers have extra load and they are more vulnerable to a server failure. A triple-redundant hub with one server down for maintenance can survive a crash of one of the two remaining servers. The load is less, too. When one server is down for maintenance, the other two servers share an extra 50% load each. With only a backup system, the extra server would double its load. Dynamic servers benefit from the hub-and-spoke model because the 'spoke' servers are not needed for reliability. Because they don't store the primary cache values, the primary application deployment repository, or the queue store, it's possible to add and remove them without affecting the primary system. With other network configurations, removing a server forces a shuffling around backup data to the remaining servers. The triad also gives a simpler user model for understanding where things are stored: data is stored in the triad. Other servers just use the data. Understanding the triad means you can feel confident about removing non-triad servers, and also know that the three triad servers are worth additional reliability attention. The standard /etc/resin.properties configuration lets you configure a triad and dynamic servers without a few properties. To configure three static servers for the triad hub, enable dynamic servers, and select the "app" cluster as the default dynamic server, use csomething like the following in your /etc/resin.properties. ... # app-tier Triad servers: app-0 app-1 app-2 app_servers : 192.168.1.10:6800 192.168.1.11:6800 192.168.1.12:6800 ... # Allow elastic nodes to join the cluster (enable for cloud mode) elastic_cloud_enable : true # The cluster that elastic nodes should join - each will contact a Triad server # Use a separate resin.properties file for each cluster home_cluster : app To start the server, you can use the "start-all" command. The start-all with start all local servers (by comparing the IP to the IP addresses of the current machine.) If no local servers are found, start-all will start a dynamic server using the <home-cluster>. unix> resinctl start-all If you've installed Resin as a Unix service, it will be started automatically when the server starts. You can either use the /etc/init.d resin command or the "service" if it's available. The service start is equivalent to a resinctl "start-all". # service resin start If you are creating a custom resin.xml or modifying the default one, you can configure the servers explicitly in the resin.xml. The baseline cloud configuration is like a normal Resin configuration: define the three triad servers in your resin.xml, and copy the resin.xml across all servers. You will attach new servers to the cluster when you start it on the command-line. You can still define more servers in the resin.xml, or fewer if you have a small deployment; it's just the basic resin.xml example that uses three servers. The baseline configuration looks like the following: You can configure the cluster using resin.properties without needing to modify the resin.xml. For the hub servers, add an IP:port for each static server. For the dynamic servers, enable elastic_cloud_enable and home_cluster. You can also configure the resin.xml directly to add the servers individually. <resin xmlns=""> ... <home-cluster>my-cluster</home-cluster> ... <cluster id="my-cluster"> <server id="a" address="192.168.1.10" port="6800"/> <server id="b" address="192.168.1.11" port="6800"/> <server id="c" address="192.168.1.12" port="6800"/> <resin:ElasticCloudService/> ... </cluster> ... </resin> The first three <server> tags in a cluster always form the triad. If you have one or two servers, they will still form the hub. One server acts like a Resin standalone; two servers back each other up. More than three <server> tags form static servers acting as spoke servers in the hub-and-spoke model. The static servers are identical to any dynamic servers, but are predefined in the resin.xml The <resin:ElasticCloudService/> enables dynamic servers. For security, Resin's is to disable dynamic servers. You can also add a <home-cluster> which provides a default for the --cluster command-line option. Before starting a server, your new machine needs the following to be installed: Since these three items are the same for each new server, you can make a virtual machine image with these already saved, use the VM image for the new machine and start it. To start a new server, you'll add a '--cluster' option with the name of the cluster you want to join. unix> resinctl --elastic-server --cluster my-cluster start If you don't have a <resin-system-auth-key> in the resin.xml, and you do have admin users defined in the AdminAuthenticator, you will also need to pass a -user and -password arguments. The new server will join the cluster by contacting the triad. It will then download any deployed applications or data, and then start serving pages. The triad will inform cluster services about the load balancer, services like caching, admin, JMS, and load-balancer. To remove a dynamic server, just stop the server instance. The triad will keep its place in the topology reserved for another 15 minutes to handle restarts, maintenance and outages. After the 15 minutes expire, the triad will automatically remove the server. Although the three static server configuration is a useful baseline for understanding Resin's clustering, you can configure fewer or more static servers in the resin.xml. Defining fewer servers than three in the resin.xml is only recommended if you actually have fewer than three servers. Defining more servers than three in the resin.xml depends on your own preference. Having only three servers in the resin.xml means you don't need to change the resin.xml when you add new servers, but listing all servers in the resin.xml makes your servers explicit - you can look in the resin.xml to know exactly what you've configured. It's a site preference. If you have fewer than three servers, you can define only the servers you need in the resin.xml. You won't get the triple redundancy, but you will still get a backup in the two-server case. For elastic configurations, it's possible to use a single static server in the resin.xml, for example if your load was between one and two servers. If your site always has two servers active or three servers, you will want to list them in the resin.xml as static servers, even through Resin would let you get away with one. Listing all the servers in the resin.xml ensures that you can connect to at least one in case of a failure. In other words, it's more reliable. With more static servers than three, you can also add them to the resin.xml. You can also define dynamic servers in the resin.xml if their IP addresses are fixed, because Resin will dynamically adapt to stopped servers. If you use the static/elastic technique, you still need to keep the triad servers up. In other words, you'll adjust load by stopping servers from the end, shutting down server "f" and keeping servers "a", "b", and "c". Cluster deployment works with dynamic servers to ensure each server is running the same application, including the newly spun-up dynamic servers. The new server will ask the triad servers for the most recent application code and deploy it. While it's nice for the convenience (skipping the copy step), it's more important for the extra reliability. Cloud deployments should generally use the cluster command-line (or browser) deployment instead of dropping a .war in the webapps directory because the cluster deployment automatically pushes deployment to new servers. With a cluster command-line deployment, the new server will check with the triad hub for the latest deployment. If there's a new version, the dynamic server will download the updates from the triad hub. The cluster deployment ensures all servers are running the same .war deployment. You don't need external scripts to copy versions to each server; that's taken care of by a core Resin capability. unix> resinctl deploy test.war If you don't have a <resin-system-auth-key> and do have administrator users configured, you will also need to pass the -user and -password parameters. The basic configuration for cluster deployment is the same as for single-server deployment. Resin uses the same <web-app-deploy> tag to specify where cluster deployment should be expanded. If for some reason you deploy a .war in the webapps directory and deploy one on the clustered command-line, the cluster will take priority. In the following example, a test.war deployed in the command-line will be expanded to the webapps/test/ directory. The example uses <cluster-default> and <host-default> so every cluster and every virtual host can use the webapps deployment. <resin xmlns=""> ... <cluster-default> <host-default> <web-app-deploy </host-default> </cluster-default> <cluster id="app-tier"> ... </cluster> ... </resin> See the load balancer documentation for more information about the load balancer. When the new server starts, it needs to receive the new requests from the load balancer. If you're using Resin's load balancer (or Resin's mod_caucho), the load balancer will send HTTP requests to the new server. The load balancer must be configured in the same resin.xml as the application tier because the app-tier cluster needs to communicate with the load balancer tier. Resin's load balancer is configured in the resin.xml as a web-tier cluster with a URL rewrite rule dispatching to the app-tier cluster. <resin xmlns="" xmlns: <cluster id="web-tier"> <server id="web-a" address="192.168.1.20" port="6800"/> <server id="web-b" address="192.168.1.21" port="6800"/> <proxy-cache/> <host id=""> <resin:LoadBalance </host> </cluster> <cluster id="app-tier"> <server id="app-a" address="192.168.1.10" port="6800"/> <server id="app-b" address="192.168.1.11" port="6800"/> <server id="app-c" address="192.168.1.12" port="6800"/> ... </cluster> </resin> With the example configuration, Resin will distribute HTTP requests to all static and dynamic servers in the app-tier. Because the HTTP proxy-cache is enabled, Resin will also cache on the web-tier. If you're not using Resin's load balancer, your cloud will need some way of informing the load balancer of the new server. Some cloud systems have REST APIs for configuring load balancers. Others might require a direct configuration. Resin's load balancer does not require those extra steps. Resin's cluster-aware resources adapt to the added and removed servers automatically. A new server can participate in the same clustered cache as the cluster, see the same cache values, and update the cache with entries visible to all the servers. The Resin resources that are automatically cache-aware are: Resin's clustered caching uses the jcache API which can either use a jcache method annotation to cache method results or an explicit Cache object injected CDI or JNDI. By minimizing the configuration and API complexities, Resin makes it straightforward to improve your performance through caching. The jcache method annotation lets you cache a method's results by adding a @CacheResult annotation to a CDI bean (or servlet or EJB.) The following example caches the result of a long computation, keyed by an argument. Because the cache is clustered, all the servers can take advantage of the cached value. import javax.cache.CacheResult; public class MyBean { @CacheResult public Object doSomething(String arg) { ... } } When using cached injection, you'll need to configure a cache instance in the resin-web.xml. Your code and its injection are still standards-based because it's using the CDI and jcache standards. <web-app xmlns="" xmlns: <resin:ClusterCache </web-app> The cache can be used with CDI and standard injection: package mypkg; import javax.inject.*; import javax.cache.*; public class MyClass { @Inject private Cache<String,String> _myCache; public void doStuff() { String value = _myCache.get("mykey"); } }
http://caucho.com/resin-4.0/admin/cluster-cloud.xtp
CC-MAIN-2015-35
refinedweb
2,214
57.57
0 Hey! So i have started learning c, quite refreshing when i normally code in Java :) I have this task where i need to store three int values in an unsinged int via bitwise operators. Its for a RGB picture where the colour is limited to 256. I have done this succesfully(i hope :) ) : unsigned int make_pixel(int red, int green, int blue) { unsigned int colour = 1; colour = colour << 9; //makes room for a 256bit colour printf("%u\n", colour); colour = red | colour; printf("red %u\n", colour); colour = colour << 8; //makes room for a 256bit colour colour = colour | green; printf("green %u\n", colour); colour = colour << 8; //makes room for a 256bit colour colour = colour | blue; printf("blue %u\n", colour); return colour; } Now i have also retrived the first value (the red one,): int get_red(unsigned int p) { return (p>>16)-512; } My problem is that i do not know where to start on the middle and last values. My first thought was that you could 'push' the last value out with colour>>8 and catch it. But it doesn't work like that apperently :) I have tried to make a chart of how the unsigned int should look at the end, if its wrong than my understanding of bitwise operators is wrong aswell :P : 1: 1 9<-: 100 000 000 red ->: 1rr rrr rrr 8<-: 1rr rrr rrr 000 000 00 green: 1rr rrr rrr ggg ggg gg 8<-: 1rr rrr rrr ggg ggg gg0 0 000 000 blue->: 1rr rrr rrr ggg ggg ggb b bbb bbb Edited 4 Years Ago by Krokcy
https://www.daniweb.com/programming/software-development/threads/434139/store-three-ints-in-one-unsigned-int-and-retrieve-them
CC-MAIN-2016-50
refinedweb
267
54.16
Published 2 months ago by segun i am trying to update my user details in the database but i am getting the above error here is my code on a gist file thanks in advance : Missing argument 2 ... obviously your id that you are not passing to the controller. How is Laravel supposed to know which profile to update? Look at your update() method. It's expecting 2 parameters, the 2nd one being the users $id. That's what the error is referring to (missing argument 2) Now look at your route. It's not accepting, or passing an ID back to the controller. Your form also needs to post to /profile/id, where id is the id of the user you are updating. why u just jumped learn how to update work in laravel, watch laravel from scratch 2017, and in your code if u use update your data so use patch method not post also u are not passing Id in your action url and route also, I think u asked so many questions which is very basic questions, and if given 1 day to laravel basic then I don't think so u asked these types of questions, stop and go learn basic of laravel Here is the snippet of your form <form class="form-horizontal" role="form" method="POST" action="{{ url('/profile') }}"> {{ csrf_field() }} <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}"> <label for="name" class="col-md-4 control-label">User Name</label> <div class="col-md-6"> <input id="name" type="text" class="form-control" name="name" value="{{ Auth::user()->name}}" required autofocus> @if ($errors->has('name')) <span class="help-block"> <strong>{{ $errors->first('name') }}</strong> </span> @endif </div> </div> <!--Codes omitted --> In the <form class="form-horizontal" role="form" method="POST" action="{{ url('/profile') }}"> You must change it into: <form class="form-horizontal" role="form" method="POST" action="{{ url('/profile/' . Auth::user()->id) }}"> and from your routes/web.php change this line Route::post('/profile', [email protected]'); into Route::post('/profile/{id}', [email protected]'); sometime if you watch the video you still have some question and you learn by asking i am sorry if i am not that good as you yet @vipin93 and you don't have to answer any of my question, there are millions of programmers out there that are ready to help, and i learned by asking and don't forget anything you already know will be simple as fuck in your eyes and be difficult in the eyes of those that does not know it and Laracast did this section for asking for help on what you don't know. Yow, we don't need to argue about nonsensical things here. There are times people forget to remember where they start. And sometimes, people becomes arrogant and thinks they know better. I once was like that. Well, everyone will sooner or later. There are a lot of ways to learn. Some people learns from books, videos, etc while some learn by seeking others. No need to bring someone down just because "they're asking stupidly, simple things". Let's just help them and guide them to the right path. Anyway, let's not sidetrack here, @segun have you fixed the problem? @segun what u said to me, same to u, and one thing u dont have read my answered fully , i have answered u are missing two things. and follow @silverxjohn answer and add one more thing. and one thing again same to u happy day {{ method_field('PATCH') }} Route::patch('/profile/{id}', [email protected]'); thanks everybody i have done it, before i did it without the id, but now i use the id aproach. @silverxjohn @vipin93 @Cronix @Snapey . thank you everybody, i have watch the video about one three weeks ago, in fact many video but i learn a lot by asking question some of the question i do asked i knew them but i asked to get other people opinion and my thanks especially go @silverxjohn God bless you and everybody including my friend @vipin93. @segum at the time of beginning when i start learning laravel, I'm also same as u I asked(even which very basic) every questions from this forum, many one suggested me I have to first learn basic but I never listen, because Why should I, if my problem will solve from this forum, so after many one suggested first learn basic so I decided to watch series laravel-5.** and @jeffery explain very well after,this when I faced any problem I try to implement own idea and it's worked after one or two attempt, sometimes if I was unable to solve then i asked.So want to say only this if u have basic then your 50-70% problem will solved by yourself. That's it I want to say u. Sign In or create a forum account to participate in this discussion.
https://laracasts.com/discuss/channels/laravel/missing-argument-2-for-apphttpcontrollersprofilecontrollerupdate
CC-MAIN-2017-22
refinedweb
824
65.35
Microsoft Reacts To Feedback But Did They Get Windows 8.1 Right? 543 MojoKid." I tested Windows 8.1 (Score:5, Funny) Windows 8.1 is by far the best Windows there is! Re:I tested Windows 8.1 (Score:4, Interesting) So how much are they paying for posts these days? I figure it must be down from the glory days of slashdot. Re:I tested Windows 8.1 (Score:5, Funny) Re: (Score:3, Funny) Are they hiring ? I have an impressive history on this site and I think I can contribute significantly to the cause. Re:I tested Windows 8.1 (Score:5, Funny) That explains why APK owns a yacht. With extra storage below deck to store his host files. Soviet Microsoft (Score:3) Re: (Score:3, Interesting) Re: (Score:2, Insightful) Newsflash: Microsoft doesn't give a flying fuck what is said about them on Slashdot. Microsoft could cure cancer, create a sustainable moonbase, and bring world peace, and people here would be whining that they really liked cancer, the moonbase wasn't 100% open source, and the world peace was going to be worse than Microsoft Bob. Those posts are trolls. EVERY. SINGLE. ONE. And you people keep falling for them EVERY. SINGLE. TIME. Even when it's patently obviously a t Re:I tested Windows 8.1 (Score:5, Interesting) Microsoft doesn't give a flying fuck what is said about them on Slashdot. Heh. Even Herb Sutter (from the Visual Studio team) has mentioned Slashdot in his talks at Channel 9 [msdn.com]. I'm sure microsofties occasionally bump on the comments on Slashdot too. This is a quite well-known technology website. I agree that the impact is probably still quite small, but it's not a complete "flying fuck". Re:I tested Windows 8.1 (Score:5, Funny) Re:I tested Windows 8.1 (Score:5, Insightful) We developers as Microsoft definitely read Slashdot. Most of us, dare I say. And when there is blatant FUD and misinformation, I myself have stepped in and corrected it with links and citations. If I am giving an opinion piece, I usually post as AC and identify that I work at Microsoft. But I don't go racing for the first post with some normative statements with a username of JustANormalGuy. This guy is obviously trolling Slashdot by pretending to be a shill. Re:I tested Windows 8.1 (Score:4, Insightful) Re:I tested Windows 8.1 (Score:5, Insightful) I totally favor fixing things that aint broke. Sometimes people don't know things are broke until you show them a better way. What I don't like is lack of options. I don;t even care if Metro is the default. I should be allowed to turn it off as an option. There is no reason to force me to use it if I don't like it. I don't think they should remove it either. I'm sure some people like it. If windows 8 had the ability to turn off metro, it would be just like windows 7 with a few improvements, rather than a disaster. Re: (Score:3) After all, do you think Answers in Genesis and Jack Chick are good biology references? Some people do think that is the correct response. Because it is a genetic flaw that there are many humans who demand smack in the face, undeniable, impossible to deny proof of something like climate change, but are positively sure, undeniably certain, no possibility of doubt certain that therre is a sky fairy who is kind and gentle, but itching to torture humans forever and ever, amen - if they don't worship him. And they have been willing to kill, maim and otherwise cause harm to others who do not share t Re: (Score:2, Insightful) Fu*k all you pretentious assholes that think they speak for all technical savvy users. I have been supporting Windows since Windows 3.11 Snowball so you can guess that I am one of the elderly folks on Slashdot. I get paid by a university to support applications used on Windows, OS X, and mobile devices. Guess what, I really like Windows 8. Why are so many of you afraid of change? After spending a hole 5 minutes customizing the new 'Modern UI' Start screen, I can find the apps I want much faster and with less Re:I tested Windows 8.1 (Score:5, Insightful) I can't believe I'm replying to the troll but heres a list. First and foremost. I don't and never will use a tablet or touch interface for real work so I don't want charms that are huge stealing my screen real estate, or windows that force full screen or any arbitrary size. I want windows that ** I ** can resize to any size I want and have multiples on the screen at one time. i want everything small and precise because I multitask... a LOT.... and with multiple large monitors. I DON'T want an app store that thinks it controls what I can and can't install on my own devices. I shouldn't have to be on a domain to bypass app store crippling of my machine. I say what software goes on and comes off of my own PC and no one else. For my users on the network, hierarchical menus for apps based on purpose is still superior when you are building systems for people so unsavvy they don't even know the name of an app to search for. I don't want cloud integrated into everything by default. As an add-on its just fine, but I don't trust other people and companies with most of my stuff and I surely didn't trust Microsoft even BEFORE this NSA mess. I also want things to work the same way every time. If I click on an icon I want it to start a new instance. Every. Time. I can manage my own windows and decide when I want new ones and when I want pre-existing ones. I don't want Windows trying to decide when I want to maximize a window by getting too close to the top. If I want it maximized, I'll click a button to do so and so on and so on and so on...... Re:I tested Windows 8.1 (Score:5, Insightful) Why are so many of you afraid of change? Once you've completely misidentified the problem, you'll never find the solution. But I'm sure it makes it a lot easier to dismiss criticism if you can pretend it comes from somewhere unreasonable. The fact of the matter is, people love change... iff it's change with significant benefits. People like changes for the better. I've heard "I wish this worked that way" a hundred times, and people are ecstatic when you come back and give them an update that makes it work the way they said. People love change if it's a genuine improvement. People only hate change when they can't see any point to it. They may not be formal about it, but everyone runs a bit of a cost/benefit analysis in their minds, and when there's an obvious cost for no significant benefit, or to fix "problems" that they never saw as a problem to begin with, they react negatively, because that's the logical response to a change of that nature. Why is that so hard? Irrelevant question. The important question is, "why is that even necessary?" It might have a good answer, but if you can't make that answer clear to people, expect them to react negatively when you ask them to do what they see as unnecessary things for little apparent benefit. Re:I tested Windows 8.1 (Score:5, Insightful) Hey, guess what.. I've been using computers since the days of the Commodore Pet. I was using and supporting microsoft since the days of MSDOS 3... And I was using UNIX before that. The bones I've had to pick with MS were originally because they had pretty shoddy tools, compared to the UNIX (for DOS), and no multi-tasking. Through the Windows 3 era, I thought it compared poorly to the Apple UI, and it performed absolutely shoddily when compared to OS/2.. I saw MS's marketing engine fire up, and scare people (needlessly) into just using their product, not by dint of superiority, just because they had cash to throw around. Dirty tricks really were the name of the game. With the advent of Win95, Microsoft actually had a GUI which I had to admit was well thought out. It did what was wanted in a simple and no fuss way. Sure, it was still a layer above DOS, but it was definitely usable, and actually comfortable.. They'd done their homework on that.. Fast forward to now. They force a UI that's pretty decent for a tablet (quite like how it handles on a tablet) onto a desktop.. And I hate it on the desktop.. The idea of using it for Servers is filling me with dread.. The ergonomics of it are atrocious in that use case; I'm just glad you can do everything in Powershell.. That really is going to be the start of a move to 'Core' install, and just run things via powershell. It's mostly how I do it these days, but I do enjoy the flexibility of the Win7 GUI (I think Win7 is the best OS MS have put out to date). I like the tech improvements behind the scenes in Win8, but after using it, I refuse to install it on my home workstation, and work is never going to move to that version (apart from tablets/kiosks, where it shines). In an attempt to grab the niche market, they seem to be eviscerating their core one.. Which I really just don't understand.. The strategy that would work would be to have an API that works across all the forms (tablet, kiosk, desktop) with a GUI that you can swap between depending on your needs.. If Android releases get the desktop done nicely (and optimised for desktops, not tablets), then MS could be in with a bigger fight than it expects.. In short, it's a good OS ruined by changes that alienate most people. Not just because they "have to learn something new" (which was their big thing about not shifting to Linux), but because it makes changes with no advantage, and quite frequently to their detriment. Re:I tested Windows 8.1 (Score:4, Funny) Yeah, I started using windows when it was 1.0 too. I like Windows 8. It boots faster, is more responsive, the redone task manager is awesome (finally), better cache management (kind of important to me since I have 64GB of RAM). The start screen is ok, I rarely use the icons, I just type what I want and hit enter -- I actually go to the start screen maybe twice a week, so it doesn't bother me at all. All my important apps are either pinned to the taskbar, or have an icon on my desktop. Not a big fan of the Metro/Modern UI, but I only use the desktop as I always have. Removing the start "button" actually gained me some space on my task bar, so I actually like it gone. Saying it's the biggest POS you have ever seen and having used all the versions of Windows, puts you in a very small club, so I would like to introduce you to Microsoft Bob. Re: (Score:3) Yeah, there are a lot of people here who don't know how to moderate at all. Nothing I said was trolling, just my opinion based on actually using it every day. Oh well. I guess truth is trolling for those who only want to hate. Re: (Score:2, Funny) Why can't we just admit, Windows is just Poo Poo now? For some of us, it's our duty to make sure Windows never drops to number two. Although it's always a real gasser to float some ideas about keeping other OSes down in the night soil, they're all excrement when the shit hits the fan like with Vista or Windows 8. Re:I tested Windows 8.1 (Score:5, Informative) I KNOW there are other archectural issues that stick in my throat about windows but those three I think about and deal with all the time. Re:I tested Windows 8.1 (Score:5, Insightful) Does the start button work like this: [penny-arcade.com] Re:I tested Windows 8.1 (Score:5, Insightful) Full screen switch produces loss of context (Score:4, Interesting) Re: (Score:2, Funny) I love Windows 8.1 too! It's so square that it makes me feel good about being square. I just adore the new square start button. Everyone would be so much happier if they just had this button as part of their day. And the new start screen is so awesome! It makes me feel like a race car driver, with all the blinking lights. My most favorite part of 8.1, though, is how Microsoft optimized the NSA uploads. It's now so smooth, I hardly can tell when the government is reviewing my files. I'm sure 8.1 is going to Re: (Score:2) Windows 8.1 is by far the best Windows 8 there is! Fixed that for ya. Re: (Score:3, Insightful) (1) You can't prove it is an ad agency rather than an obvious troll. You can sue Microsoft and try to use discovery to find out, but how much money are you willing to spend? That would bankrupt Slashdot. And then you'd probably find out it wasn't Microsoft. (2) The posts are irrelevant. In fact, you guys piling on by replying with your whining is much worse for the quality of discussion than the posts you object to. If you and the others had just shut up and moved on, the moderation system would have taken c Re:I tested Windows 8.1 (Score:5, Funny) Yeah! We only like paid negative MS posts here! Start Button in 8.1 is useless. (Score:5, Informative) I downloaded the dev preview. Yeah, there's a Start button. Big deal. All it does is drop you into Metro -- pardon me. Into The-Interface-Formerly-Known-As-Metro. There's still no Start Menu, which is what the "I want the Start Button" was all about. Re: (Score:3, Informative) What more exactl Re: (Score:2) Start -> Run -> cmd dropped you right into a DOS shell. To do this in Win 8.1, you need to: Start -> Metro -> ??? Re:Start Button in 8.1 is useless. (Score:5, Informative) Re: (Score:2, Insightful) You press start and type "cmd". Typing on the start screen initiates a search. Alternatively press win+s to open the search panel, and type "cmd". Alternatively right click on the start menu and click run, then type cmd. Thanks. Just what I've always wanted in a modern GUI - more typing. Re: (Score:2) How are any of those options "more typing"? Re: (Score:2) Re: (Score:3) Not exactly obvious though, is it? Where's the graphical hint to tell you "You can type in here"? Re:Start Button in 8.1 is useless. (Score:5, Interesting) I prefer the win7 start menu. Why? Let's say I use calculator a lot. I mean A LOT. But, I don't want to put a quick launch button down, because the group policy enforced by my employer locks that thing down tighter than a nun's cunt, prevents it from being resized, enforces that certain things be in it, etc. The win7 start menu keeps track what what I launch from it frequently, and puts quick links in for those applications, waaaaaaaaaay above the demonized 'all programs' area. I DON'T HAVE TO MANAGE THIS LIST. It is simply populated with what I most frequently invoke. Thus, to start calulator, it is literally: START->Calculator. TWO CLICKS. TWO. Moreover, the software I use TO DO MY JOB, makes very heavy use of the mouse. Letting go of the mouse, so I can type "calc.exe" into the wild blue void is measurably less productive for my use case. STOP INSISTING THAT ALL USERS ARE DATA ENTRY DRONES. Moreover? YES, I *HAVE* used windows 8. Know what? It is counter productive to the workflow paradigm of the software I use, because it requires me to let go of the goddamn mouse, and type shit. Know what else? I use notepad to look at the generated NC code I produce to make sure the toolpaths I am making are generating sane results, ad guess what? Windows 8 tries to make fucking notepad full screen! BULLSHIT, I just need it as a teeny little window to scroll through, jackasses! I fucking hate the "why are you afraid of change!? Are you some kind of luddite?! You're a luddite aren't you?1 yeah, You're a Luddite if you don't like the new formerly-known-as-metro UI paradigm, because it is new, and the old way is old, and if you like old, and not new, then you are a luddite!" Circular reasoning bullshit. No, I dislike the new windows 8 UI because it fucking sucks for what I do for a living, gets in my way, slows me the fuck down, and invokes assholes to character assasinate me (and others in my boat) when we say we DON'T WANT the windows 8 UI paradigm on the desktop! Is it so fucking hard to understand that NOT EVERYONE uses the keyboard the way you do, and that this is NOT a case of "idiots at the wheel"? That perhaps, the mouse is a legitimate input device, and not something to arrogantly scorn, since it has real, legitimate uses in graphical design that fucking keyboard shortcut keys will *NEVER* be able to replace? Of course not. It is just easier to measure everyone else as being whiners, and not having legitimate complaints, because that makes you feel better without having to actually acknowledge wrongdoing, character assasinate them as luddites who are afraid of change, and arrogantly (and ignorantly) assert that they should just use the keyboard instead of the mouse anyway, "because it's faster". Yeah buddy, try selecting NC geometry to drive 5 axis toolpaths on using the tab key. I fucking dare ya to, and to show how much faster it is. Because it fucking isn't. There are operations you can't even DO without a goddamn mouse in this software, for god's sake! "Well, just use different software then!" You arrogantly chortle-- Not an option bitches, its mandated by contract agreements what softwares are allowed. Besides, more "open" offerings just don't have the functionality anyway. Can you do what you do faster with metro by using the keyboard? Quite possibly. That isn't what is being argued. What is being argued is that what *I* do with the computer is greatly hobbled by metro's hamfisted bullshit, and I have legitimate complaints about it that are fundamentaly intractable by anything other than reverting the changes. That is why my employer, and our partners we do work for, DON'T USE WIN8. What would have bee the POLITE thing to do? Turn on metro by default allright, but make it truly optional-- GIVE US A WAY TO TURN IT OFF. But no, the response we had shoved down our throats so hard that our asses bled? "Metro is the future! Its faster and better, and the old way is old, and if you don't like it, tha Re: (Score:3) Re: (Score:3) You press start and type "cmd". Typing on the start screen initiates a search. Alternatively press win+s to open the search panel, and type "cmd". Alternatively right click on the start menu and click run, then type cmd. No, you type "powershell". The old Command Prompt is deprecated. Re: (Score:3) Re:Start Button in 8.1 is useless. (Score:5, Informative) Start -> Run -> cmd dropped you right into a DOS shell. To do this in Win 8.1, you need to: Start -> Metro -> ??? Easier. Windows 8: Move mouse to bottom left corner and right click. Pick either command prompt or command prompt in admin mode Windows 8.1: Right click start logo. Pick either command prompt or command prompt in admin mode From that same menu I have quick access to options that took more than a few clicks to get to before. Also in 8.1, you can use this to shutdown or restart. Re: (Score:2) What's a "Window" key? I don't think my Model M has one of those. Re: (Score:2) This isn't even a funny joke anymore, you can find keyboards without a key with the windows logo on it, but it's still there, because having a Super button is pretty useful. Re: (Score:3) Actually, it's not universally a joke. I'm typing this on a Model M, ca 1991, and yeah, I'll give up Windows before I give up this keyboard. Re:Start Button in 8.1 is useless. (Score:5, Insightful) In my experience, the Windows key's most suitable task seems to be to get accidentally bumped by the side of my hand and minimizing my games at the worst possible moment... Re: (Score:3) Re: (Score:2) No, that's not all the 8.1 start button does, it tries to interfere with the smooth working of Classic Start Menu. You can't disable it and while Classic will overlay it's own button by default it doesn't quite cover it by default. Cue hilarious 'I missed the button by a pixel and ended up in Metro' adventures. To be fair though, I predicted Microsoft would use the returning Start button to block 3rd party Start Menus. I didn't predict they'd do it so badly it would be worked around almost instantly. Re: (Score:2) Re: (Score:2) Re:Start Button in 8.1 is useless. (Score:5, Interesting) Oh and the hodgepodge of functionality. I love how in the start menu the oft used "search box" is right next to the shut down function, which is right next to a tiny tiny arrow which opens up lock computer/sleep functionalty. Why is the shut off button so large, when I do this function at most once a day? And next to often used functions like search and lock? Great UI. For me, the start screen is much more customizable, much more informative, and easier to use all around. If I want to launch an app and i'm on the desktop, I win+s to pull up the search bar and type the app name. If I don't know the app name, I open up the "All Apps" window and I sort and I can see all my installed apps at a glance instead of rooting through a tree of vaguely and uninformatively named folders. Going back is not a breath of fresh air, it's suffocating.. classic shell ftw.. the only thing I've needed metro has been going to boot in unsigned drivers mode... it's pretty easy to argue that start menu is better if you use deskto. You don't have to do that at all. Want the control panel? Rigtht click on the start menu, it's right there. Want to launch an app? Press win+s and type the first few letters. Control panel can be launched this way, or you can make it even faster by launching the control panel item you want straight from the search pane. Try using it before commenting next time. Re:Start Button in 8.1 is useless. (Score:5, Insightful) Personally, I don't care so much about the formal start menu - I use either shortcut keys or just Win-R the program name for just about everything I don't have as an icon on my desktop. I suspect most people pining for the start menu really don't care about it specifically, but rather, the whole set of known OS behaviors that came with it: What do I (we?) want? I want the window manager to behave as a window manager. I want small, configurable iconic shortcuts that open programs for me in a window. I want a base desktop that doesn't look like Times Square at night (complete with its many flashing neon ads). I specifically do not want every program to open itself in a more-or-less-modal fullscreen style on my 30" WQXGA display. I have a monitor that big for a reason, and believe it or not, that reason has nothing to do with spending all day prettifying Word documents intended for a booklet layout. I want the "store" to mean I go to Amazon or Newegg in a non-MSIE browser. I do not, ever, want any attempt whatsoever at "upselling" by Microsoft, or worse, the few money-grubing OEM partners of theirs they haven't managed to alienate yet. In short, I want Windows 7. And if five years from now that means I have to run Linux to get it, I damned well will. Re: (Score:3) It's a simple thing really. People want floating windows, not things that forces a context switch and changes the whole screen. Some people have wide screens and run multiple application in parallel. The paradigm that made Microsoft Windows popular is to use floating windows to organize your multiple applications working concurrently. Re: (Score:2) Re: (Score:3) Re: (Score:2) Re: (Score:3) Re:Start Button in 8.1 is useless. (Score:4, Informative) Have you even used the product you're bashing? Re: (Score:2) No, the "I want the start button" was all about normal users confronted with the desktop, and no idea what to do with it. Have you seen all those youtube videos of putting someone in front of Windows 8, and watching them have no idea what to do? This is for them. The return of the start 'button', to get them to the start screen restores the discover-ability of functionality. No, its not quite the same interface, but the functionality is there. Its an open question whether or not the functionality is better or Re:Start Button in 8.1 is useless. (Score:5, Funny) What? Are you saying that you want the Start Button to have some action when clicked? If it was so important, you should have documented it at the requirements. You asked for a button, MS gave you a button. Content yourself with it. Successor (Score:3) ...to Windows 7? Yes and no (Score:5, Insightful) It's pretty obvious that someone high enough in their business-customer focused product guys heard enough Start button complaints to get that put back. I know a lot of people wanted the menu to return, but that was doubtful given how much Microsoft wants to see the Store and the whole Apps thing succeed. They have made a lot of tweaks to make using Windows 8.1 on keyboard-and-mouse PCs much easier, and I'm happy for that. One thing that I desperately want back is the "themeable" user interface on the desktop. I'll even give up the Start Menu for that. I want to be able to choose between the new "Windows 2.0" desktop, the "dated and cheesy" Aero Glass theme I like in Win7, or even go all the way back to "Windows Classic" like I've been able to do since Win2K. That's just the in-box themes too -- lots of vendors used the theming code in the OS to completely transform the desktop. I was really hoping for Aero Glass to make a return (or even Aero without the Glass acceleration.) Unfortunately, it looks like they're still not listening to people on that front. Re:Yes and no (Score:5, Insightful) I really don't understand why MS insists on locking down the themes. The engine is fully capable of using whatever theme the user wants, but for unknown reasons this is restricted to the one included theme digitally signed by Microsoft. There is no good reason for that. Why should we have to hack a DLL to get a feature that the OS already supports? A lot of the issues with Win8 would go away if theming was permitted. (For instance, the one thing I find most annoying about Win8 is the centered title bar text – this breaks the way I've read window titles since Win95.) Re: (Score:2) Reason: brand Re:Yes and no (Score:5, Informative) The engine is fully capable of using whatever theme the user wants, but for unknown reasons this is restricted to the one included theme digitally signed by Microsoft. There is no good reason for that. There is a very good reason for that. They want to retain a universal look for Windows. Very important for branding. Meh (Score:5, Informative) Start8 (boot-to-desktop, Win7 start menu, remove hotspots) slapped on top of Win8 solves most of my complaints about Win8, and ModernMix makes Metro apps (like Metro Netflix, since it can view SuperHD content) helps with Metro-only apps. Start8 already has a beta out for Win8.1, to account for the fact that there is now a built-in boot-to-desktop, and that there is a system start button that needs to be removed before the fake one can be added. I'll undoubtedly get Win8.1 to get the improvements, and let Stardock fix the major annoyances for me. But pop3 mail or no? (Score:2) "Enhancements"? (Score:3) Re: (Score:2) Since when it's not? It does make the product better, not worse... Or, better, it would if it actualy included a start menu. Penny Arcade's Response... (Score:5, Insightful) Pretty much mirrors my own. Although I would add in an extra side of "fuck you"... [penny-arcade.com] Re: (Score:2) How many times are you going to post the same comment? I first posted it under the AC post because I didn't see that an actual person had posted something similar. Since AC posts often get modded down or ignored I figured I'd copy/paste it to this one. Still nothing better over Windows 7 (Score:4, Interesting) No one is interested in the Modern UI apps and the Start screen is harder to use than the Start menu. It's a jumbled mess of icons which steals your whole screen and you have to move your mouse much more than before. Actually, I have noticed that many resort to just typing the application name they want to use into the search bar as the GUI is so clunky to use. The minimal performance improvements, improved file transfer dialog, improved task manager, ISO mounting and DirectX 11.2, are not big enough features to justify an upgrade. All those features are good enough in Windows 7 already. Those improvements could have been released as a free Platform Update for Windows 7. Re: (Score:2) Actually, I have noticed that many resort to just typing the application name they want to use into the search bar as the GUI is so clunky to use. That's how people were using the old start menu too. That's how its supposed to be used. You pin apps you use the most either directly to the taskbar or in a taskbar toolbar. For stuff you don't use much you use the start screen, and the type-search is how it was intended to be used. The minimal performance improvements, improved file transfer dialog, improved task Re: (Score:2) Actually, the most compelling Windows upgrade was from ME to XP. There's still things that are more logical and better in XP than any version since. Re:Still nothing better over Windows 7 (Score:4, Insightful) That's how people were using the old start menu too. That's how its supposed to be used. That's how some people were using it, but for a lot of people, that's the clunkiest possible way to do it. In what world does it make sense to have to remember the name of an application you don't use regularly? Re: (Score:3) In what world does it make sense to have to remember the name of an application you don't use regularly? Ah, so in the event you don't know the name of the application, you will need to scan for it in a list, where you will attempt to recognize its name and or icon, right? So then you feel it would be better if that list should in be a non-resizable small popup window in the corner of the screen organized in a hierarchical structure usually headed by either the name of the company that produced it or some va Re:Still nothing better over Windows 7 (Score:4, Informative) That's how people were using the old start menu too. That's how its supposed to be used. The start menu, from Windows 95 and until Vista, had no integrated search. You cannot say "that's how its supposed to be used." It became an option in Vista and 7, but not too many people (per my personal observations) even know that the built-in search exists. Some users that I know do not touch the keyboard unless they must, like for typing an email - and even that they do with one finger, "hunt and peck" style. You can't expect them to remember names of applications. Hell, I don't remember most of the names of applications on this very box. I have better things to remember than that. For those applications that I do remember about, "quick" does not return Quicken, but "quicken" does - how would MS explain that? BTW, QuickTime is not returned either - except the "About QuickTime." This is garbage. Typing is only a tool for some power users, and it has limited value as you cannot know what applications are installed on a given PC that you just connected to. You use the hierarchical menu to find out. As long as Microsoft "dead ends" platforms... (Score:4, Interesting) I put time and money and effort into making salable sofware products. What Microsoft has told me repeatedly is that I don't matter to them. At all. What would motivate me, as a developer, to invest 1 more minute in a platform that's almost guaranteed to go the way of VB6, Winforms, Silverlight or XNA? Want to go to the web as your customers are demanding? Recode. Want to upgrade that game? Recode? Want to keep that nifty Silverlight app going. Find another platform and recode. Only C++ developers were extended the fundamental courtesy of running unmanaged old code along with .net. Everyone else is essentially told "tough shit." Worse, half-hearted efforts like the VB6 upgrade or WPF/Winforms hosting aren't developed to actually *work* and so end up wasting even more of your time. VB6 should have upgraded with one click, or run between tags as unmanaged code. Winforms should either have actually been hostable in WPF, or come with a one click upgrade to an ASP simulacrum of Winform code. VBScript and JScript should have migrated to VBScript.net and JScript.net rather than the syntactic abomination that is Powershell. Those would have been the right decisions, had Microsoft given a shit. When Microsoft finally realizes that the word "Recode" IS ALWAYS THE WRONG ANSWER when a developer needs to migrate to another platform, they might actually get some interest in their products. Not before. Common courtesy and consideration of the financial needs of real developers would go a long way. The ISV world is not made of C++ elite. It's made of people who have to get some work done and make a living - who do not, and will never aspire to the at the top of the programming heap. That's your core audience, not the 20-something genius you hire from Kazakhstan. Cater to them and their ilk, and them only and you will fail. Like you're doing now. Re: (Score:2) funny thing about them EOL'ing products is that they do them even if they are using them. so how much life do the silverlight.* and xna.* have left in windows phone? So? (Score:2) Let me know when I can use it on a desktop without ever seeing any part of Metro for any reason, AND has some improvement over 7 that makes it worth buying. Until then, I have no interest in even trying it. start menu, we will miss you (Score:2) Still no classic start menu. But then again how often do you really use the start menu? I run windows 7 on my general desktop and between pinning apps to the taskbar and using fences for some groups of icons on my desktop, I really have no need for a start menu. The downside is some programs come with help files, utilities and other ancillary programs that are better off stuck in a folder of an alphabetically arranged list. But those are a simple windows key -> type name and hit enter when the search find Re: (Score:2) I use the start menu quite frequently. Re: (Score:2) To each his own I suppose. Most of the software I install which gets lost in the start menu is usually some utility I need for a file conversion or evaluating something. I used to let them pile up but now I uninstall them unless they were incredibly difficult to find. I find that on my windows PC its mostly games and a few programs that I run on both windows and Linux. Even faster? Really? (Score:2) I don't know if they could get it much faster, after I installed the update to my bios fully supporting UEFI, I was right around 7seconds on the OS after post on a 1st gen SSD. Where they're going to trim and get a faster boot time even from that I have no freaking clue. Waitwhat? (Score:2) Come again? Unless they completely broke the OS from the cloud down, they already have somewhere around 80% of developers actively working in their environment. Oh! Riiight - By "8.1", Microsoft doesn't mean "Win7-plus-1.1 and we fixed the useless bullshit we did in Windows-FisherPrice-edition", it means they gave their latest defective-by-design codebase a facelift so as to not completely alienate those of us who will use 7 until M Funny. (Score:3) You know about all the bitching and moaning. It is just about a new UI, that really isn't that big of a deal, especially for a group of people use to using a bunch of Operating Systems. I haven't read many comments about Windows 8 with problems with more important things such as Driver Compatibility, Unexpect crashes, other technical problems, or Slowness. It just sounds like a bunch of Whiny people who wants to get an Apple or Defend Linux, or are so old or autistic that they cannot handle any change. Uninstalled it in 2 days (Score:2). Did they get 8.1 right? Uhm. NO! (Score:2) Microsoft may have "reacted" to feedback. But they sure as hell didn't LISTEN to it. It's not about the UI, FFS! (Score:5, Insightful) It's about Microsoft moving from a 'general purpose computing' model to an 'app store computing' model. Where everything has to be code-signed, approved/censored, and taxed at 30%+. They are doing this by gradually phasing out the desktop and applying pressure to users to use Metro, by making it harder to avoid - whilst the desktop gradually has functionality stripped out (first the Start menu, now the control panel) This is why we should absolutely reject Win8. Not because the new start screen is annoying. No, Metro is still a blatant attempt... (Score:3) ...to use their desktop monopoly to gain a foothold in the tablet market. And if there were an antitrust regulator left anywhere on earth that still had the intestinal fortitude to go after Microsoft, they would be getting fined for it. "Getting developers on board"... yeah, on board the doomed ship SS Surface. Re: (Score:2) Penny Arcade. [penny-arcade.com] 'nuff said. But, as "Gabe" says in the actual news post for that day, he actually LIKES the TIle UI. I like it too. But, I can see it not being for everyone, and it obviously has some short-comings. Re:Penny Arcade (Score:5, Insightful) The Metro UI is just fine... maybe even good... for a tablet. For a mouse driven desktop PC, it is still a pile of pastel colored shit. All they need to do is not force me to use it on PC and I'm good. I'm not offended that they did it, I just want them to get it out of my way in a place where it is not very efficient. It's not like I am demanding that they re-write the UI, they already had the Windows 7 UI for the desktop. Just slap that on top of your improvements and add the Metro option if you want or need it. Have Metro run on tablets by default and the normal Desktop run on PC's by default. I understand that sometimes you have to push things, but there is really no benefit to Metro for PC users. There might be one for Microsoft, in that they want everyone to think of Metro as the One and Only Operating System and parlay their desktop market share into tablet share, but that doesn't actually help me in any way. At this point, they're just being stubborn assholes. The comic got that much right. Re:Microsoft's big mistake (Score:5, Insightful) .. was naming it Windows 8, instead of Windows Tablet Edition, which could also be added to Windows 7 as a Tablet Mode. Uh, no. Windows 8 was a desperate attempt to get some kind of prescence on tablets and phones. To do that, they need apps. To get apps, they need to convince developers that they should develop apps for Windows 8. To do that, they had to push the tablet interface on the desktop. Of course the idea was retarded from the start, which is why it's come around to bite them in the ass. They threw their desktop users under the bus and gained only a minimal number of tablet and phone users. Wait, what? (Score:2) Three times a year since the middle 90's there are news of people revisiting the dogmas of the desktop, and building something completely different. Every time they screw up the same thing: people want desktops, not something completely different. Microsoft: 'own goal' once again. (Score:5, Interesting) Microsoft owns the desktop, and has tons of money. They didn't ever say, "How do we make the desktop really good? How do we use our massive resources to make our customer's lives better?" That can include serious and radical rethinking---if it makes desktop experience better. Microsoft had a 'smart phone' -- a real computer on a phone with a reasonably capable OS -- long before Apple and Android. Microsoft did see the future and drove into a ditch. This Windows Phone OS UI was awful. Terrible, revolting. The UI was really bad---because they tried to do a Windows XP on a tiny thing with a stylus. (I had a treo 700 something which I got for free). There was even a little mini "control panel" and similar confusions. Because at that time the ideology was Windows Uber Alles and serving the Windows empire. Jobs didn't insist on stuffing MacOS UI on the iPhone, because it wouldn't be GOOD for those uses. Even though it was quite different there were no deep strain of serious complaint about the UI. So phones and tablets get popular. And Microsoft makes the same mistake AGAIN as with Windows Phone (pre 7) -- stuffing a totally inappropriate interface (and one which isn't even that pleasant) somewhere else. This time, unlike Windows Phone, greatly annoying their enormous number of paying customers. There are all sorts of ideas about how to make better desktops at a deep level (at least browse academia for 20 years) which are substantially more than another skin. Back in 1995, Microsoft had the good sense to copy something decent for the Win 95 UI, NeXTSTEP, though of course it was degraded, it was still clear and effective enough. Nobody missed Win 3.1's UI. Desktop customers are not stupid dinosaurs, maybe they actually notice better from worse. Even today, if they re-implemented NeXTSTEP 1993 for Win 9 desktop, they'd still be ahead. Really. Re: (Score:3) Re: (Score:3) I don't think people want "desktops" as much as they want an efficient control UI for the form factor they are using. Metro is okay for tablets. It is NOT okay for PCs with mouse driven inputs. Oh sure, you can use it with a mouse, but the layout is for fat fingers which completely wastes the accuracy you can get with a mouse input device. Consider that even large icons in the Desktop are still smaller than some of the gigantic boxes you have in Metro. That's all just wasted space unless you need it. Ag Re: (Score:2) i guess i won't be installing a ms solution to test. most of my test deployments last forever as I can only work and test on them as time permits. I still have a share-point install i did in Jan that i haven't done anything on and probably won't for another month or so. is anyone awake at the helm at MS.
https://tech.slashdot.org/story/13/07/01/1754242/microsoft-reacts-to-feedback-but-did-they-get-windows-81-right?sdsrc=popbyskidbtmprev
CC-MAIN-2016-44
refinedweb
7,790
73.27
The Cable Guy - March 2004 Local Server-Less DNS Name Resolution for IPv6 Local Server-Less Domain Name System (LSLDNS), also known as multicast DNS, is a new capability in the IPv6 protocol that is provided with Microsoft Windows CE version 4.1 and later. LSLDNS is described in the Internet draft titled "Local Server-less DNS (LSLDNS) query resolution" (draft-ietf-dnsext-mdns-07.txt). Note In recent revisions of the multicast DNS Internet draft, the name of the protocol has been changed to Linklocal Multicast Name Resolution (LLMNR) and many implementation details have been changed. This article does not describe LLMNR. LSLDNS provides a method to resolve names on an ad hoc, single-subnet network that does not contain a functioning DNS server. IPv4 in Windows TCP/IP solves this problem by using NetBIOS over TCP/IP (NetBT), which is enabled by default. With NetBT, a querying node broadcasts a NetBIOS Name Query Request message to the local subnet broadcast address. The node that owns the queried name sends back a unicast NetBIOS Name Query Response to the requestor and the name is resolved. This method does not work for IPv6 for the following reasons: - NetBIOS is not defined to operate over IPv6. - There are no broadcast addresses in IPv6. LSLDNS is a simple request-reply mechanism used on ad hoc, single-subnet networks to allow IPv6 nodes to resolve each other's names in the absence of DNS name resolution functionality. Multi-subnet networks are assumed to have a functioning router and DNS server. Because broadcasts are not defined for IPv6, multicasts are used instead. LSLDNS is similar to DNS in the following ways: - Uses fully qualified domain names (FQDNs) - Uses the same messages and message structure as DNS, as defined in RFC 1035 LSLDNS is different than DNS in the following ways: - LSLDNS messages are sent to TCP and UDP port 5353, rather than TCP and UDP port 53 - LSLDNS message queries are sent to a multicast address, rather than the unicast address of a DNS server - The LSLDNS name cache is separate from the DNS name cache LSLDNS is used when DNS servers: - Are not configured - Do not return a response to a query - Respond with Return Code (RCODE) set to 0, but there are no answer records - Respond with RCODE set to 3 (domain name does not exist) The multicast address used for DNS Name Query Request messages is known as the solicited name multicast address, and is constructed from the following: - The prefix FF02::2:0:0/96. - The high-order 32-bits of the Message Digest 5 (MD5) hash calculation on the host name portion of an FQDN or unqualified name. For example, if the FQDN is officecomputer.example.com, the host name is officecomputer. The host that is assigned the host name listens on the solicited name multicast address and the host attempting name resolution of an FQDN beginning with the host name uses the solicited name multicast address as the destination address of a DNS Name Query Request message. How LSLDNS Works During the startup process, a node that supports LSLDNS calculates its own solicited name multicast address and instructs IPv6 to listen for packets sent to that address. When an application uses the getaddrinfo() Windows Sockets function call to resolve an FQDN or non-qualified name to an address, the LSLDNS-capable node extracts the host name, calculates the MD5 hash of the host name, and appends the high-order 32 bits to the FF02::2:0:0/96 prefix to form the solicited name multicast address. The querying node then constructs and sends a DNS Name Query Request message with the following contents: - IPv6 header Source Address field is set to the link-local address of the interface of the querying node Destination Address field is set to the solicited name multicast address Hop Limit field is set to 255 - UDP header Source Port field is set to 5353 Destination Port field is set to 5353 - DNS header Recursion Desired (RD) flag set to 0 Question section contains the full name as originally specified by the application and a request for the record type specified in the getaddrinfo() function call Note that the Hop Limit in the IPv6 header is set to 255. The receiver verifies that the Hop Limit field is set to 255 before performing further processing on the message. This check is similar to the practice for Neighbor Discovery messages, in which the receiver verifies that the message came from a node that is attached to the local link. If the node were off-link, the Hop Limit field would be less than 255. Note also that the RD flag in the DNS header is set to 0, indicating that the requestor does not wish the receiver to perform recursive queries on its behalf. The multicast DNS Name Query Request message is received by the nodes that are listening on the specified solicited name multicast address (there is typically only one). They first verify that the Hop Limit field is set to 255. If it is not, the message is silently discarded. The receiving host then checks to see if it is authoritative for the name in the Question section of the message. Contrary to normal DNS behavior, LSLDNS nodes are authoritative for specific names that have been assigned to them, rather than for a portion of the namespace beginning at the assigned name. Using conventional DNS server terminology, LSLDNS nodes are only authoritative for the zone roots corresponding to their assigned names (the term zone is used here loosely as LSLDNS nodes are not DNS servers that store zones). For example, an LSLDNS node that has been assigned the name office.example.com is not also authoritative for all names that begin with office.example.com. If a node that receives the DNS Name Query Request message is authoritative for the name in the Question section of the message, it constructs and sends a DNS Name Query Response message with the following contents: - IPv6 header Source Address field is set to the link-local address of the sending interface of the responder Destination Address field is set to the Source Address field of the received DNS Name Query Request message (the link-local address of the requestor) Hop Limit field is set to 255 - UDP header Source Port field is set to 5353 Destination Port field is set to 5353 - DNS header Authoritative Answer (AA) flag set to 1 Recursion Available (RA) flag set to 0 RCODE field set to 0 Question section includes the Question section fields and contents from the DNS Name Query Request message Answer sections include the appropriate records for the names and their associated types as requested in the DNS Name Query Request message If the entire DNS Name Query Response message is larger than 512 bytes, the responder will set the Truncation (TC) flag to 1. The requestor can then either repeat the query using a unicast, TCP-based DNS Name Query Request message or it can retry the UDP-based query using EDNS0 (as defined in RFC 2671). If the requestor does not receive a reply, it can retransmit the DNS Name Query Request message up to three more times. Only after not receiving any replies from its retransmitted queries can LSLDNS conclude that the name being queried for does not exist on the network and indicate the name resolution failure to the application that called the getaddrinfo() function. It is possible that more than one node on an ad hoc or single subnet network is using the same host name. For example, one node is assigned the FQDN officecomputer.example.com and another node is assigned the FQDN officecomputer.upstairs.example.com. For both of these computers, the solicited name multicast address is the same. A query for the name officecomputer.example.com sent to the solicited name multicast address corresponding to the host name officecomputer is processed by both of these computers. However, only the computer assigned the officecomputer.example.com name sends a response. It is also possible that more that one node is assigned the same FQDN. For both of these computers, the solicited name multicast address is the same. A query sent to the solicited name multicast address corresponding to the host name in the FQDN is processed by both of these computers and both computers send a response. In this case, the requestor treats the multiple responses as if it received multiple answer records in a single reply. For More Information For more information about IPv6, consult the following resources: - Internet Protocol Version 6 Technology Center - IETF DNS Extensions Working Group - Internet Protocol Version 6 (IPv6) Support in Windows CE 4.1 and later For a list of all The Cable Guy articles, click here.
https://technet.microsoft.com/en-us/library/bb878001.aspx
CC-MAIN-2017-09
refinedweb
1,474
52.12
PVS-Studio Probes into Linux' Innards (3.18.1) - What was checked - How the check was done - A few words about security for a start - Suspicious fragments - Conclusion For the sake of advertisement, we decided to analyze the Linux kernel with our static code analyzer. The difficulty of this task makes it especially interesting. Linux' source codes have been checked, and are still checked, by a number of different tools. So finding anything new was hardly probable. However, if we succeeded, it would be a nice advertisement for the PVS-Studio analyzer's capabilities. What was checked The Linux kernel was taken from the The Linux Kernel Archives site. We checked the Latest Stable Kernel 3.18.1. At the time of writing this article, the kernel version 3.19-rc1 has been already released. Unfortunately, analyzing a project and writing an article takes quite a bit of work and time, so we have to settle for a check of a slightly obsolete version. Here's my reply to those who may argue that we ought to have checked the latest version available. - We regularly check a number of projects, and we have lots of other tasks to fulfill besides free analysis of projects. This is why we absolutely cannot start all over, just because a new version was released. In doing so, we'd risk never publishing anything at all :). - 99% of all errors we found are still there. So you can still rely on this article to make the Linux kernel's code a bit better. - The purpose of this article is to advertise PVS-Studio. If we can find errors in version X of some project, then we can certainly find something in version Y too. Our checks are quite superficial (as we are not familiar with the project code) and their goal is to help us gather material for promo articles like this. What can really benefit a project is purchasing a PVS-Studio license, and regular use of the tool by the project authors. How the check was done We used the PVS-Studio static code analyzer version 5.21 to check the kernel. For the check of the Linux Kernel, we took the Ubuntu-14.04 distribution, on which a lot of detailed guides are available, explaining how to configure and build the kernel. The analyzer checks preprocessed files that need to be obtained for successfully compilable files, so building a project is one of the most important analysis stages. We then wrote a small utility in C++ that could save a command line, the current folder, and environment variables for each of the running compiler processes. Those of you familiar with PVS-Studio products, will immediately recall the PVS-Studio Standalone utility, that allows one to check any project under Windows. We use WinAPI to address processes in this utility, so we only had to rewrite this monitoring mechanism for Linux, while the rest of the code, dealing with preprocessing launch and analysis, was completely ported. So a Linux kernel check was only a matter of time. A few words about security for a start It happened somehow that people grew to treat the PVS-Studio analyzer solely as a tool to detect errors, and no one cares that it can also detect certain type of vulnerabilities. It's our own fault of course, and we have to improve the situation. You see, messages generated by PVS-Studio can be treated in different ways. For instance, an issue can be both a typo and a vulnerability at the same time. It all depends on how you look at it. I want you to take a look at a few warnings generated by PVS-Studio when analyzing Linux. It's not that I mean to say the analyzer found true vulnerabilities in Linux, but the warnings cited below could well do that. Dangerous use of the memcmp() function static unsigned char eprom_try_esi( struct atm_dev *dev, unsigned short cmd, int offset, int swap) { unsigned char buf[ZEPROM_SIZE]; struct zatm_dev *zatm_dev; int i; zatm_dev = ZATM_DEV(dev); for (i = 0; i < ZEPROM_SIZE; i += 2) { eprom_set(zatm_dev,ZEPROM_CS,cmd); /* select EPROM */ eprom_put_bits(zatm_dev,ZEPROM_CMD_READ,ZEPROM_CMD_LEN,cmd); eprom_put_bits(zatm_dev,i >> 1,ZEPROM_ADDR_LEN,cmd); eprom_get_byte(zatm_dev,buf+i+swap,cmd); eprom_get_byte(zatm_dev,buf+i+1-swap,cmd); eprom_set(zatm_dev,0,cmd); /* deselect EPROM */ } memcpy(dev->esi,buf+offset,ESI_LEN); return memcmp(dev->esi,"\0\0\0\0\0",ESI_LEN); } PVS-Studio's diagnostic message: V642 Saving the 'memcmp' function result inside the 'unsigned char' type variable is inappropriate. The significant bits could be lost breaking the program's logic. zatm.c 1168 Notice the 'return' operator at the very end of the function body. The 'memcmp' function returns the following values of the 'int' type: - < 0 - buf1 less than buf2; - 0 - buf1 identical to buf2; - > 0 - buf1 greater than buf2; Notice the following: - "> 0" means any number, not 1; - "< 0" is not necessarily -1. There may be different return values: -100, 2, 3, 100, 256, 1024, 5555, and so on. It means that this result cannot be cast to the 'unsigned char' type (this is the type returned by the function). Implicit type conversion may result in truncating significant bits, which will break program execution logic. What is dangerous about such errors, is that the return value may depend on the architecture and implementation of a particular function on the given architecture. For example, a program may work well in the 32-bit version, but fail in the 64-bit. So what does this mean? Just an incorrect check of something related to EPROM. It's an error of course, but what does it have to do with a vulnerability? It means that the V642 diagnostic can reveal a vulnerability too! You don't believe me? OK, here is an identical piece of code from MySQL/MariaDB. typedef char my_bool; ... my_bool check(...) { return memcmp(...); } It was not PVS-Studio that had found this issue; but it well could have. This error caused a severe vulnerability in MySQL/MariaDB up to versions 5.1.61, 5.2.11, 5.3.5, 5.5.22. The point about this, is that when a new MySQL /MariaDB user logs in, the token (SHA of the password and hash) is calculated and compared to the expected value by the 'memcmp' function. On some platforms, the return value may fall out of the [-128..127] range, so in 1 case out of 256, the procedure of comparing the hash to the expected value always returns 'true' regardless of the hash. As a result, an intruder can use a simple bash-command to gain root access to the vulnerable MySQL server, even if he doesn't know the password. This vulnerability was caused by the code fragment cited above, found in the 'sql/password.c' file. For a detailed description of this vulnerability, follow this link: Security vulnerability in MySQL/MariaDB. Now let's get back to Linux. Here's another dangerous code fragment: void sci_controller_power_control_queue_insert(....) { .... for (i = 0; i < SCI_MAX_PHYS; i++) { u8 other; current_phy = &ihost->phys[i]; other = memcmp(current_phy->frame_rcvd.iaf.sas_addr, iphy->frame_rcvd.iaf.sas_addr, sizeof(current_phy->frame_rcvd.iaf.sas_addr)); if (current_phy->sm.current_state_id == SCI_PHY_READY && current_phy->protocol == SAS_PROTOCOL_SSP && other == 0) { sci_phy_consume_power_handler(iphy); break; } } .... } PVS-Studio's diagnostic message: V642 Saving the 'memcmp' function result inside the 'unsigned char' type variable is inappropriate. The significant bits could be lost, breaking the program's logic. host.c 1846 The return result of the memcmp() function is saved into the other variable of the unsigned char type. I don't think we're dealing with any vulnerability here, but the SCSI controller's work is in danger. Here are a couple of other fragments of this kind: - V642 Saving the 'memcmp' function result inside the 'unsigned char' type variable is inappropriate. The significant bits could be lost breaking the program's logic. zatm.c 1168 - V642 Saving the 'memcmp' function result inside the 'unsigned char' type variable is inappropriate. The significant bits could be lost breaking the program's logic. host.c 1789 Dangerous use of the memset() function We continue searching for dangerous issues. Now let's check functions that clear private data. These are usually various encryption functions. Unfortunately, memory clearing is not always done correctly, and you risk getting quite an unpleasant result. To learn more about these unpleasant results, see the article "Overwriting memory - why?". Let's take a look at a sample of incorrect code: static int crypt_iv_tcw_whitening(....) { .... u8 buf[TCW_WHITENING_SIZE]; .... out: memset(buf, 0, sizeof(buf)); return r; } PVS-Studio's diagnostic message: V597 The compiler could delete the 'memset' function call, which is used to flush 'buf' buffer. The RtlSecureZeroMemory() function should be used to erase the private data. dm-crypt.c 708 All looks fine at first glance. The crypt_iv_tcw_whitening() function allocates a temporary buffer on the stack, encrypts something, and then clears the buffer with private data by calling the memset() function. However, the call of the memset() function will actually be deleted by the compiler in the course of optimization. From the viewpoint of the C/C++ language, the buffer is not used in any way after it has been cleared. Which means it's not necessary to clear it. At the same time, this issue is very easy to miss. It can hardly be covered by unit testing; the debugger won't let you see it either (the call of the memset function will be there in the debug-version). I want to draw your attention to this idea: this is not a "theoretically possible behavior" of the compiler, but rather, very much a real one. Compilers do tend to remove memset() function calls. To learn more about that, see the description of the V597 diagnostic. In this particular example, PVS-Studio gives somewhat inappropriate recommendations about using the RtlSecureZeroMemory() function - but it's because it is oriented towards Windows. There's no such function in Linux of course, but the main point is to warn the user, while picking the necessary analogous function is not difficult at all. Another similar example: static int sha384_ssse3_final(struct shash_desc *desc, u8 *hash) { u8 D[SHA512_DIGEST_SIZE]; sha512_ssse3_final(desc, D); memcpy(hash, D, SHA384_DIGEST_SIZE); memset(D, 0, SHA512_DIGEST_SIZE); return 0; } PVS-Studio's diagnostic message: V597 The compiler could delete the 'memset' function call, which is used to flush 'D' buffer. The RtlSecureZeroMemory() function should be used to erase the private data. sha512_ssse3_glue.c 222 Below is an example of code, where 4 buffers at once may fail to be cleared: keydvt_out, keydvt_in, ccm_n, mic. The code is taken from the security.c file (lines 525 - 528). int wusb_dev_4way_handshake(....) { .... struct aes_ccm_nonce ccm_n; u8 mic[8]; struct wusb_keydvt_in keydvt_in; struct wusb_keydvt_out keydvt_out; .... error_dev_update_address: error_wusbhc_set_gtk: error_wusbhc_set_ptk: error_hs3: error_hs2: error_hs1: memset(hs, 0, 3*sizeof(hs[0])); memset(&keydvt_out, 0, sizeof(keydvt_out)); memset(&keydvt_in, 0, sizeof(keydvt_in)); memset(&ccm_n, 0, sizeof(ccm_n)); memset(mic, 0, sizeof(mic)); if (result < 0) wusb_dev_set_encryption(usb_dev, 0); error_dev_set_encryption: kfree(hs); error_kzalloc: return result; .... } And finally the last example of a password left "hanging about" in memory: int E_md4hash(const unsigned char *passwd, unsigned char *p16, const struct nls_table *codepage) { int rc; int len; __le16 wpwd[129]; /* Password cannot be longer than 128 characters */ if (passwd) /* Password must be converted to NT unicode */ len = cifs_strtoUTF16(wpwd, passwd, 128, codepage); else { len = 0; *wpwd = 0; /* Ensure string is null terminated */ } rc = mdfour(p16, (unsigned char *) wpwd, len * sizeof(__le16)); memset(wpwd, 0, 129 * sizeof(__le16)); return rc; } PVS-Studio's diagnostic message: V597 The compiler could delete the 'memset' function call, which is used to flush 'wpwd' buffer. The RtlSecureZeroMemory() function should be used to erase the private data. smbencrypt.c 224 Let's stop here. See the following files for 3 more bad memset() calls: - sha256_ssse3_glue.c 214 - dev-sysfs.c 104 - qp.c 143 Dangerous checks The PVS-Studio analyzer includes the V595 diagnostic rule to detect issues when a pointer is first dereferenced, and then checked for NULL. Sometimes there's nothing tricky about this diagnostic. Let's examine the following simple case: static int tc_ctl_action(struct sk_buff *skb, struct nlmsghdr *n) { struct net *net = sock_net(skb->sk); struct nlattr *tca[TCA_ACT_MAX + 1]; u32 portid = skb ? NETLINK_CB(skb).portid : 0; .... } PVS-Studio's diagnostic message: V595 The 'skb' pointer was utilized before it was verified against nullptr. Check lines: 949, 951. act_api.c 949 It's simple here. If the 'skb' pointer is null, we're in trouble. The pointer is dereferenced in the first line. It should be noted, that it's not because of an unchecked pointer being dereferenced that the analyzer is angry with this code. There would be too many false positives that way. After all, it is impossible for a function argument to equal 0 sometimes, isn't it? And the check might have well been done somewhere before. So, the logic of this diagnostic is different. PVS-Studio treats code as dangerous if a pointer is first dereferenced, and then checked. If there is a check for a pointer, then the programmer assumes it may equal 0. Therefore, a warning should be generated. We're done with this simple example. But it was not that, which we were actually interested in. Let's now pass on to a more complicated case related to compiler-driven optimizations. static int podhd_try_init(struct usb_interface *interface, struct usb_line6_podhd *podhd) { int err; struct usb_line6 *line6 = &podhd->line6; if ((interface == NULL) || (podhd == NULL)) return -ENODEV; .... } PVS-Studio's diagnostic message: V595 The 'podhd' pointer was utilized before it was verified against nullptr. Check lines: 96, 98. podhd.c 96 This is an example of code people would start arguing about, claiming everything's alright. Their line of thought is the following. Let the podhd pointer be equal to NULL. The &podhd->line6 expression doesn't look neat. But there's no error here. There's no memory addressing; it's just the address of one of the class members being calculated here. True, the value of the 'line6' pointer is incorrect - it points to "nowhere". But this pointer is not used, is it? An incorrect address was calculated, so what? There's a check a bit further in the code, so if 'podhd' is null, the function will terminate. The 'line6' pointer is not used anywhere, that's why no error will occur in reality. Ladies and gentlemen, you are mistaken! You still can't do it that way. Don't be lazy about fixing code like this. Here's the optimizing compiler's line of thought; the pointer is dereferenced here: podhd->line6. Aha, the programmer knows what he's doing. Then the pointer is surely not null here. Nice, I'll remember that. And then the compiler stumbles across the following check: if ((interface == NULL) || (podhd == NULL)) return -ENODEV; What does it now do? It optimizes it. It believes that the 'podhd' pointer doesn't equal zero. That's why it will reduce the check to the following code: if ((interface == NULL)) return -ENODEV; Just like with memset(), working with the debug-version won't let you know that this check will be absent from the code, which makes this issue especially difficult to find. As a result, if you pass a null pointer to the function, it will continue working instead of returning the (-ENODEV) status. The consequences of it are hard to predict. The point here, is that the compiler can delete an important pointer check from a poorly written code. That is, there are functions which only pretend to check pointers. But in fact they will handle null pointers. I don't know if it can be exploited in any way, but I assume issues like this can be treated as potential vulnerabilities. Another similar example: int wpa_set_keys(struct vnt_private *pDevice, void *ctx, bool fcpfkernel) __must_hold(&pDevice->lock) { .... if (is_broadcast_ether_addr(¶m->addr[0]) || (param->addr == NULL)) { .... } PVS-Studio's diagnostic message: V713 The pointer param->addr was utilized in the logical expression before it was verified against nullptr in the same logical expression. wpactl.c 333 While carrying out optimization, the compiler can reduce the check to the following code: if (is_broadcast_ether_addr(¶m->addr[0])) The Linux kernel is large, so I got over 200 V595 warnings from the analyzer. Shame on me, I felt too lazy to look through all of them, and only picked one example for the article. All the other suspicious fragments are left for the developers to investigate. Here's the complete list: Linux-V595.txt. True, not all of these warnings reveal genuine errors; in many cases, a pointer is absolutely sure not to be null. However, this list still ought to be checked. I bet there are a couple dozen genuine errors there. Suspicious fragments Perhaps not all the code fragments described in this article really contain errors. But they are quite strange and suspicious, and worthy of investigation by the developers. Incorrect logic conditions void b43legacy_phy_set_antenna_diversity(....) { .... if (phy->rev >= 2) { b43legacy_phy_write( dev, 0x0461, b43legacy_phy_read(dev, 0x0461) | 0x0010); .... } else if (phy->rev >= 6) b43legacy_phy_write(dev, 0x049B, 0x00DC); .... } PVS-Studio's diagnostic message: V695 Range intersections are possible within conditional expressions. Example: if (A < 5) { ... } else if (A < 2) { ... }. Check lines: 2147, 2162. phy.c 2162 The second condition will never be true. Let's simplify the code to make it clearer: if ( A >= 2) X(); else if ( A >= 6) Y(); As you can see, there's no such value in the 'A' variable that could trigger the call of the Y() function. Now let's examine other similar cases. They don't need to be commented on. static int __init scsi_debug_init(void) { .... if (scsi_debug_dev_size_mb >= 16) sdebug_heads = 32; else if (scsi_debug_dev_size_mb >= 256) sdebug_heads = 64; .... } PVS-Studio's diagnostic message: V695 Range intersections are possible within conditional expressions. Example: if (A < 5) { ... } else if (A < 2) { ... }. Check lines: 3858, 3860. scsi_debug.c 3860 static ssize_t ad5933_store(....) { .... /* 2x, 4x handling, see datasheet */ if (val > 511) val = (val >> 1) | (1 << 9); else if (val > 1022) val = (val >> 2) | (3 << 9); .... } PVS-Studio's diagnostic message: V695 Range intersections are possible within conditional expressions. Example: if (A < 5) { ... } else if (A < 2) { ... }. Check lines: 439, 441. ad5933.c 441 There are a couple of other issues of this kind, which I won't cite here in order to keep the article short: - V695 Range intersections are possible within conditional expressions. Example: if (A < 5) { ... } else if (A < 2) { ... }. Check lines: 1417, 1422. bnx2i_hwi.c 1422 - V695 Range intersections are possible within conditional expressions. Example: if (A < 5) { ... } else if (A < 2) { ... }. Check lines: 4815, 4831. stv090x.c 4831 Now let's examine another type of suspicious condition. static int dgap_parsefile(char **in) { .... int module_type = 0; .... module_type = dgap_gettok(in); if (module_type == 0 || module_type != PORTS || module_type != MODEM) { pr_err("failed to set a type of module"); return -1; } .... } PVS-Studio's diagnostic message: V590 Consider inspecting the 'module_type == 0 || module_type != 68' expression. The expression is excessive or contains a misprint. dgap.c 6733 I'm not familiar with the code, and I have no ideas on what this check should look like, so I won't make any comments on it. Here's another of the same kind: - V590 Consider inspecting the 'conc_type == 0 || conc_type != 65' expression. The expression is excessive or contains a misprint. dgap.c 6692 "Red-eye" While studying the analyzer's messages, I came across a function named name_msi_vectors(). Although it is short, you absolutely don't feel like reading it. This is probably why it contains a very suspicious line. static void name_msi_vectors(struct ipr_ioa_cfg *ioa_cfg) { int vec_idx, n = sizeof(ioa_cfg->vectors_info[0].desc) - 1; for (vec_idx = 0; vec_idx < ioa_cfg->nvectors; vec_idx++) { snprintf(ioa_cfg->vectors_info[vec_idx].desc, n, "host%d-%d", ioa_cfg->host->host_no, vec_idx); ioa_cfg->vectors_info[vec_idx]. desc[strlen(ioa_cfg->vectors_info[vec_idx].desc)] = 0; } } PVS-Studio's diagnostic message: V692 An inappropriate attempt to append a null character to a string. To determine the length of a string by 'strlen' function correctly, a string ending with a null terminator should be used in the first place. ipr.c 9409 It is the last line which I find strange: ioa_cfg->vectors_info[vec_idx]. desc[strlen(ioa_cfg->vectors_info[vec_idx].desc)] = 0; Now I will omit it and you'll notice at once that something's not right here: S[strlen(S)] = 0; This statement is absolutely pointless. Zero will be written where it already is. I suspect the programmer wanted something else to happen. Endless wait static int ql_wait_for_drvr_lock(struct ql3_adapter *qdev) { int i = 0; while (i < 10) { if (i) ssleep(1); if (ql_sem_lock(qdev, QL_DRVR_SEM_MASK, (QL_RESOURCE_BITS_BASE_CODE | (qdev->mac_index) * 2) << 1)) { netdev_printk(KERN_DEBUG, qdev->ndev, "driver lock acquired\n"); return 1; } } netdev_err(qdev->ndev, "Timed out waiting for driver lock...\n"); return 0; } PVS-Studio's diagnostic message: V654 The condition 'i < 10' of loop is always true. qla3xxx.c 149 The function is trying to lock the driver. If it fails, it waits for 1 second and tries again. There are total 10 attempts to make. This number, however, will actually become infinite. The reason is that the 'i' variable is not incremented anywhere. Incorrect error message static int find_boot_record(struct NFTLrecord *nftl) { .... if ((ret = nftl_read_oob(mtd, block * nftl->EraseSize + SECTORSIZE + 8, 8, &retlen, (char *)&h1) < 0) ) { printk(KERN_WARNING "ANAND header found at 0x%x in mtd%d, " "but OOB data read failed (err %d)\n", block * nftl->EraseSize, nftl->mbd.mtd->index, ret); continue; .... } PVS-Studio's diagnostic message: V593 Consider reviewing the expression of the 'A = B < C' kind. The expression is calculated as following: 'A = (B < C)'. nftlmount.c 92 Should an error occur, the function must print the information about it; including the error code. But it is actually (err 0) or (err 1) that will be printed instead of the real code error. The reason is that the programmer made a mess of the operation precedence. He wanted to put the return result of the nftl_read_oob() function into the 'ret' variable at first; then he wanted to compare this variable to 0, and if (ret < 0) then get the error message printed. In reality, it all works quite the other way. At first, the result of the nftl_read_oob() function is compared to 0. The comparison result is value 0 or 1. This value will be written into the 'ret' variable. Thus, if the nftl_read_oob() function has returned a negative number, then ret == 1. The message will be printed alright, but it will be incorrect. As you can see, additional parentheses are used in the condition. It's not known whether they were used to suppress the compiler warning about assignment inside 'if', or to explicitly specify the operation sequence. If the latter was meant, then we're dealing with a typo - a closing parenthesis is put in the wrong place. The correct way to write this code is as follows: if ((ret = nftl_read_oob(mtd, block * nftl->EraseSize + SECTORSIZE + 8, 8, &retlen, (char *)&h1)) < 0 ) { Potential typo int wl12xx_acx_config_hangover(struct wl1271 *wl) { .... acx->recover_time = cpu_to_le32(conf->recover_time); acx->hangover_period = conf->hangover_period; acx->dynamic_mode = conf->dynamic_mode; acx->early_termination_mode = conf->early_termination_mode; acx->max_period = conf->max_period; acx->min_period = conf->min_period; acx->increase_delta = conf->increase_delta; acx->decrease_delta = conf->decrease_delta; acx->quiet_time = conf->quiet_time; acx->increase_time = conf->increase_time; acx->window_size = acx->window_size; <<<--- .... } PVS-Studio's diagnostic message: V570 The 'acx->window_size' variable is assigned to itself. acx.c 1728 All the fields of one structure are copied into fields of another structure, save for one: acx->window_size = acx->window_size; Is it an error? Correct code? I don't know. Suspicious octal number static const struct XGI330_LCDDataDesStruct2 XGI_LVDSNoScalingDesData[] = { {0, 648, 448, 405, 96, 2}, /* 00 (320x200,320x400, 640x200,640x400) */ {0, 648, 448, 355, 96, 2}, /* 01 (320x350,640x350) */ {0, 648, 448, 405, 96, 2}, /* 02 (360x400,720x400) */ {0, 648, 448, 355, 96, 2}, /* 03 (720x350) */ {0, 648, 1, 483, 96, 2}, /* 04 (640x480x60Hz) */ {0, 840, 627, 600, 128, 4}, /* 05 (800x600x60Hz) */ {0, 1048, 805, 770, 136, 6}, /* 06 (1024x768x60Hz) */ {0, 1328, 0, 1025, 112, 3}, /* 07 (1280x1024x60Hz) */ {0, 1438, 0, 1051, 112, 3}, /* 08 (1400x1050x60Hz)*/ {0, 1664, 0, 1201, 192, 3}, /* 09 (1600x1200x60Hz) */ {0, 1328, 0, 0771, 112, 6} /* 0A (1280x768x60Hz) */ ^^^^ ^^^^ }; PVS-Studio's diagnostic message: V536 Be advised that the utilized constant value is represented by an octal form. Oct: 0771, Dec: 505. vb_table.h 1379 All the numbers in this structure are defined in decimal format. And suddenly there is one octal number: 0771. The analyzer didn't like it. Nor did I. I suspect the programmer wrote this zero just for the column to look neatly even. But the value is obviously incorrect then. Suspicious line static void sig_ind(PLCI *plci) { .... byte SS_Ind[] = "\x05\x02\x00\x02\x00\x00"; /* Hold_Ind struct*/ byte CF_Ind[] = "\x09\x02\x00\x06\x00\x00\x00\x00\x00\x00"; byte Interr_Err_Ind[] = "\x0a\x02\x00\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; byte CONF_Ind[] = "\x09\x16\x00\x06\x00\x00\0x00\0x00\0x00\0x00"; ^^^^^^^^^^^^^^^^^^^ .... } PVS-Studio's diagnostic message: V638 A terminal null is present inside a string. The '\0x00' characters were encountered. Probably meant: '\x00'. message.c 4883 The arrays contain some magic numbers. What I don't like is the contents of the CONF_Ind[] array. It contains nulls together with the "x00" text. I think it's a typo, and actually this line should look as follows: byte CONF_Ind[] = "\x09\x16\x00\x06\x00\x00\x00\x00\x00\x00"; That is, '0' before 'x' is excessive and was added by mistake. It results in the "x00" values being interpreted as text, not as character codes. Suspicious code formatting static int grip_xt_read_packet(....) { .... if ((u ^ v) & 1) { buf = (buf << 1) | (u >> 1); t = strobe; i++; } else if ((((u ^ v) & (v ^ w)) >> 1) & ~(u | v | w) & 1) { .... } PVS-Studio's diagnostic message: V705 It is possible that 'else' block was forgotten or commented out, thus altering the program's operation logics. grip.c 152 I don't think there's an error here. But the code is terribly formatted - that's why I decided to include it in the article. Perhaps it should be checked just in case. Undefined behavior in shift operations static s32 snto32(__u32 value, unsigned n) { switch (n) { case 8: return ((__s8)value); case 16: return ((__s16)value); case 32: return ((__s32)value); } return value & (1 << (n - 1)) ? value | (-1 << n) : value; } PVS-Studio's diagnostic message: V610 Undefined behavior. Check the shift operator '<<. The left operand '-1' is negative. hid-core.c 1016 Shifting negative numbers causes undefined behavior. I wrote a lot on that and won't dwell on it now. Those unfamiliar with the issue, see the article "Wade not in unknown waters. Part three (about shift operators)". I can anticipate objections like, "but it works!" Well, it probably does. But I don't think the Linux kernel is the kind of software where one can rely on such an approach. The code should be rewritten. There are quite a lot of shifts like that, so I collected them all in one file: Linux-V610.txt. Mess with enum There are two enum's in the code: enum iscsi_param { .... ISCSI_PARAM_CONN_PORT, ISCSI_PARAM_CONN_ADDRESS, <<<<---- .... }; enum iscsi_host_param { ISCSI_HOST_PARAM_HWADDRESS, ISCSI_HOST_PARAM_INITIATOR_NAME, ISCSI_HOST_PARAM_NETDEV_NAME, ISCSI_HOST_PARAM_IPADDRESS, <<<<---- ISCSI_HOST_PARAM_PORT_STATE, ISCSI_HOST_PARAM_PORT_SPEED, ISCSI_HOST_PARAM_MAX, }; Note the constants ISCSI_PARAM_CONN_ADDRESS, and ISCSI_HOST_PARAM_IPADDRESS; they have similar names, and this is what I feel to be the source of the mess. Take a look at the following code fragment: int iscsi_conn_get_addr_param( struct sockaddr_storage *addr, enum iscsi_param param, char *buf) { .... switch (param) { case ISCSI_PARAM_CONN_ADDRESS: case ISCSI_HOST_PARAM_IPADDRESS: <<<<---- .... case ISCSI_PARAM_CONN_PORT: case ISCSI_PARAM_LOCAL_PORT: .... default: return -EINVAL; } return len; } PVS-Studio's diagnostic message: V556 The values of different enum types are compared: switch(ENUM_TYPE_A) { case ENUM_TYPE_B: ... }. libiscsi.c 3501 The ISCSI_HOST_PARAM_IPADDRESS constant doesn't relate to enum iscsi_param. This is most likely a typo, and the ISCSI_PARAM_CONN_ADDRESS constant must be used instead. Other similar PVS-Studio's messages: - V556 The values of different enum types are compared: switch(ENUM_TYPE_A) { case ENUM_TYPE_B: ... }. svm.c 1360 - V556 The values of different enum types are compared: switch(ENUM_TYPE_A) { case ENUM_TYPE_B: ... }. vmx.c 2690 - V556 The values of different enum types are compared: switch(ENUM_TYPE_A) { case ENUM_TYPE_B: ... }. request.c 2842 - V556 The values of different enum types are compared: switch(ENUM_TYPE_A) { case ENUM_TYPE_B: ... }. request.c 2868 Strange loop I can't show you the code fragment for this as it is pretty large, and I don't know how to reduce and make it nicely formatted. So here is a pseudo-code instead. void pvr2_encoder_cmd () { do { .... if (A) break; .... if (B) break; .... if (C) continue; .... if (E) break; .... } while(0); } The loop is executed once. I suspect the programmer chose to implement it that way in order to avoid using the goto operator. If something goes wrong, the 'break' operator is called, and the program starts executing operators after the loop. What embarrasses me is that there is the 'continue' operator instead of 'break' in one case. At the same time, it works as if it were 'break'. Let me explain the point. Here's what the standard have to say about this: §6.6.2 in the standard: "The continue statement (...) causes control to pass to the loop-continuation portion of the smallest enclosing iteration-statement, that is, to the end of the loop." (Not to the beginning.) Thus, the (0) condition will be checked after calling the 'continue' operator, and the loop will terminate as the condition is false. There are 2 possible explanations. - The code is correct. The 'continue' operator is indeed meant to terminate the loop. If this is the case, I recommend replacing it with 'break' for the sake of uniformity, and in order not to confuse developers who will maintain the code in the future. - The 'continue' operator is meant to resume the loop. Then the code is incorrect, and should be rewritten. Copy-Paste error void dm_change_dynamic_initgain_thresh( struct net_device *dev, u32 dm_type, u32 dm_value) { .... if (dm_type == DIG_TYPE_THRESH_HIGH) { dm_digtable.rssi_high_thresh = dm_value; } else if (dm_type == DIG_TYPE_THRESH_LOW) { dm_digtable.rssi_low_thresh = dm_value; } else if (dm_type == DIG_TYPE_THRESH_HIGHPWR_HIGH) <<-- { <<-- dm_digtable.rssi_high_power_highthresh = dm_value; <<-- } <<-- else if (dm_type == DIG_TYPE_THRESH_HIGHPWR_HIGH) <<-- { <<-- dm_digtable.rssi_high_power_highthresh = dm_value; <<-- } <<-- .... } PVS-Studio's diagnostic message: V517 The use of 'if (A) {...} else if (A) {...}' pattern was detected. There is a probability of logical error presence. Check lines: 1755, 1759. r8192U_dm.c 1755 The code was written through the Copy-Paste technique, and in one place the programmer forgot to replace: - DIG_TYPE_THRESH_HIGHPWR_HIGH with DIG_TYPE_THRESH_HIGHPWR_LOW - rssi_high_power_highthresh with rssi_high_power_lowthresh Also, I'd like the developers to pay attention to the following fragments: - V517 The use of 'if (A) {...} else if (A) {...}' pattern was detected. There is a probability of logical error presence. Check lines: 1670, 1672. rtl_dm.c 1670 - V517 The use of 'if (A) {...} else if (A) {...}' pattern was detected. There is a probability of logical error presence. Check lines: 530, 533. ioctl.c 530 Re-initialization There are strange fragments where a variable is assigned different values twice on end. I guess these places should be examined. static int saa7164_vbi_fmt(struct file *file, void *priv, struct v4l2_format *f) { /* ntsc */ f->fmt.vbi.samples_per_line = 1600; <<<<---- f->fmt.vbi.samples_per_line = 1440; <<<<---- f->fmt.vbi.sampling_rate = 27000000; f->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY; f->fmt.vbi.offset = 0; f->fmt.vbi.flags = 0; f->fmt.vbi.start[0] = 10; f->fmt.vbi.count[0] = 18; f->fmt.vbi.start[1] = 263 + 10 + 1; f->fmt.vbi.count[1] = 18; return 0; } PVS-Studio's diagnostic message: V519 The 'f->fmt.vbi.samples_per_line' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 1001, 1002. saa7164-vbi.c 1002 static int saa7164_vbi_buffers_alloc(struct saa7164_port *port) { .... /* Init and establish defaults */ params->samplesperline = 1440; params->numberoflines = 12; <<<<---- params->numberoflines = 18; <<<<---- params->pitch = 1600; <<<<---- params->pitch = 1440; <<<<---- params->numpagetables = 2 + ((params->numberoflines * params->pitch) / PAGE_SIZE); params->bitspersample = 8; .... } PVS-Studio's diagnostic messages: - V519 The 'params->numberoflines' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 118, 119. saa7164-vbi.c 119 - V519 The 'params->pitch' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 120, 121. saa7164-vbi.c 121 Conclusion Errors can be found in any large project. The Linux kernel is no exception. However, running a static analyzer for occasional checks, is not the right way of using it. True, they can help you write a promo article like this, but they are of little use to the project. Use static analysis regularly, and it will help you save plenty of time by detecting a number of errors almost as soon as they have been introduced into the code. Protect your project from bugs with a static analyzer! Anyone interested is welcome to try PVS-Studio on their projects. The analyzer runs under Windows. If you want to use it in development of large Linux applications, write to us and we'll discuss possible options for drawing a contract on adapting PVS-Studio for your projects and tasks.
http://www.viva64.com/en/b/0299/
CC-MAIN-2016-30
refinedweb
5,482
58.18
This sample demonstrates how you can use the AutoCompleteExtender control from ASP.NET AJAX Control Toolkit and customize its behavior without modifying it. I like Google's suggest feature and was thinking of using it in any of my projects. ASP.NET's AJAX Control Toolkit has a similar control ( AutoCompleteExtender) which provides the basic items to complete this functionality. I searched about its usage and found many examples, but I was not satisfied with them. They were all populating only a single field using this extender. I then came up with an idea, why not fill the contact details including the name, email address, and phone numbers using just one extender, but without modifying any provided functionality, so that our code can be used with newer versions. Below is what it will look like after populating that contact form. Let's check out how AutoCompleteExtender works. Below is the description for this on toolkit's sample site. AutoCompleteis an ASP.NET AJAX extender that can be attached to any TextBoxcontrol, and will associate that control with a popup panel to display words that begin with the prefix typed into the textbox. The dropdownwith candidate words supplied by a web service is positioned on the bottom left of the textbox. It says that this control will fetch its data from a webservice, and it can be attached to a TextBox control (it can only be attached with one control). When users starts typing in that TextBox control, it fetches a suggestion list from the configured webservice. So we need two things, one would be our sample contact page, and the other will b a webservice. Here is our webservice code. cannot access it from your client script. [ScriptService()] public class SuggestionService : System.Web.Services.WebService { Our webmethod would return a, the first is the text which will be displayed and to my rescue. has a prefix, area code, number and extension fields. <div style="border: 1px solid rgb(204, 204, 204); padding: 10px; width: 400px;"> <table cellspacing="0" cellpadding="0" border="0"> <tbody><tr> <td style="width: 100px; text-align: right;">First Name:</td> <td><asp:textbox</td> </tr> <tr> <td style="width: 100px; text-align: right;">Last Name:</td> <td><asp:textbox</td> </tr> <tr> <td style="width: 100px; text-align: right;">Home Phone:</td> <td> <table cellspacing="0" cellpadding="0" border="0"> <tbody><tr> <td><asp:textbox</td> <td>-<asp:textbox</td> <td>-<asp:textbox</td> </tr> </tbody></table> </td> </tr> <tr> <td style="width: 100px; text-align: right;">Work Phone:</td> <td> <table cellspacing="0" cellpadding="0" border="0"> <tbody><tr> <td><asp:textbox</td> <td>-<asp:textbox</td> <td>-<asp:textbox</td> <td> x </td> <td><asp:textbox</td> </tr> </tbody></table> </td> </tr> <tr> <td style="width: 100px; text-align: right;">Email Address :</td> <td><asp:textbox</td> </tr> </tbody>< their description on AutoCompleteExtender sample page. We must set some of them to activate its working. First specify the ServicePath and set it to our webservice we just created and then set the ServiceMethod, which will return a the firstname field, and when you select any item from that list, only firstname field is set with the above JavaScript function. This function would parse the value attribute, which is a valid JSON data passed from our webservice, and set appropriate fields with this parsed data. This concludes our sample. Now you can test it yourself. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/ajax/autosuggestextender.aspx
crawl-002
refinedweb
577
61.77
Dino Esposito One of the things I like most in ASP.NET MVC is the ability to expose a façade of methods that can be easily invoked from HTTP clients, including jQuery-based pages, mobile apps and plain C# back ends. For a long time, building this service layer took place in the realm of Windows Communication Foundation (WCF) services. Attempts were made to specialize WCF for HTTP, such as the introduction of the webHttpBinding mechanism and frameworks such as the now-retired REST Starter Kit. None of these approaches, though, could really eliminate developer roadblocks such as notorious WCF over-configuration, overuse of attributes and a structure not specifically designed for testability. Then came Web API—a new framework designed to be thin, testable, independent from the hosting environment (for example, IIS) and HTTP-focused. However, Web API has a programming interface that looks almost too similar to ASP.NET MVC, in my opinion. This isn’t a negative remark, though, as ASP.NET MVC has a clean and well-defined programming interface. Web API actually started with a programming model that looked similar to WCF and then grew to resemble ASP.NET MVC. In this article, I’ll provide a view of Web API from the perspective of the average ASP.NET MVC developer, and focus on a functional area of Web API that represents a plus over plain ASP.NET MVC: content negotiation. Web API is a framework you can use to create a library of classes that can handle HTTP requests. The resulting library, along with some initial configuration settings, can be hosted in a runtime environment and consumed by callers via HTTP. Public methods on controller classes become HTTP endpoints. Configurable routing rules help define the form of URLs used to access specific methods. With the exception of routing, however, most of what defines the default form of URL handling in Web API is convention rather than configuration. If you’re an ASP.NET MVC developer, at this point you might stop reading and wonder why on earth you’d want to use a new framework that seems to just duplicate the concept of controllers you “already have” in ASP.NET MVC. The quick answer to that is, yes, you probably don’t need Web API in ASP.NET MVC, because you can achieve nearly the same functionality via plain controllers. For example, you can easily return data formatted as JSON or XML strings. You can easily return binary data or plain text. You can shape up the URL templates you like best. The same controller class can serve JSON data or an HTML view, and you can easily separate controllers that return HTML from controllers that just return data. In fact, a common practice is to have an ApiController class in the project where you stuff all endpoints expected to return plain data. Here’s an example: public class ApiController : Controller { public ActionResult Customers() { var data = _repository.GetAllCustomers(); return Json(data, JsonRequestBehavior.AllowGet); } … } Web API uses the best of the ASP.NET MVC architecture and improves it in two main areas. First, it introduces a new logical layer known as content negotiation with a standard set of rules to request data in a given format, whether JSON, XML or some other format. Second, Web API has no dependencies whatsoever on ASP.NET and IIS—more specifically, it has no dependency on the system.web.dll library. Certainly it can be hosted in an ASP.NET application under IIS. However, while this probably remains the most common scenario, a Web API library can be hosted in any other application that provides an ad hoc hosting environment, such as a Windows service, a Windows Presentation Foundation (WPF) application or a console application. At the same time, if you’re an expert ASP.NET MVC developer, the Web API concepts of controllers, model binding, routing and action filters will be familiar to you. If you’re an ASP.NET MVC developer, you might be initially confused regarding the benefits of Web API because its programming model looks nearly identical to ASP.NET MVC. However, if you’re a Web Forms developer, you shouldn’t be confused. With Web API, exposing HTTP endpoints from within a Web Forms application is a child’s game. All it takes is adding one or more classes similar to this: public class ValuesController : ApiController { public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } public string Get(int id) { return "value"; } } Note that this is the same code you’d use to add a Web API controller to an ASP.NET MVC application. You also have to specify routes. Here’s some code you want to run at application startup: RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = System.Web.Http.RouteParameter.Optional }); Unless otherwise annotated with the NonAction attribute, any public methods on the class that match the default naming and routing conventions are public HTTP-callable endpoints. They can be called from any client without the need for generated proxy classes, web.config references or special code. Routing conventions in Web API dictate the URL starts with /api followed by the controller name. Note that there’s no action name clearly expressed. The action is determined by the type of request, whether GET, PUT, POST or DELETE. A method name that begins with Get, Put, Post or Delete is conventionally mapped to the corresponding action. For example, a method GetTasks on a TaskController will be invoked for any GET request to a URL such as /api/task. Regardless of the apparent similarity of behavior and class names with ASP.NET MVC, Web API lives in a completely separate set of assemblies and uses a completely different set of types—System.Net.Http is the primary assembly. : Howard Dierking (Microsoft)Howard Dierking is a program manager on the Windows Azure Frameworks and Tools team where his focus is on ASP.NET, NuGet and Web APIs. Previously, Dierking served as the editor in chief of MSDN Magazine, and also ran the developer certification program for Microsoft Learning. He spent 10 years prior to Microsoft as a developer and application architect with a focus on distributed systems. "If you’re building solutions other than ASP.NET MVC applications, using Web API is a no-brainer." Very true, especially if you are using Web Forms. Building off that comment, and off your recent article on Code Magazine: "Planning Web Solutions Today: Web Forms, ASP.NET MVC, Web API, and OWIN. Oh My!", , I think there is now a new way to design Web Forms applications, but I have not seen any in depth articles or technical advice on the subject. Part of the reason for the lack of information on the subject is that whenever we see articles comparing MVC and Web Forms, the article authors typically (and with good reason) make the assumption that a Web Forms application is all about using server controls, and AJAX, if used, involves server controls like the UpdatePanel. Yet even prior to ASP.NET Web Api, page method(s) in a single code behind file of a Web Forms page allowed the developer to gain control over html, css, and seamless data refreshes: except for the the single form element, and a few less common scenarios, resorting to server controls becomes unnecessary. With ASP.NET Web Api, the tasks we might have done before with page methods in code behind break free from their dependency on the code behind file. A Web Forms app can be used as the outer shell of a "Single Page Application", or a single site made up of multiple mini-SPA's. You leverage Web Forms for login/authentication, and for its high-level (not directly impacting html tags) Master Page page layout tool. Once a user logs in, you have one (or a few) .aspx pages that serve as the base page from with the spa (or mini-spa's) begin, and then you go to work with Angular, Ember, Knockout, or whatever other JS framework. Also worth noting is that even in VS 2010, you can have clean urls, bundling, and minification with Web Forms. I would appreciate if you could write in depth on this approach: maybe it breathes new life into the usage of Web Forms apps and changes the discussion of the traditional Web Forms vs .NET MVC debate. Thanks! Content negotiation become more complex when caching and per-type resource extension are thrown into the mix. By per-type resource extension I mean, for example, incorporating supplemental data required for layout templates for HTML rendering, as well as for updating the layout client-side to support single-page navigation. Content negotiation yields great value, but is not by any means easy to achieve. NIce More MSDN Magazine Blog entries > Browse All MSDN Magazines Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
http://msdn.microsoft.com/en-us/magazine/dn574797.aspx
CC-MAIN-2014-23
refinedweb
1,502
54.52
Console Applications Hi all, through this wizard: File > New file or Project > Application > Qt console application, I created a project and wrote this into main.cpp: #include <QCoreApplication> #include <qtextstream.h> QTextStream cout(stdout, QIODevice::WriteOnly); int main(int argc, char** argv) { // avoid compiler warnings Q_UNUSED(argc) Q_UNUSED(argv) QString s1("Paris"); QString s2("London"); // string concatenation QString s = s1 + " " + s2 + "!"; cout << s << endl; } When I run it using Desktop kit, it shows nothing! What is the reason please? The result of Qt console application is available inside qtcreator in application ouput As described in this sample image Good, thank you. Where are these kinds of apps used and useful? @tomy said in Console Applications: Good, thank you. Where are these kinds of apps used and useful? If you want to have an application without any Human machine interface Does it mean an app in communication with another app/hardware (without any show to the owner of the machine/app/hardware), like in a refrigerator? @tomy said in Console Applications: Does it mean an app in communication with another app/hardware (without any show to the owner of the machine/app/hardware), like in a refrigerator? I am not sure,but i think yes This is what wikipedia says about Console application ...For data processing tasks and computer administration.. Maybe expiremented people ,can enlighten us a bit more ? @tomy No... console apps are applications your run on the console/terminal. In linux a lot of applications are console only. No GUI. Console applications can have a UI just not a GUI. Think about almost any command you've ever run, it's a console application. Things like tar, ls, cp, rmdir, etc are all console apps. Most utilities provide a console method with their applications. So things like winzip will have their gui mode but also a console mode. This helps in automation and running applications from batch scripts, etc. Even the compiler you use in Qt Creator is a console application.. Hope that helps you understand the difference. No... console apps are applications your run on the console/terminal. Like CMD on Windows, or when I run qmake, binarycreator .exe file by CMD, yeah? In linux a lot of applications are console only. No GUI. Console applications can have a UI just not a GUI. Yes, I've written many many console apps in C++ so far, but I was curious to know their application in the real world. Think about almost any command you've ever run, it's a console application. Things like tar, ls, cp, rmdir, etc are all console apps. I don't know these extensions :-) but I got your mean. Most utilities provide a console method with their applications. So things like winzip will have their gui mode but also a console mode. This helps in automation and running applications from batch scripts, etc. Does it mean this provide the user of of such an app with "two" ways of executing a given app? If so, why should the programmer bother himself for that extra way!? Even the compiler you use in Qt Creator is a console application. And does it mean that the Qt Creator has two parts: an IDE (which is visual) and we work on it, and a practical and functional part which we don't deal with it directly but it does the work?. Ow great. A funny story: When I was always writing console applications (all the drills, exercises and try-this-s of the C++ programming book of B.Stroustrup), I didn't like them and would think that the only benefit of these hard-working on writing these apps is to make us ready to use them on GUI apps! Hope that helps you understand the difference. It helped much and thank you. :-) @tomy Yea exactly like cmd on windows. That is the console for a windows platform. Real world console applications are things like utilities, servers, etc. Some you might know in windows are ipconfig, ping, net, etc. Those "extensions" are all applications in a posix environment. Linux/osx/android/etc. I can give you a real world example for the multi-UI approach... Recently I was contracted to write a program that handled packaging of files for distribution to embedded devices like credit card terminals, etc. We'll call it package manager. This package manager had a GUI where you could build the packages easily with drag and drop from the filesystem, etc. It handled all the devices types you could create the packages for, and generally was easy to use as GUIs tend to be. However, there was a build and automation team at this company who needed to make these packages as well. For them I provided the same functionality but in a CLI (command line interface AKA a console application). This allowed them to automate creating of packages with their ruby scripts. Also it allowed the SCM build management team to create packages as parts of the build for customers all from cmake and other automated build environments. Qmake could do it as well. So basically, GUIs save a lot of typing work, but require human interaction. CLIs you can pass the information in via a file or on the command line, however you want, and it's automated. So it can all be run as part of an automated thing. There are a lot of times where I prefer console apps to GUI ones. Most people who want to mess with files on their system would open a file manager (in windows Explorer), click around to browse to their files, etc. For me I prefer the console. I would open a terminal, cd to the directory I need, cp to copy files, mv to move, etc. I much prefer typing to a mouse. A mouse is slow, typing is very fast, especially if you know hot keys for everything. A good example of this.. let's say you wanted to know your IP address (in windows)... With a keyboard not even touching your mouse you could hit Window+R type cmd hit enter. Then type ipconfig /all<enter> and you're done. That's using the CLI. To do the same thing in the GUI, you have to click start, control panel, Network Settings, Right click your adapter, properties, double click TCP/IP v4, and finally you have your IP address... It would take me about 3 seconds with a keyboard and upwards of 15-20s with a mouse. And finally yes, most (all?) IDEs are just ways to wrap the underlying console tools. So Qt Creator uses mingw or visual studio as it's compiler, and gdb (or vs?) as it's debugger. Everything you do in Qt Creator can be done (very easily) without it. You can do it on the command line, or you can use other IDEs. As a die hard vim user I prefer VI compatible IDEs like slickedit or clion (those aren't free though). Creator has some basic vim support which is cool, as does visual studio. CLion is my favorite these days though. It doesn't have support for Qml at the moment which annoys me but I think when I get time I will write a Qml plugin for it, assuming they don't beat me to it. ;) A final example... in Qt Creator you would hit build, underneath here is what it would do with a hidden console: qmake mingw32-make -j4 So you could do that on your own without the IDE if you wanted. This is more prevalent in osx or linux than in windows though. Windows command line stuff is annoying rather than helpful like it is in a posix environment. @tomy said in Console Applications: Does it mean an app in communication with another app/hardware (without any show to the owner of the machine/app/hardware), like in a refrigerator? This is called embedded software. SW + HW like an "intelligent" refrigerator is an embedded system. Console applications can be command line applications which means you write one command (with command line arguments) and the application runs without further interaction. A console application can also have a TUI, text based user interface (see the wikipedia article mentioned above) using for example ncurses library. Or it can be line based interactive like many C++ tutorial applications, writing output line by line and receiving text input one line at a time. Actually many of the real life GUI applications have some console features. If nothing else, you can start it with an argument like "--version" (many GNU/Linux apps) or "/?" (many Windows apps) and they output the version number or short help. Many apps can take any file name as an argument and try to open it as if you chose the file from File->Open. In your own applications command line arguments can be very useful in development phase, you (or a test user) can give --debug argument and your main() code switches debugging with qDebug on. Or you can switch features on/off without changing the code and rebuilding. In Qt Creator open Projects->Run and you can add Command line arguments there. In your program you can handle command line arguments with QCommandLineParser, or in simple cases just get them with QCoreApplication::arguments() and handle the string list. I agree that these console uses are very prevalent in mac os and linux and you have been on linux and it has made it that you prefer console to mouse clicks. I think windows command line stuff is not very annoying (and you used it to demonstrate the ability of a cmd compared to mouse clicks in the IP example!) Lets teach me (!) using a CLI instead of the IDE in Qt Creator: As shown above, I've created a console project (in the first post of the thread), then wrote a simple code in the main.cpp. Now in the IDE I can click on run (or ctrl+r) to see the result. Then it finishes. How to do these things (this process) using CLI without using the IDE? As an out of scope question: do you return the base of CMD (DOS OS) to Unix? @tomy "As an out of scope question: do you return the base of CMD (DOS OS) to Unix?" - what does it mean? What is base? Writing a simple CLI C++ app without IDE in a terminal (CMD): - Use an editor to write your cpp file (for example vim or what ever): vim myapp.cpp - Then call the compiler: g++ -o myapp myapp.cpp - Then start your app: ./myapp That's all for a simple app. In Qt creator you can see what it does if you press CTRL-R in "Compile Output" tab: it uses only CLI tools, like qmake, compiler (for example g++), linker,... Console apps are not only important on UNIX/Linux/MacOS but even on Windows. You need them for example to write scripts, build software,... - ambershark @tomy @jsulm's example is perfect for linux but since I know you don't know linux yet and are using windows I'll give you the same thing for windows: Launch a cmd and do the following: > mkdir test > cd test create a main.cpp with somthing like: #include <iostream> using namespace std; int main() { cout << "hello world" << endl; return 0; } > qmake -project > qmake > mingw32-make > test.exe This assumes you have /path/to/qt/bin in your path variable in order to use and access qmake. It also assumes you have mingw32 compiler installed. If not substitute compilation command mingw32-makefor whatever compiler you have. This is a great example of where linux is easier than windows on a command line (from our other thread). There is no real additional setup in linux, all the stuff @jsulm wrote works right out of the box. Edit: Explaining some of the commands -- qmake -projectWill create you a test.pro file. This is only done once to bootstrap your project file. After that you modify that .pro file to add the things you need. qmakeevaluates the project file and creates a makefile for you. mingw32-makeinvokes the make program for the mingw compiler. This will execute the Makefile that was generated when you ran qmake and build your application using mingw32-g++, and other pieces it needs to compile and link. Thank you very much. One question: "> test.exe" Why should we have a test.exefile? @tomy Hi The test.exe comes from the executing the real makefile as neatly explained in section "mingw32-make " :) Hi, I asked because I don't have that file in the test folder! - mrjj Qt Champions 2016 @tomy Well do you see .o file ? Maybe there is a build folder one level up? If not, then show the log (text) you get from running mingw32-make (step) Maybe there is compile or link error as that would do that no .exe is created. Ah, sorry. Its in the release folder Oops sorry I forget that in windows things like Release/ and Debug/ folders. :) @ambershark Well i had to follow the sample and see. Was not sure what would really happen :) @mrjj Lol. I'm glad it actually worked since I just typed that out without testing anything. And I don't use windows much so I could easily have messed it up. :) Sorry there isn't such a file an any folder there: - jsulm Moderators @tomy Maybe it is just called differently? So, is there ANY *.exe file? Also, if you build in CMD you actually will see which files are generated. Did you check? Look, I did these: Creating a C++ file named "main" with a simple code in it, in the "test" folder. Then, found and ran all three commands (qmake -project, qmake, mingw32-make). And the result as shown above (with no ".exe" file in the "test" folder. I CMD: @tomy Looks like g++ is not found. Try to add the bin directory of your MinGW installation to PATH and try again. Hi An alternative to fiddling with path is to run the c:\Qt\5.8\mingw53_32\bin\qtenv2.bat in the cmd before trying to compile. Hi An alternative to fiddling with path is to run the c:\Qt\5.8\mingw53_32\bin\qtenv2.bat in the cmd before trying to compile. Hi, "The system cannot find the path specified." Anyway, it's not that important and we can leave it out because it's not my purpose to be familiar with running files from CMd, now. Maybe when needed. (I liked to test that simple example this way but, the testing may not be so easy) Thanks. @tomy Depending on the MinGW version you install the path can be a bit different. Just search for qtenv2.bat file in your Qt installation directory. Yes, I did it and I think the system is set now and ready for the next tests. You can look at this: "text.exe" exists but nothing is shown after test.exe in CMD. Update: After re-opening the CMD and testing the .exe: - Flotisable @tomy Locate the libgcc_... file on your system and copy it to the same directory with the exe. Or set the PATH variable. See. @tomy said in Console Applications: "The system cannot find the path specified." Well you need to use the correct path for your installation. It sets the correct path for tools but that you can also do in other ways. - mrjj Qt Champions 2016 @tomy You need to provide the DLLs it wants from the CORRECT compiler folder under c:\Qt so you end up with (maybe more DLLs) Please read You need to provide the DLLs it wants from the CORRECT compiler folder under c:\Qt so you end up with (maybe more DLLs) I added them from the folder: C:\Qt\Qt5.8.0\5.8\mingw53_32 No reaction. @tomy Did you read the link ? Anyway, it might need extra dlls :) You can try the tool or use To check the dlls. Anyway, to make it run, that release folder must be an deployment folder so keep reading docs and it will work :). @tomy well being experienced means you know for each job what is the right tool. Besides using GUI or CLI is 2 sides of same coin. If you look in Creator/VS you can see the command line it uses to get the job done. So if i need CLI action i will visually create and edit files and then simply steal the CLI line to build it. That way i can use CLI when it suits :) Its not fair to dismiss CLI as GUI would be nothing without it. GUI was invented to make life easier for those of us that feels CLI is just too much typing but i work with ppl that can create something 10X faster using CLI. Building libs and dependencies. They like CLI for the direct power user control it gives. If its not for your liking ( or mine ;) then its not the tools fault in my opinion. The reason it just dont work for you is that the environment is not setup and u are used to the IDE setting it up before running exe. The qtenv2.bat was part of that automation etc. So power user will bother to use CLI as its efficient and there is noi layer in between (the IDE) so they prefer CLI and some kinky editor :) - ambershark @tomy said in Console Applications:. Oh yea CLI is faster in some cases not all. The reason I recommended you trying the CLI for a console app is to learn this stuff. But I bet if we raced, me on a CLI, you with the IDE, I'd win every time. ;) I'm not saying don't use an IDE, they are great. But you should at least understand what the IDE is hiding from you (or making easier). Like @mrjj said GUIs are just making life easier for people who want to type less. And they usually do a great job. I use an IDE too, but not always. For a lot of things I use the CLI since it's so much faster. Git for instance. Almost always command line unless there is a complex command, then I'll use a gui. All the problems you're running into here are things you will need to know how to deal with. If you were to distribute any software you would need to deal with all these dlls to get it to run on someone else's machine. This is normal development stuff that the IDE is hiding from you. It's very important to learn. This is also really only an issue with windows. Windows has (at least in my opinion) really annoying ways of finding and using libraries for an application. On a linux or mac system with a properly set up Qt environment, the binary would just run without needing to be pointed at the right supporting libraries, or having to make a distribution by copying the libs to your app directory. Well, not entirely true, posix OSes have these issues as well but it's really only when you need to make a release distribution and not during development. Even on the command line. Yeah, of course you would win :-) ;) GUIs are just making life easier for people who want to type less. All people (except professionals) like this way; and since I want to be a professional on this case too, I will certainly catch this topic. I think when I will start using Linux, it will be a good point to learn it too, or even by using the Linux terminal it will be easily achievable. If you were to distribute any software you would need to deal with all these dlls to get it to run on someone else's machine. I've done this before. :-) When I using my C++ experience became able to write a good accurate Qt GUI calculator while I'd read only the first chapter of the Qt book (a few pages), I went to make it installable on others' machines and went to the end of the process and by Qt Framework Installer the goal was available. ;) So, I'd gone the way, "but", I wouldn't like to re-go through such a rather complex way for such a simple code (main.cpp). :) Windows has (at least in my opinion) really annoying ways of finding and using libraries for an application. :-) :D Thanks. @tomy said in Console Applications: I think when I will start using Linux, it will be a good point to learn it too, or even by using the Linux terminal it will be easily achievable. Definitely a good time to learn command line stuff. Linux is a command line OS. You can install a window manager and run GUI apps but it's not a native linux thing. It's a completely separate program. You don't necessarily need to learn the command line stuff to succeed as a professional developer, but it will help a lot. And you will never be as good as someone else who knows it.
https://forum.qt.io/topic/76952/console-applications
CC-MAIN-2017-39
refinedweb
3,556
73.47
Write a C, C++ program to find largest element in an unsorted array. You can solve this problem using multiple approach. First Approach Sort an array. Once array is sorted, last element of an array is largest. For sorting you can use selection sort, Bubble Sort , QuickSort, MergeSort etc. Quicksort and MergeSort is best for sorting large elements in minimum time complexity( O(nlogn) ). Second Approach i) Take one flag and initialize it to first element of an array. ii) Run a loop and compare with each element, if any element is greater than the assigned value then update the largest variable. Program to Find Smallest Element in An Array More Question on Arrays C++ Program to find largest element in an Array #include <iostream> using namespace std; int main() { /* Declare an array of length 50 .*/ int arr[50],i,n,largest; cout<<"Enter how many elements you want to enter (keep less than 50)"; cin>>n; for(i=0;i<n;i++){ cin>>arr[i]; } /* Initialize it to the first element of an array. */ largest=arr[0]; /* Traverse and compare each element of an array. */ for( i=0;i<n;i++) { if(arr[i]>largest){ largest=arr[i]; } } cout<<" \nLargest element of an array is "<<largest; return 0; }Output : Enter how many elements you want to enter (keep lesst than 50) : 5 7 3 8 2 4 Largest element of an array is 8
http://www.cprogrammingcode.com/2012/05/write-program-to-find-largest-element.html
CC-MAIN-2021-17
refinedweb
235
62.17
jLinq – Extending A Method It wasn’t until late into the jLinq project that I had the idea that you should be able to extend your own methods onto the main library. jLinq ended up having quite a rewrite in order to make it fit that model. jLinq is actually entirely composed to extension methods which I suppose is a form of dog-fooding your own product. If I couldn’t do it with an extension method, then my framework didn’t expose enough to a future developer. The jLinq Documentation section is still under-construction at this point, so this post serves as a brief introduction to extending jLinq. jLinq allows you to extend jLinq in three separate ways. - Create an entirely new function in the jLinq library - Create a new function in a separate namespace in the jLinq library - Create your own library (with a copy of the existing jLinq library) Each of these methods allow you to add one of four types of functions. This may change as time goes on to allow more methods, but for now these are what is available. Source Commands A source command is the first command you call when performing a jLinq query. The command .from() is a good example of a source command. Source commands return a jLinq object and any extension methods that have been provided. A source command should also set the data that is being queried Query Commands A query command is what sets the comparisons that are used when making a selection. Query commands are not run immediately so you are able to use operators like or() and not() to set how the query is evaluated. The criteria is not evaluated until you call a selection command which is explained more in a moment. Action Commands An action command affects a query or data, but doesn’t actually change what is selected. A good example is the .orderBy() command. This command resorts the information for the query, but doesn’t change what will ultimately be selected. Selection Commands A selection command can return anything, including the query being created. Normally, a selection command returns the results of the query as an array. Sometimes a selection command will return something different, like with commands like .count() or .isEmpty(), which return numbers and booleans. More About Extensions Namespaces jLinq doesn’t allow you to overwrite a method in the core. Instead, if you want to create a command that is the same name as an existing command, you must provide a namespace to put it into. This way, naming conflicts are minimized. You access a command the same way you normally would, except you include the namespace first jLinq.from(...).custom.startsWith(...). Custom Libraries Another thing you can do is create a separate instance of the jLinq library under a different name (technically, you can override jLinq at that point, but that wouldn’t be very nice). If you’re working with a custom library then you can override anything (granted you don’t lock the library too, which will be explained in another post) More Control You can see that jLinq gives you complete control over how you use the library. Hopefully people begin to develop add-ins for jLinq that can be shared at the jLinq Message Boards. If you have questions or comments, please share them here or at the message boards. I’d love to get some feedback!
https://somewebguy.wordpress.com/2009/05/03/jlinq-extending-a-method/
CC-MAIN-2017-17
refinedweb
574
61.06
Python provides a powerful set of tools to create and manipulate lists of data. In this part, we take a deep dive into the Python list type. We use Python lists to implement and optimize the Sieve of Eratosthenes, which will produce a list of all prime numbers up to a big number (like 10 million) in a snap. Along the way, we introduce some Python techniques for mathematical functions and data analysis. This programming lesson is meant to complement Chapter 2 of An Illustrated Theory of Numbers, and mathematical background can be found there. Before diving into lists, we recall the brute force primality test that we created in the last lesson. To test whether a number n is prime, we can simply check for factors. This yields the following primality test. def is_prime(n): ''' Checks whether the argument n is a prime number. Uses a brute force search for factors between 1 and n. ''' for j in range(2,n): # the range of numbers 2,3,...,n-1. if n%j == 0: # is n divisible by j? print("{} is a factor of {}.".format(j,n)) return False return True We can also implement this test with a while loop instead of a for loop. This doesn't make much of a difference, in Python 3.x. (In Python 2.x, this would save memory). def is_prime(n): ''' Checks whether the argument n is a prime number. Uses a brute force search for factors between 1 and n. ''' j = 2 while j < n: # j will proceed through the list of numbers 2,3,...,n-1. if n%j == 0: # is n divisible by j? print("{} is a factor of {}.".format(j,n)) return False j = j + 1 # There's a Python abbreviation for this: j += 1. return True is_prime(10001) is_prime(101) If $n$ is a prime number, then the is_prime(n) function will iterate through all the numbers between $2$ and $n-1$. But this is overkill! Indeed, if $n$ is not prime, it will have a factor between $2$ and the square root of $n$. This is because factors come in pairs: if $ab = n$, then one of the factors, $a$ or $b$, must be less than or equal to the square root of $n$. So it suffices to search for factors up to (and including) the square root of $n$. We haven't worked with square roots in Python yet. But Python comes with a standard math package which enables square roots, trig functions, logs, and more. Click the previous link for documentation. This package doesn't load automatically when you start Python, so you have to load it with a little Python code. from math import sqrt This command imports the square root function ( sqrt) from the package called math. Now you can find square roots. sqrt(1000) There are a few different ways to import functions from packages. The above syntax is a good starting point, but sometimes problems can arise if different packages have functions with the same name. Here are a few methods of importing the sqrt function and how they differ. from math import sqrt: After this command, sqrt will refer to the function from the math package (overriding any previous definition). import math: After this command, all the functions from the math package will be imported. But to call sqrt, you would type a command like math.sqrt(1000). This is convenient if there are potential conflicts with other packages. from math import *: After this command, all the functions from the math package will be imported. To call them, you can access them directly with a command like sqrt(1000). This can easily cause conflicts with other packages, since packages can have hundreds of functions in them! import math as mth: Some people like abbreviations. This imports all the functions from the math package. To call one, you type a command like mth.sqrt(1000). import math math.sqrt(1000) factorial(10) # This will cause an error! math.factorial(10) # This is ok, since the math package comes with a function called factorial. Now let's improve our is_prime(n) function by searching for factors only up to the square root of the number n. We consider two options. def is_prime_slow(n): ''' Checks whether the argument n is a prime number. Uses a brute force search for factors between 1 and n. ''' j = 2 while j <= sqrt def is_prime_fast(n): ''' Checks whether the argument n is a prime number. Uses a brute force search for factors between 1 and n. ''' j = 2 root_n = sqrt(n) while j <= root is_prime_fast(1000003) is_prime_slow(1000003) I've chosen function names with "fast" and "slow" in them. But what makes them faster or slower? Are they faster than the original? And how can we tell? Python comes with a great set of tools for these questions. The simplest (for the user) are the time utilities. By placing the magic %timeit before a command, Python does something like the following: Give it a try below, to compare the speed of the functions is_prime (the original) with the new is_prime_fast and is_prime_slow. Note that the %timeit commands might take a little while. %timeit is_prime_fast(1000003) %timeit is_prime_slow(1000003) %timeit is_prime(1000003) Time is measured in seconds, milliseconds (1 ms = 1/1000 second), microseconds (1 µs = 1/1,000,000 second), and nanoseconds (1 ns = 1/1,000,000,000 second). So it might appear at first that is_prime is the fastest, or about the same speed. But check the units! The other two approaches are about a thousand times faster! How much faster were they on your computer? is_prime_fast(10000000000037) # Don't try this with `is_prime` unless you want to wait for a long time! Indeed, the is_prime_fast(n) function will go through a loop of length about sqrt(n) when n is prime. But is_prime(n) will go through a loop of length about n. Since sqrt(n) is much less than n, especially when n is large, the is_prime_fast(n) function is much faster. Between is_prime_fast and is_prime_slow, the difference is that the fast version precomputes the square root sqrt(n) before going through the loop, where the slow version repeats the sqrt(n) every time the loop is repeated. Indeed, writing while j <= sqrt(n): suggests that Python might execute sqrt(n) every time to check. This might lead to Python computing the same square root a million times... unnecessarily! A basic principle of programming is to avoid repetition. If you have the memory space, just compute once and store the result. It will probably be faster to pull the result out of memory than to compute it again. Python does tend to be pretty smart, however. It's possible that Python is precomputing sqrt(n) even in the slow loop, just because it's clever enough to tell in advance that the same thing is being computed over and over again. This depends on your Python version and takes place behind the scenes. If you want to figure it out, there's a whole set of tools (for advanced programmers) like the disassembler to figure out what Python is doing. is_prime_fast(10**14 + 37) # This might get a bit of delay. Now we have a function is_prime_fast(n) that is speedy for numbers n in the trillions! You'll probably start to hit a delay around $10^{15}$ or so, and the delays will become intolerable if you add too many more digits. In a future lesson, we will see a different primality test that will be essentially instant even for numbers around $10^{1000}$! To check whether a number n is prime, you can first check whether n is even, and then check whether n has any odd factors. Change the is_prime_fast function by implementing this improvement. How much of a speedup did you get? Use the %timeit tool to study the speed of is_prime_fast for various sizes of n. Using 10-20 data points, make a graph relating the size of n to the time taken by the is_prime_fast function. Write a function is_square(n) to test whether a given integer n is a perfect square (like 0, 1, 4, 9, 16, etc.). How fast can you make it run? Describe the different approaches you try and which are fastest. We have already (briefly) encountered the list type in Python. Recall that the range command produces a range, which can be used to produce a list. For example, list(range(10)) produces the list [0,1,2,3,4,5,6,7,8,9]. You can also create your own list by a writing out its terms, e.g. L = [4,7,10]. Here we work with lists, and a very Pythonic approach to list manipulation. With practice, this can be a powerful tool to write fast algorithms, exploiting the hard-wired capability of your computer to shift and slice large chunks of data. Our application will be to implement the Sieve of Eratosthenes, producing a long list of prime numbers (without using any is_prime test along the way). We begin by creating two lists to play with. L = [0,'one',2,'three',4,'five',6,'seven',8,'nine',10] L[3] print(L[3]) # Note that Python has slightly different approaches to the print-function, and the output above. print(L[4]) # We will use the print function, because it makes our printing intentions clear. print(L[0]) The location of an entry is called its index. So at the index 3, the list L stores the entry three. Note that the same entry can occur in many places in a list. E.g. [7,7,7] is a list with 7 at the zeroth, first, and second index. print(L[-1]) print(L[-2]) The last bit of code demonstrates a cool Python trick. The "-1st" entry in a list refers to the last entry. The "-2nd entry" refers to the second-to-last entry, and so on. It gives a convenient way to access both sides of the list, even if you don't know how long it is. Of course, you can use Python to find out how long a list is. len(L) You can also use Python to find the sum of a list of numbers. sum([1,2,3,4,5]) sum(range(100)) # Be careful. This is the sum of which numbers? # The sum function can take lists or ranges. Slicing lists allows us to create new lists (or ranges) from old lists (or ranges), by chopping off one end or the other, or even slicing out entries at a fixed interval. The simplest syntax has the form L[a:b] where a denotes the index of the starting entry and index of the final entry is one less than b. It is best to try a few examples to get a feel for it. Slicing a list with a command like L[a:b] doesn't actually change the original list L. It just extracts some terms from the list and outputs those terms. Soon enough, we will change the list L using a list assignment. L[0:5] L[5:11] # Notice that L[0:5] and L[5:11] together recover the whole list. L[3:7] This continues the strange (for beginners) Python convention of starting at the first number and ending just before the last number. Compare to range(3,7), for example. The command L[0:5] can be replaced by L[:5] to abbreviate. The empty opening index tells Python to start at the beginning. Similarly, the command L[5:11] can be replaced by L[5:]. The empty closing index tells Python to end the slice and the end. This is helpful if one doesn't know where the list ends. L[:5] L[3:] Just like the range command, list slicing can take an optional third argument to give a step size. To understand this, try the command below. L[2:10] L[2:10:3] If, in this three-argument syntax, the first or second argument is absent, then the slice starts at the beginning of the list or ends at the end of the list accordingly. L # Just a reminder. We haven't modified the original list! L[:9:3] # Start at zero, go up to (but not including) 9, by steps of 3. L[2: :3] # Start at two, go up through the end of the list, by steps of 3. L[::3] # Start at zero, go up through the end of the list, by steps of 3. Not only can we extract and study terms or slices of a list, we can change them by assignment. The simplest case would be changing a single term of a list. print(L) # Start with the list L. L[5] = 'Bacon!' print(L) # What do you think L is now? print(L[2::3]) # What do you think this will do? We can change an entire slice of a list with a single assignment. Let's change the first two terms of L in one line. L[:2] = ['Pancakes', 'Ham'] # What was L[:2] before? print(L) # Oh... what have we done! L[0] L[1] L[2] We can change a slice of a list with a single assignment, even when that slice does not consist of consecutive terms. Try to predict what the following commands will do. print(L) # Let's see what the list looks like before. L[::2] = ['A','B','C','D','E','F'] # What was L[::2] before this assignment? print(L) # What do you predict? Create a list L with L = [1,2,3,...,100] (all the numbers from 1 to 100). What is L[50]? Take the same list L, and extract a slice of the form [5,10,15,...,95] with a command of the form L[a:b:c]. Take the same list L, and change all the even numbers to zeros, so that L looks like [1,0,3,0,5,0,...,99,0]. Hint: You might wish to use the list [0]*50. Try the command L[-1::-1] on a list. What does it do? Can you guess before executing it? Can you understand why? In fact, strings are lists too. Try setting L = 'Hello' and the previous command. The Sieve of Eratosthenes (hereafter called "the sieve") is a very fast way of producing long lists of primes, without doing repeated primality checking. It is described in more detail in Chapter 2 of An Illustrated Theory of Numbers. The basic idea is to start with all of the natural numbers, and successively filter out, or sieve, the multiples of 2, then the multiples of 3, then the multiples of 5, etc., until only primes are left. Using list slicing, we can carry out this sieving process efficiently. And with a few more tricks we encounter here, we can carry out the Sieve very efficiently. primes = list(range(100)) # Let's start with the numbers 0...99. Now, to "filter", i.e., to say that a number is not prime, let's just change the number to the value None. primes[0] = None # Zero is not prime. primes[1] = None # One is not prime. print(primes) # What have we done? Now let's filter out the multiples of 2, starting at 4. This is the slice primes[4::2] primes[4::2] = [None] * len(primes[4::2]) # The right side is a list of Nones, of the necessary length. print(primes) # What have we done? Now we filter out the multiples of 3, starting at 9. primes[9::3] = [None] * len(primes[9::3]) # The right side is a list of Nones, of the necessary length. print(primes) # What have we done? Next the multiples of 5, starting at 25 (the first multiple of 5 greater than 5 that's left!) primes[25::5] = [None] * len(primes[25::5]) # The right side is a list of Nones, of the necessary length. print(primes) # What have we done? Finally, the multiples of 7, starting at 49 (the first multiple of 7 greater than 7 that's left!) primes[49::7] = [None] * len(primes[49::7]) # The right side is a list of Nones, of the necessary length. print(primes) # What have we done? What's left? A lot of Nones and the prime numbers up to 100. We have successfully sieved out all the nonprime numbers in the list, using just four sieving steps (and setting 0 and 1 to None manually). But there's a lot of room for improvement, from beginning to end! prime_list(n)which would output a list of primes up to nwithout so much supervision. nat the beginning. We solve these problems in the following way. Truevalue at prime indices and a Falsevalue at composite indices. This reduces the memory usage and increases the speed. whichfunction (explained soon) will make the desired list of primes after everything else is done. Here is a somewhat efficient implementation of the Sieve in Python.. p = 2 # The first prime is 2. And we start sieving by multiples of 2. while p <= sqrt(n): # We only need to sieve by p is p <= sqrt(n). if flags[p]: # We sieve the multiples of p if flags[p]=True. flags[p*p::p] = [False] * len(flags[p*p::p]) # Sieves out multiples of p, starting at p*p. p = p + 1 # Try the next value of p. return flags print(isprime_list(100)) If you look carefully at the list of booleans, you will notice a True value at the 2nd index, the 3rd index, the 5th index, the 7th index, etc.. The indices where the values are True are precisely the prime indices. Since booleans take the smallest amount of memory of any data type (one bit of memory per boolean), your computer can carry out the isprime_list(n) function even when n is very large. To be more precise, there are 8 bits in a byte. There are 1024 bytes (about 1000) in a kilobyte. There are 1024 kilobytes in a megabyte. There are 1024 megabytes in a gigabyte. Therefore, a gigabyte of memory is enough to store about 8 billion bits. That's enough to store the result of isprime_list(n) when n is about 8 billion. Not bad! And your computer probably has 4 or 8 or 12 or 16 gigabytes of memory to use. To transform the list of booleans into a list of prime numbers, we create a function called where. This function uses another Python technique called list comprehension. We discuss this technique later in this lesson, so just use the where function as a tool for now, or read about list comprehension if you're curious. def where(L): ''' Take a list of booleans as input and outputs the list of indices where True occurs. ''' return [n for n in range(len(L)) if L[n]] Combined with the isprime_list function, we can produce long lists of primes. print(where(isprime_list(100))) Let's push it a bit further. How many primes are there between 1 and 1 million? We can figure this out in three steps: But it's better to do it in two steps. Trueis 1, for the purpose of summation!) sum(isprime_list(1000000)) # The number of primes up to a million! %timeit isprime_list(10**6) # 1000 ms = 1 second. %timeit sum(isprime_list(10**6)) This isn't too bad! It takes a fraction of a second to identify the primes up to a million, and a smaller fraction of a second to count them! But we can do a little better. The first improvement is to take care of the even numbers first. If we count carefully, then the sequence 4,6,8,...,n (ending at n-1 if n is odd) has the floor of (n-2)/2 terms. Thus the line flags[4::2] = [False] * ((n-2)//2) will set all the flags to False in the sequence 4,6,8,10,... From there, we can begin sieving by odd primes starting with 3. The next improvement is that, since we've already sieved out all the even numbers (except 2), we don't have to sieve out again by even multiples. So when sieving by multiples of 3, we don't have to sieve out 9,12,15,18,21,etc.. We can just sieve out 9,15,21,etc.. When p is an odd prime, this can be taken care of with the code flags[p*p::2*p] = [False] * len(flags[p*p::2*p]).] * len(flags[p*p::2*p]) # Sieves out multiples of p, starting at p*p. p = p + 2 # Try the next value of p. Note that we can proceed only through odd p! return flags %timeit sum(isprime_list(10**6)) # How much did this speed it up? Another modest improvement is the following. In the code above, the program counts the terms in sequences like 9,15,21,27,..., in order to set them to False. This is accomplished with the length command len(flags[p*p::2*p]). But that length computation is a bit too intensive. A bit of algebraic work shows that the length is given formulaically in terms of p and n by the formula: (Here $\lfloor x \rfloor$ denotes the floor function, i.e., the result of rounding down.) Putting this into the code yields the following.] * ((n-p*p-1)//(2*p)+1) # Sieves out multiples of p, starting at p*p. p = p + 2 # Try the next value of p. return flags %timeit sum(isprime_list(10**6)) # How much did this speed it up? That should be pretty fast! It should be under 100 ms (one tenth of one second!) to determine the primes up to a million, and on a newer computer it should be under 50ms. We have gotten pretty close to the fastest algorithms that you can find in Python, without using external packages (like SAGE or sympy). See the related discussion on StackOverflow... the code in this lesson was influenced by the code presented there. Prove that the length of range(p*p, n, 2*p) equals $\lfloor \frac{n - p^2 - 1}{2p} \rfloor + 1$. A natural number $n$ is called squarefree if it has no perfect square divides $n$ except for 1. Write a function squarefree_list(n) which outputs a list of booleans: True if the index is squarefree and False if the index is not squarefree. For example, if you execute squarefree_list(12), the output should be [False, True, True, True, False, True, True, True, False, False, True, True, False]. Note that the False entries are located the indices 0, 4, 8, 9, 12. These natural numbers have perfect square divisors besides 1. Your DNA contains about 3 billion base pairs. Each "base pair" can be thought of as a letter, A, T, G, or C. How many bits would be required to store a single base pair? In other words, how might you convert a sequence of booleans into a letter A,T,G, or C? Given this, how many megabytes or gigabytes are required to store your DNA? How many people's DNA would fit on a thumb-drive? Now that we can produce a list of prime numbers quickly, we can do some data analysis: some experimental number theory to look for trends or patterns in the sequence of prime numbers. Since Euclid (about 300 BCE), we have known that there are infinitely many prime numbers. But how are they distributed? What proportion of numbers are prime, and how does this proportion change over different ranges? As theoretical questions, these belong the the field of analytic number theory. But it is hard to know what to prove without doing a bit of experimentation. And so, at least since Gauss (read Tschinkel's article about Gauss's tables) started examining his extensive tables of prime numbers, mathematicians have been carrying out experimental number theory. primes = where(isprime_list(1000000)) len(primes) # Our population size. A statistician might call it N. primes[-1] # The last prime in our list, just before one million. type(primes) # What type is this data? print(primes[:100]) # The first hundred prime numbers. To carry out serious analysis, we will use the method of list comprehension to place our population into "bins" for statistical analysis. Our first type of list comprehension has the form [x for x in LIST if CONDITION]. This produces the list of all elements of LIST satisfying CONDITION. It is similar to list slicing, except we pull out terms from the list according to whether a condition is true or false. For example, let's divide the (odd) primes into two classes. Red primes will be those of the form 4n+1. Blue primes will be those of the form 4n+3. In other words, a prime p is red if p%4 == 1 and blue if p%4 == 3. And the prime 2 is neither red nor blue. redprimes = [p for p in primes if p%4 == 1] # Note the [x for x in LIST if CONDITION] syntax. blueprimes = [p for p in primes if p%4 == 3] print('Red primes:',redprimes[:20]) # The first 20 red primes. print('Blue primes:',blueprimes[:20]) # The first 20 blue primes. print("There are {} red primes and {} blue primes, up to 1 million.".format(len(redprimes), len(blueprimes))) This is pretty close! It seems like prime numbers are about evenly distributed between red and blue. Their remainder after division by 4 is about as likely to be 1 as it is to be 3. In fact, it is proven that asymptotically the ratio between the number of red primes and the number of blue primes approaches 1. However, Chebyshev noticed a persistent slight bias towards blue primes along the way. Some of the deepest conjectures in mathematics relate to the prime counting function $\pi(x)$. Here $\pi(x)$ is the number of primes between 1 and $x$ (inclusive). So $\pi(2) = 1$ and $\pi(3) = 2$ and $\pi(4) = 2$ and $\pi(5) = 3$. One can compute a value of $\pi(x)$ pretty easily using a list comprehension. def primes_upto(x): return len([p for p in primes if p <= x]) # List comprehension recovers the primes up to x. primes_upto(1000) # There are 168 primes between 1 and 1000. Now we graph the prime counting function. To do this, we use a list comprehension, and the visualization library called matplotlib. For graphing a function, the basic idea is to create a list of x-values, a list of corresponding y-values (so the lists have to be the same length!), and then we feed the two lists into matplotlib to make the graph. We begin by loading the necessary packages. import matplotlib # A powerful graphics package. import numpy # A math package import matplotlib.pyplot as plt # A plotting subpackage in matplotlib. Now let's graph the function $y = x^2$ over the domain $-2 \leq x \leq 2$ for practice. As a first step, we use numpy's linspace function to create an evenly spaced set of 11 x-values between -2 and 2. x_values = numpy.linspace(-2,2,11) # The argument 11 is the *number* of terms, not the step size! print(x_values) type(x_values) You might notice that the format looks a bit different from a list. Indeed, if you check type(x_values), it's not a list but something else called a numpy array. Numpy is a package that excels with computations on large arrays of data. On the surface, it's not so different from a list. The numpy.linspace command is a convenient way of producing an evenly spaced list of inputs. The big difference is that operations on numpy arrays are interpreted differently than operations on ordinary Python lists. Try the two commands for comparison. [1,2,3] + [1,2,3] x_values + x_values y_values = x_values * x_values # How is multiplication interpreted on numpy arrays? print(y_values) Now we use matplotlib to create a simple line graph. %matplotlib inline plt.plot(x_values, y_values) plt.title('The graph of $y = x^2$') # The dollar signs surround the formula, in LaTeX format. plt.ylabel('y') plt.xlabel('x') plt.grid(True) plt.show() Let's analyze the graphing code a bit more. See the official pyplot tutorial for more details. %matplotlib inline plt.plot(x_values, y_values) plt.title('The graph of $y = x^2$') # The dollar signs surround the formula, in LaTeX format. plt.ylabel('y') plt.xlabel('x') plt.grid(True) plt.show() The first line contains the magic %matplotlib inline. We have seen a magic word before, in %timeit. Magic words can call another program to assist. So here, the magic %matplotlib inline calls matplotlib for help, and places the resulting figure within the notebook. The next line plt.plot(x_values, y_values) creates a plot object based on the data of the x-values and y-values. It is an abstract sort of object, behind the scenes, in a format that matplotlib understands. The following lines set the title of the plot, the axis labels, and turns a grid on. The last line plt.show renders the plot as an image in your notebook. There's an infinite variety of graphs that matplotlib can produce -- see the gallery for more! Other graphics packages include bokeh and seaborn, which extends matplotlib. x_values = numpy.linspace(0,1000000,1001) # The numpy array [0,1000,2000,3000,...,1000000] pix_values = numpy.array([primes_upto(x) for x in x_values]) # [FUNCTION(x) for x in LIST] syntax We created an array of x-values as before. But the creation of an array of y-values (here, called pix_values to stand for $\pi(x)$) probably looks strange. We have done two new things! [primes_upto(x) for x in x_values]to create a list of y-values. First, we explain the list comprehension. Instead of pulling out values of a list according to a condition, with [x for x in LIST if CONDITION], we have created a new list based on performing a function each element of a list. The syntax, used above, is [FUNCTION(x) for x in LIST]. These two methods of list comprehension can be combined, in fact. The most general syntax for list comprehension is [FUNCTION(x) for x in LIST if CONDITION]. Second, a list comprehension can be carried out on a numpy array, but the result is a plain Python list. It will be better to have a numpy array instead for what follows, so we use the numpy.array() function to convert the list into a numpy array. type(numpy.array([1,2,3])) # For example. Now we have two numpy arrays: the array of x-values and the array of y-values. We can make a plot with matplotlib. len(x_values) == len(pix_values) # These better be the same, or else matplotlib will be unhappy. %matplotlib inline plt.plot(x_values, pix_values) plt.title('The prime counting function') plt.ylabel('$\pi(x)$') plt.xlabel('x') plt.grid(True) plt.show() In this range, the prime counting function might look nearly linear. But if you look closely, there's a subtle downward bend. This is more pronounced in smaller ranges. For example, let's look at the first 10 x-values and y-values only. %matplotlib inline plt.plot(x_values[:10], pix_values[:10]) # Look closer to 0. plt.title('The prime counting function') plt.ylabel('$\pi(x)$') plt.xlabel('x') plt.grid(True) plt.show() It still looks almost linear, but there's a visible downward bend here. How can we see this bend more clearly? If the graph were linear, its equation would have the form $\pi(x) = mx$ for some fixed slope $m$ (since the graph does pass through the origin). Therefore, the quantity $\pi(x)/x$ would be constant if the graph were linear. Hence, if we graph $\pi(x) / x$ on the y-axis and $x$ on the x-axis, and the result is nonconstant, then the function $\pi(x)$ is nonlinear. m_values = pix_values[1:] / x_values[1:] # We start at 1, to avoid a division by zero error. %matplotlib inline plt.plot(x_values[1:], m_values) plt.title('The ratio $\pi(x) / x$ as $x$ varies.') plt.xlabel('x') plt.ylabel('$\pi(x) / x$') plt.grid(True) plt.show() That is certainly not constant! The decay of $\pi(x) / x$ is not so different from $1 / \log(x)$, in fact. To see this, let's overlay the graphs. We use the numpy.log function, which computes the natural logarithm of its input (and allows an entire array as input). %matplotlib inline plt.plot(x_values[1:], m_values, label='$\pi(x)/x$') # The same as the plot above. plt.plot(x_values[1:], 1 / numpy.log(x_values[1:]), label='$1 / \log(x)$') # Overlay the graph of 1 / log(x) plt.title('The ratio of $\pi(x) / x$ as $x$ varies.') plt.xlabel('x') plt.ylabel('$\pi(x) / x$') plt.grid(True) plt.legend() # Turn on the legend. plt.show() The shape of the decay of $\pi(x) / x$ is very close to $1 / \log(x)$, but it looks like there is an offset. In fact, there is, and it is pretty close to $1 / \log(x)^2$. And that is close, but again there's another little offset, this time proportional to $2 / \log(x)^3$. This goes on forever, if one wishes to approximate $\pi(x) / x$ by an "asymptotic expansion" (not a good idea, it turns out). The closeness of $\pi(x) / x$ to $1 / \log(x)$ is expressed in the prime number theorem: $$\lim_{x \rightarrow \infty} \frac{\pi(x)}{x / \log(x)} = 1.$$ %matplotlib inline plt.plot(x_values[1:], m_values * numpy.log(x_values[1:]) ) # Should get closer to 1. plt.title('The ratio $\pi(x) / (x / \log(x))$ approaches 1... slowly') plt.xlabel('x') plt.ylabel('$\pi(x) / (x / \log(x)) $') plt.ylim(0.8,1.2) plt.grid(True) plt.show() Comparing the graph to the theoretical result, we find that the ratio $\pi(x) / (x / \log(x))$ approaches $1$ (the theoretical result) but very slowly (see the graph above!). A much stronger result relates $\pi(x)$ to the "logarithmic integral" $li(x)$. The Riemann hypothesis is equivalent to the statement $$\left\vert \pi(x) - li(x) \right\vert = O(\sqrt{x} \log(x)).$$ In other words, the error if one approximates $\pi(x)$ by $li(x)$ is bounded by a constant times $\sqrt{x} \log(x)$. The logarithmic integral function isn't part of Python or numpy, but it is in the mpmath package. If you have this package installed, then you can try the following. from mpmath import li print(primes_upto(1000000)) # The number of primes up to 1 million. print(li(1000000)) # The logarithmic integral of 1 million. Not too shabby! As a last bit of data analysis, we consider the prime gaps. These are the numbers that occur as differences between consecutive primes. Since all primes except 2 are odd, all prime gaps are even except for the 1-unit gap between 2 and 3. There are many unsolved problems about prime gaps; the most famous might be that a gap of 2 occurs infinitely often (as in the gaps between 3,5 and between 11,13 and between 41,43, etc.). Once we have our data set of prime numbers, it is not hard to create a data set of prime gaps. Recall that primes is our list of prime numbers up to 1 million. len(primes) # The number of primes up to 1 million. primes_allbutlast = primes[:-1] # This excludes the last prime in the list. primes_allbutfirst = primes[1:] # This excludes the first (i.e., with index 0) prime in the list. primegaps = numpy.array(primes_allbutfirst) - numpy.array(primes_allbutlast) # Numpy is fast! print(primegaps[:100]) # The first hundred prime gaps! What have we done? It is useful to try out this method on a short list. L = [1,3,7,20] # A nice short list. print(L[:-1]) print(L[1:]) Now we have two lists of the same length. The gaps in the original list L are the differences between terms of the same index in the two new lists. One might be tempted to just subtract, e.g., with the command L[1:] - L[:-1], but subtraction is not defined for lists. Fortunately, by converting the lists to numpy arrays, we can use numpy's term-by-term subtraction operation. L[1:] - L[:-1] # This will give a TypeError. You can't subtract lists! numpy.array(L[1:]) - numpy.array(L[:-1]) # That's better. See the gaps in the list [1,3,7,20] in the output. Now let's return to our primegaps data set. It contains all the gap-sizes for primes up to 1 million. print(len(primes)) print(len(primegaps)) # This should be one less than the number of primes. As a last example of data visualization, we use matplotlib to produce a histogram of the prime gaps. max(primegaps) # The largest prime gap that appears! %matplotlib inline plt.figure(figsize=(12, 5)) # Makes the resulting figure 12in by 5in. plt.hist(primegaps, bins=range(1,115)) # Makes a histogram with one bin for each possible gap from 1 to 114. plt.ylabel('Frequency') plt.xlabel('Gap size') plt.grid(True) plt.title('The frequency of prime gaps, for primes up to 1 million') plt.show() Observe that gaps of 2 (twin primes) are pretty frequent. There are over 8000 of them, and about the same number of 4-unit gaps! But gaps of 6 are most frequent in the population, and there are some interesting peaks at 6, 12, 18, 24, 30. What else do you observe? Create functions redprimes_upto(x) and blueprimes_upto(x) which count the number of red/blue primes up to a given number x. Recall that we defined red/blue primes to be those of the form 4n+1 or 4n+3, respectively. Graph the relative proportion of red/blue primes as x varies from 1 to 1 million. E.g., are the proportions 50%/50% or 70%/30%, and how do these proportions change? Note: this is also visualized in An Illustrated Theory of Numbers and you can read an article by Rubinstein and Sarnak for more. Does there seem to be a bias in the last digits of primes? Note that, except for 2 and 5, every prime ends in 1,3,7, or 9. Note: the last digit of a number n is obtained from n % 10. Read about the "Prime Conspiracy", recently discovered by Lemke Oliver and Soundararajan. Can you detect their conspiracy in our data set of primes?
https://nbviewer.jupyter.org/github/MartyWeissman/Python-for-number-theory/blob/master/P3wNT%20Notebook%203.ipynb
CC-MAIN-2019-43
refinedweb
6,475
75.81
wcscpy, wcscpy_s From cppreference.com 1) Copies the wide string pointed to by src(including the terminating null wide character) to wide character array pointed to by dest. The behavior is undefined if the destarray is not large enough. The behavior is undefined if the strings overlap. / sizeof(wchar_t) destszis less or equal wcsnlen_s(src, destsz), in other words, truncation would occur - overlap would occur between the source and the destination strings - As with all bounds-checked functions, wcsc #include <wchar.h> #include <stdio.h> #include <locale.h> int main(void) { wchar_t *src = L"犬 means dog"; // src[0] = L'狗' ; // this would be undefined behavior wchar_t dst[wcslen(src) + 1]; // +1 to accommodate for the null terminator wcscpy(dst, src); dst[0] = L'狗'; // OK setlocale(LC_ALL, "en_US.utf8"); printf("src = %ls\ndst = %ls\n", src, dst); } Output: src = 犬 means dog dst = 狗 means dog
http://en.cppreference.com/w/c/string/wide/wcscpy
CC-MAIN-2017-26
refinedweb
147
57.37
19 May 2010 09:31 [Source: ICIS news] SHANGHAI (ICIS news)--China’s top economic planning body, the National Development and Reform Commission (NDRC), has issued an initial permit for a joint-venture refinery and petrochemical complex between Sinopec and Kuwait Petroleum Corp (KPC) in Guangdong province, a local official said on Wednesday. Under the initial permit issued on 14 May, both firms could build the mega project at a newly chosen site in ?xml:namespace> “It is just an initial permission to allow the complex to go forward, but it is still unknown when the final approval will be released,” the official told ICIS news. KPC's chief executive said in early March that approval was expected to be obtained by the end of the year, according to Reuters. The $9bn (€7.38bn) joint-venture project - which includes a In addition, the project's feasibility study and environmental impact assessment had been submitted to NDRC and the Ministry of Environmental Protection respectively, to seek their approvals, according to a newsletter published on the The project in the south of ($1 = €0.82) Please visit the complete ICIS plants and projects databas
http://www.icis.com/Articles/2010/05/19/9360655/chinas-ndrc-issues-initial-permit-for-sinopec-kpc-project.html
CC-MAIN-2014-52
refinedweb
192
53.55
In server-side Swift projects, Apple’s Swift Package Manager, or SPM, lets you manage your project dependencies, allowing you to import libraries into your applications with ease. In this tutorial, you’ll build a website to display random idioms. You’ll learn how to manage projects and dependencies, and how to read and modify Package.swift manifest files. Ready for a dive into logistics with SPM? Break a leg! Creating Packages Packages are simply repositories that contain one or more libraries and executables. Your application will have a Package.swift manifest file to manage its dependencies, and every package has its own Package.swift manifest to handle any dependencies that it may have. The manifest files are also written in Swift, as implied by the file extension! A manifest file describes the package; it contains a list of dependencies and targets. A target is the specification of a single module and its dependencies. You can compile each target that contains a main.swift to an executable. You might have seen modules in Xcode before. Your app itself is an executable module, and it has dependencies that, in turn, are also modules. With SPM, you can create packages right from Terminal. SPM uses the directory name as your project name when setting up your application. Getting Started First, create a directory with the desired project name and enter that directory: mkdir Website cd Website To create an executable project, run the following command: swift package init --type=executable Note: If you wanted to create a library instead, you would omit the type parameter and simply swift package init instead. You should see the following output as the system creates all the boilerplate for an SPM project: That’s it; you’ve created your own package! Adding Dependencies The next step in creating a project is to add its dependencies. To do that, open the Package.swift manifest file inside the directory where you created your project. At the top of the file is the Swift tools version. You should not remove the generated tools version comment; it’s read by SPM to understand how to interpret the manifest. Each package has a name and a list of targets. Your executable has a regular target and a test target. The regular target is your executable or library, whereas the test target is a test suite. Your Package.swift file should look as follows: // swift-tools-version:4.2 import PackageDescription let package = Package( name: "Website", dependencies: [ ], targets: [ .target( name: "Website", dependencies: []), .testTarget( name: "WebsiteTests", dependencies: ["Website"]), ] ) In this tutorial, you’ll add the WebsiteBuilder library as a dependency to your application. This library was created specially for this tutorial. Finding Dependency URLs To add a dependency, you need three pieces of information: the URL, the version number and the name. To get the URL, open the GitHub link to the WebsiteBuilder library and look for a green button named Clone or download. Click that button and look for Clone with HTTPS. If you don’t see this, you should see the text Use HTTPS instead. Click Use HTTPS to toggle to the HTTPS link, which you can then copy using the clipboard button. The package version can usually be found in the README of the project. But if you want an older version of the package, or need to find the version yourself, you can find it in the releases tab of the project. For this project, you are going to start with version 1.0.0. The package name may be in the README, but you can always find it in the Package.swift file for the dependency. The name of this dependency is WebsiteBuilder. In your app’s Package.swift file, you’ll find an array of dependencies. There is one example dependency there, but it’s commented out as it’s only for reference purposes. Add the following line to your manifest within the dependencies array. .package(url: "", from: "1.0.0") This references the URL and the version number from the GitHub repository. Next, add the package name – WebsiteBuilder – to the list of named dependencies in your Website target: .target( name: "Website", dependencies: ["WebsiteBuilder"]), Save your file and go back to Terminal. That takes care of your dependencies. But dependencies also have properties, which you’ll learn about next. Editing Dependency Properties You’ve just added your first SPM dependency in it’s simplest form, but what happens when you want some more specificity into the version of the dependency your app requires? SPM lets you specify version requirements in a very granular way, providing great control over the exact version, or even branch, of the required dependency. Note: These are examples to show how you can specify different versions. They use truncated URLs and imaginary version numbers. The following code specifies any version of the dependency, starting at 1.1.3 and less than 2.0.0: .package(url: "", from: "1.1.3") If you want specify a minimum and maximum version for one dependency, you can use a range: .package(url: "", "1.1.0"..."1.2.1") Use the following if you’re interested in an exact version of a dependency: .package(url: "", .exact("1.2.3")) All of these version-specific variations also support beta-versioning. For example: .package(url: "", from: "1.1.3-beta.4") You can also lock the dependency to a specific branch in git. This is useful if a feature or fix is not yet released: .package(url: "", .branch("bugfix/issue-121")) Finally, you can specify a commit by its hash: .package(url: "", .revision("04136e97a73b826528dd077c3ebab07d9f8f48e2")) Integrating With Xcode Now that your project is set up, you’re ready to generate an Xcode project. Execute the following command in Terminal to do so: swift package generate-xcodeproj This will download the dependencies and create an Xcode project — Website.xcodeproj. Note: If you have used Swift Package Manager before, you may notice that we didnR17;t ask you to use swift build. This is because the Xcode project generation command does this for you, as well as resolve your dependency tree before building your project. Later on, you’ll get a hint of how swift build and swift package update work on their own! You should output similar to the following: Finally, open the project. Protip: you can open it quickly from Terminal by executing the following command: open ./Website.xcodeproj Or, by using xed, which will open the project in the current folder: xed . Xcode may select an iOS device or simulator as the targeted device, so make sure to switch to My Mac. Build and run the project in Xcode. This will compile the project, start the project, print a message in the console and exit. Open main.swift in Xcode and replace its contents with the following code: import NIO import WebsiteBuilder /// All idioms the app can respond with let idioms = [ "A blessing in disguise", "Better late than never", "Bite the bullet", "Break a leg", "Cutting corners", "Get your act together", "That's the last straw", "You can say that again" ] /// Responds to the request with a random idiom chosen from the list above struct IdiomResponder: HTTPResponder { func respond(to request: HTTPRequest) -> EventLoopFuture<HTTPResponse> { guard let randomIdiom = idioms.randomElement() else { return request.eventLoop.newFailedFuture(error: Error.noIdiomsAvailable) } let response = HTTPResponse(status: .ok, body: HTTPBody(text: randomIdiom)) return request.eventLoop.newSucceededFuture(result: response) } enum Error: Swift.Error { /// This error occurs if the idiom list is empty case noIdiomsAvailable } } /// Creates a new website responding with the IdiomResponder let website = Website(responder: IdiomResponder()) /// Runs the website at the default port try website.run() In this piece of code, you respond to an incoming network with a random idiom from the provided list using SwiftNIO. While SwiftNIO itself is out-of-scope for this tutorial, you can learn more about it in SwiftNIO: A simple guide to async on the server. Build and run the application again using the Run button in Xcode. Oh no – it doesn’t work: Fatal error: Error raised at top level: bind(descriptor:ptr:bytes:) failed: Permission denied (errno: 13) Uh-oh! What kind of bug is this? This is a deliberate error in this tutorial, and may even be a blessing in disguise. This means that the application attempted to use a port that is already in use, or one that you do not have permission to use. In this case, it’s a permission problem. The library uses port 80, which is only usable by the super user. Managing Dependencies In this project, you would be unable to run the application without switching to the super user. For development purposes, you’ll commonly use a port different than 80. You’re usually free to use any port above port 1024 that is not already in use. Usually, you will specify a dependency using from to set a minimum version, so that SPM can download updates of newer version of the package. But in this scenario, version 1.0.1 has the port permission problem, and the last known working version is 1.0.0. Looks like you’ll need to go back to 1.0.0. Edit Package.swift and replace the dependency with the following to pin the dependency to exactly version 1.0.0: .package(url: "", .exact("1.0.0")) After changing the manifest, your dependencies won’t be updated automatically. To update them, you could just update your Xcode project again, but this time, run the following command in your project’s directory from Terminal: swift package update This command, on its own, will look for newer or different versions of your dependencies and download them as required. You are working in Xcode to update this project, so you’ll need to regenerate your Xcode project after running this command. This is necessary because dependencies can add and remove files. Execute the following command to regenerate your project: swift package generate-xcodeproj Troubleshooting Dependencies Some versions of Xcode will prompt you with the following: Click Revert to reload the project from the disk. And if Xcode will not compile your application after this, close the window and open the project again. This time when you build and run in Xcode, you will see Server started and listening in the console. Open a web browser, and go to localhost:8080 to check out what you made, refreshing a few times as you go. Now you know how to run an application using Xcode. So far, so good! Next, you’ll learn more about SPM and running swift from the terminal. Stop the application in Xcode if it is running, and switch back to Terminal. Running From the Terminal Now that you’ve learned how to build and run applications on macOS, you’re all set to start developing. However, server-side Swift is commonly run on Linux servers. So you’ll need to know how to compile and run applications on Linux, too. On macOS, as long as you have Xcode 10.1 or later installed, you’re all set. If you are working in a Linux environment, you need to set up Swift as described on the Swift Download page. There are three primary commands that you’ll work with; the most common command is swift run. This will build your application and run the resulting executable. If there are multiple executable targets, you simply add the target name to the command: swift run Website The first time you run this command, SPM compiles everything first, which might take a bit of extra time, but it will compile much faster in subsequent compiles. Once you see the Server started and listening message, you’ll know it’s up and running. To stop the server, press Control + C. Another common task is running unit tests. Don’t run this for now, but the following command is the one you’ll use for running the unit tests of your package: swift test Note: Do not run swift test as it will run the server in the background and never stop it. Testing server-side Swift projects is outside the scope of this tutorial, so while it is important to know this command, the project is not set up for testing. Finally, use the following command to build your executable without running it: swift build Build Configurations The above commands use the debug configuration by default. There are more configurations available; the most common one is release. The debug configuration compiles much faster than release, but compiling a binary with the release configuration results in increased optimization. Add --configuration release to your command to change the configuration to release, and execute it: swift run --configuration release This command starts the server. Navigate to in your browser. If you see an idiom, your application is working! However, don’t call it a day just yet. There’s still a problem to be solved! Editing the Library In many development scenarios, another application will be using port 8080. You’ll need to move one of the applications to another port by assigning another unused port. The imported library doesn’t support this, but you can implement it yourself! The first step is to put the package in editable mode. Press Control + C to stop the server. Then, run the following command: swift package edit WebsiteBuilder This moves WebsiteBuilder into the Dependencies folder in your project. SPM will not update or change the dependency. Before you can edit the package, regenerate the Xcode project. Tip: To quickly recall commands in Terminal, you can press the up-arrow key repeatedly in Terminal. Do this until you get back to the swift package generate-xcodeproj line, then press Return to run it again and regenerate the project. Within the Dependencies group in Xcode’s Project navigator, you’ll find a list of all dependency sources. Open Website.swift in the WebsiteBuilder dependency folder. Remove the following line from the run() method: let port = 8080 Also change the run() method’s signature to the following: public func run(port: Int) throws { Now you’ll need to specify your port. Open your own application’s main.swift file. Change the last line in that file, the one that actually runs the website, and modify the port number: try website.run(port: 8123) To complete this tutorial, run the application using the release configuration in Terminal with your swift run --configuration release command. Once it’s started, open the website in a browser at. Do you see an idiom? If so, you’re done! Time flies when you’re having fun, doesn’t it? Where to Go From Here? You can download the completed version of this project using the Download Materials button at the top or bottom of this screen. - One of the most important libraries in server-side Swift, SwiftNIO, is covered in the SwiftNIO tutorial, also mentioned earlier in this tutorial. - If you’re interested in learning about API development, look into Kitura and Vapor. Getting Started with Vapor and Getting Started with Kitura are two tutorials that will teach you the basics. - In Vapor vs. Kitura, the two server-side Swift frameworks go head to head. If you’re not sure which to use, read that and make your decision! Questions or comments? Leave them in the forum section below! .
https://linksoftvn.com/an-introduction-to-swift-package-manager/
CC-MAIN-2019-18
refinedweb
2,560
65.32
since there is no support for autologin using kde-keyring, gnome-keyring is the only option. most build time switcher are documented here (aka read the f****** code) Search Criteria Package Details: retroshare 0.6.2-1 Dependencies (14) - curl (curl-git, curl-http2-git) -) - libmicrohttpd (libmicrohttpd-git) - libupnp - libxslt - libxss - opencv (opencv-cuda-git, 2017-06-01 19:36 since there is no support for autologin using kde-keyring, gnome-keyring is the only option. ShalokShalom commented on 2017-06-01 18:02 Why is libgnome-keyring the package for "autologin"? I mean, is this the only option in KDE systems as well? And how do i trigger these "build triggers"? They seem new to me, i never saw such ones before. buttcake commented on 2017-03-13 14:34 Any news on when is this getting into the repos ? sehraf commented on 2016-09-04 16:16 I've already updated the PKGBUILD and only need to push it but i currently don't have access to the computer. Expect the update on monday afternoon CET. sehraf commented on 2016-07-04 14:27 @herzmeister ask upstream or use the -git version. This is not the place to ask for such update... herzmeister commented on 2016-07-04 11:39 an update would be nice, because apparently a recent commit in the last days might fix a connection issue that i've been having for the last few months aereaux commented on 2016-06-18 18:57 When building the package with this new patch, I get the following error: ==> Starting prepare()... ../aca88308eae16ab67627593c0df2fce7beb02e89.patch:115: trailing whitespace. const float Node::MASS_FACTOR = 10 ; ../aca88308eae16ab67627593c0df2fce7beb02e89.patch:116: trailing whitespace. const float Node::FRICTION_FACTOR = 10.8f ; ../aca88308eae16ab67627593c0df2fce7beb02e89.patch:117: trailing whitespace. const float Node::REPULSION_FACTOR = 4; ../aca88308eae16ab67627593c0df2fce7beb02e89.patch:118: trailing whitespace. const float Node::NODE_DISTANCE = 130.0f ; ../aca88308eae16ab67627593c0df2fce7beb02e89.patch:119: trailing whitespace. error: patch failed: retroshare-gui/src/gui/elastic/node.cpp:87 error: retroshare-gui/src/gui/elastic/node.cpp: patch does not apply error: patch failed: retroshare-gui/src/gui/elastic/node.h:118 error: retroshare-gui/src/gui/elastic/node.h: patch does not apply error: patch failed: retroshare-gui/src/gui/gxsforums/GxsForumThreadWidget.cpp:1565 error: retroshare-gui/src/gui/gxsforums/GxsForumThreadWidget.cpp: patch does not apply ==> ERROR: A failure occurred in prepare(). Aborting... Adding the option --ignore-space-change to the git apply fixes it, but I'm not sure what the best way to fix this error is, or why it's happening to me (if it isn't happening to anyone else). herzmeister commented on 2016-06-14 11:22 indeed, is working now, thanks sehraf commented on 2016-06-14 07:26 fixed once and for all sehraf commented on 2016-06-12 20:02 is this (again) related to C standards? Does anybody know how to fix this (once and for all)? This is fix upstream for a long time now - maybe there will be a release soon... herzmeister commented on 2016-06-12 13:29 Currently getting an error (again): In file included from dbase/fimonitor.cc:29:0: ./rsserver/p3face.h: At global scope: .:1740: recipe for target 'temp/linux-g++/obj/fimonitor.o' failed make[1]: *** [temp/linux-g++/obj/fimonitor.o] Error 1 make[1]: Leaving directory '/tmp/yaourt-tmp-mep/aur-retroshare/src/RetroShare-0.6.0/libretroshare/src' Makefile:99: recipe for target 'sub-libretroshare-src-libretroshare-pro-make_first' failed make: *** [sub-libretroshare-src-libretroshare-pro-make_first] Error 2 ==> ERROR: A failure occurred in build(). Aborting... ==> ERROR: Makepkg was unable to build retroshare. sehraf commented on 2016-04-18 09:25 should be fixed now: sehraf commented on 2015-07-12 18:13 Note: the webfiles for the webui are now installed to /usr/share/RetroShare06/webui because this is where the GUI expects them to be. sehraf commented on 2015-06-29 11:37 I've adopted the packet and updated it to 0.6 RC2 since RS 0.5 looks pretty dead by now some notes: - VOIP is currently broken due to a bug in speex - ssh/rpc interface was replaced by a WIP json interface - webui files are installed to /usr/share/RetroShare/webfiles/ stqn commented on 2015-06-10 16:00 I won’t be using Arch Linux anymore so I’m disowning this. ayjanu commented on 2015-03-29 21:05 Thank you. stqn commented on 2015-03-29 20:45 Right, it seems that it is a bug in speex 1.2rc2. As a workaround, if you don’t care about VOIP you can set _build_voip=false in the PKGBUILD. See for more info and other potential workarounds. Not sure how to fix it properly myself. Someone should report it to the speex project. Unfortunately they don’t seem to have a bugtracker. ayjanu commented on 2015-03-29 19:54 Attempting to build RetroShare today results in a build error. Not knowing much about compiling errors yet, I have included as much of the text that seemed relevant to the problem. In file included from /usr/include/speex/speexdsp_types.h:122:0, from /usr/include/speex/speex_preprocess.h:46, from gui/SpeexProcessor.h:19, from gui/AudioInputConfig.h:40, from gui/AudioInputConfig.cpp:37: /usr/include/speex/speexdsp_config_types.h:13:9: error: ‘uint16_t’ does not name a type typedef uint16_t spx_uint16_t; ^ /usr/include/speex/speexdsp_config_types.h:15:9: error: ‘uint32_t’ does not name a type typedef uint32_t spx_uint32_t; ^ In file included from gui/SpeexProcessor.h:21:0, from gui/AudioInputConfig.h:40, from gui/AudioInputConfig.cpp:37: /usr/include/speex/speex_jitter.h:62:4: error: ‘spx_uint32_t’ does not name a type spx_uint32_t len; /**< Length of the packet in bytes */ ^ /usr/include/speex/speex_jitter.h:63:4: error: ‘spx_uint32_t’ does not name a type spx_uint32_t timestamp; /**< Timestamp for the packet */ ^ /usr/include/speex/speex_jitter.h:64:4: error: ‘spx_uint32_t’ does not name a type spx_uint32_t span; /**< Time covered by the packet (same units as timestamp) */ ^ /usr/include/speex/speex_jitter.h:65:4: error: ‘spx_uint16_t’ does not name a type spx_uint16_t sequence; /**< RTP Sequence number if available (0 otherwise) */ ^ /usr/include/speex/speex_jitter.h:66:4: error: ‘spx_uint32_t’ does not name a type spx_uint32_t user_data; /**< Put whatever data you like here (it's ignored by the jitter buffer) */ ^ /usr/include/speex/speex_jitter.h:178:57: error: ‘spx_uint32_t’ has not been declared void jitter_buffer_remaining_span(JitterBuffer *jitter, spx_uint32_t rem); ^ Makefile:376: recipe for target 'AudioInputConfig.o' failed make: *** [AudioInputConfig.o] Error 1 ==> ERROR: A failure occurred in build(). Aborting... ==> ERROR: Makepkg was unable to build retroshare. stqn commented on 2014-04-10 14:22 Because of the openssl heartbleed leak, it’s important that you update your Arch system ASAP and restart Retroshare. You should have openssl 1.0.1.g. stqn commented on 2014-04-09 21:33 What? libssh exists. Are you getting an error? rakoo commented on 2014-04-09 20:40 libssh doesn't exist for the nogui client, maybe use libssh-git ? BrunoSpy commented on 2014-03-22 14:34 You can add armv6h to the list of architecture : tested and approved ! stqn commented on 2014-01-29 22:34 Updated to 0.5.5c. Thanks BrunoSpy. BrunoSpy commented on 2014-01-29 19:36 New version available : msx commented on 2013-11-11 05:06 Thank you very much for keeping this nice app updated! stqn commented on 2013-10-31 20:28 Updated to 0.5.5b! The detailed changelog file hasn’t been updated since 0.5.5a but the post above should list the most significant changes. demaio commented on 2013-10-31 14:49 I flagged it as out of date because I read about the new release on their blog at and had seen the download link at the end of the blog post. But you are right, the official download page does not list it, I just had not noticed because of the links in the blog post. My suggestion is to wait until they have updated the download page and provide a source package. Many thanks for your efforts. stqn commented on 2013-10-30 19:24 Someone flagged this as out of date. 0.5.5b files have indeed been uploaded to sourceforge ( ) but there is no source archive and the official download page ( ) still lists 0.5.5a. The Windows, OSX and Debian releases use 3 different SVN revisions. What do you suggest? stqn commented on 2013-10-02 09:19 I updated the PKGBUILD yesterday for the new source archive. Nothing has changed (no need to reinstall), but if you get the new PKGBUILD you may have to delete your old RetroShare-v0.5.5a.zip file. wookietreiber commented on 2013-10-02 06:30 ==> Validating source files with sha256sums... RetroShare-v0.5.5a.zip ... FAILED retroshare.install ... Passed retroshare.desktop ... Passed wookietreiber commented on 2013-10-02 06:30 your checksums don't match! stqn commented on 2013-09-12 00:48 Updated to v0.5.5a. Changelog: silvernode commented on 2013-06-18 06:49 I just discovered Retroshare. Thank you for picking up and maintaining this package. Keep up the good work, I love Retroshare! stqn commented on 2013-04-06 19:57 Fixed… Apparently the $srcdir variable is no longer available outside of the build() and package() functions. stqn commented on 2013-04-06 16:43 I can confirm that (with the new pacman/makepkg 4.1.0). I’ll try to fix it but couldn’t find any documentation about the breaking change. lothar_m commented on 2013-04-06 15:05 there seems to be an issue with the PKGBUILD. When i try to compile, it complains about missing src directories for openpgpsdk. To correct the problem i had to edit the PKGBUILD and mannually set the srcdir variable. Does anyone else suffers this problem? zarel commented on 2013-04-05 09:25 The source tarball have been renamed, now it's located at It has the same hash as before, only the name has changed. stqn commented on 2013-03-24 15:31 Updated to 0.5.4e. Changelog: Edit the PKGBUILD if you want to build retroshare-nogui. It adds the following deps: libssh protobuf. All plugins are built by default, which add the following deps: speex curl libxslt. You can disable each plugin individually in the PKGBUILD. stqn commented on 2013-03-23 21:38 Dear BrunoSpy, I know that RS 0.5.4e is out for some platforms (Windows and OSX), but the source package is still of v0.5.4d. Thus this package can not be updated yet. stqn commented on 2013-03-01 19:34 Fixed qmake-qt4 name. Now requires the new qt4 package. stqn commented on 2013-03-01 02:27 PKGBUILD update: - should still work when Qt5 hits the repos - removed extraneous .svn directories from the skins directory - you can choose to build and install either plugin independantly now - the speex dependency is added automatically if you choose to build the VOIP plugin. stqn commented on 2012-12-19 17:44 Updated to 0.5.4d. stqn commented on 2012-11-29 22:40 Enabled VOIP and LinksCloud plugins by default. The VOIP plugin requires speex, and can be used from the private chat windows. You’ll have to edit the PKGBUILD if you don’t want the plugins (set _USE_PLUGINS to false and remove speex from the dependencies.) stqn commented on 2012-11-22 21:31 Updated to 0.5.4c. Doesn’t install to /opt anymore. Changelog: stqn commented on 2012-09-26 20:29 Updated to 0.5.4b. Contains (experimental) changes to make downloads a bit faster. stqn commented on 2012-09-23 15:17 Updated to 0.5.4a. gpgme no longer a dependency. RS now handles its own keyring and keys are stored in .retroshare, not .gnupg anymore. The transfer will be made when you launch 0.5.4a the first time. It is now possible to have RS respect your theme if you select the “skin with no name” in the Appearance settings. stqn commented on 2012-07-13 20:42 malevolent, no, gpa is not needed. It’s just a GUI for GPG, so it has nothing to do with RS. Corrupted certificates can happen if you use Chrome to copy them. malevolent commented on 2012-07-13 12:37 ATTENTION: you must install gpa in order to make work certificates within this application. Without that, your peers will see your GPG is corrupted. Anonymous comment on 2012-07-05 21:35 plugins would be nice to test voip :) stqn commented on 2012-05-31 20:28 Updated to 0.5.3c. Faster multi-source downloads, ability to mute annoying people in the chat lobbies, and a right-click menu to paste one's certificate are the changes that I can remember. stqn commented on 2012-04-07 14:30 @cortuly: yes, as the note says, plugins compilation doesn’t work. I don’t need that and no-one requested it (I think there’s no interesting and working plugin yet.) Anonymous comment on 2012-04-07 08:58 Yes it works now thank you. When I set plugins to TRUE i get this btw. Not important for me but maybe you should know that there seems to be something wrong. ==> Entering fakeroot environment... ==> Starting package()... ==> Install files to fakeroot-environment install: cannot stat ‘/tmp/yaourt-tmp-fuly/aur-retroshare/src/trunk/plugins/bin/libcalendar_plugin.so’: No such file or directory nipsky commented on 2012-04-07 08:51 It works now, thanks! stqn commented on 2012-04-07 00:53 Fixed. Please try the new tarball. stqn commented on 2012-04-06 16:30 Must be caused by some recent SDK (libc/c++) update. I'll update my Arch and see what I can do as soon as my backup is finished. nipsky commented on 2012-04-06 15:23 Compilation fails for me with (same thing on a 32bit machine): 4 -D_FORTIFY_SOURCE=2 -fPIC -Wall -W -I/usr/share/qt/mkspecs/linux-g++-64 -I. -I. -o temp/linux-g++-64/obj/udpbitdht.o udp/udpbitdht.cc udp/udpbitdht.cc: In member function 'virtual void UdpBitDht::run()': udp/udpbitdht.cc:322:26: error: 'usleep' was not declared in this scope udp/udpbitdht.cc:329:10: error: 'sleep' was not declared in this scope make: *** [temp/linux-g++-64/obj/udpbitdht.o] Error 1 Xyne commented on 2012-03-06 16:37 Thanks! stqn commented on 2012-03-06 11:01 Made suggested improvements. No need to update if you're already running 0.5.3b. Xyne commented on 2012-03-04 20:13 Hi, I've made some changes to the PKGBUILD and local source files. You can find the updated source archive here: The changes include: * replaced $* with "$@" in the launcher script (this ensure proper word expansion of passed arguments) * replace hackish if-block conditions in install script and PKGBUILD with proper double-bracketed conditions * added missing quotes to $srcdir and other variables in the PKGBUILD I forgot to bump the pkgrel variable. Thanks for maintaining this package. Anonymous comment on 2012-03-03 01:12 i don't mind rebuilding, as long as i can set up a server to relay with afterwards. stqn commented on 2012-03-03 01:07 Ah ah Giggaflop, I've been working on it and by mistake uploaded a PKGBUILD that builds retroshare-nogui. (But doesn't install it!) You should get the latest PKGBUILD (-4), set "_USE_NOGUI" to "TRUE", and build (maybe with "makepkg -ef" to avoid rebuilding everything else.) Anonymous comment on 2012-03-03 00:38 wait who just fixed that? i swear i just did the exact same thing, but the version increased O_O did i just contribute? Anonymous comment on 2012-03-02 23:16 How do i get retroshare-nogui with this package? stqn commented on 2012-03-02 00:45 Thanks fsck, it should be fixed now (bdboot.txt copied to /usr/share/RetroShare/, then retroshare itself should copy it to ~/.retroshare at startup). Anonymous comment on 2012-03-01 21:19 bdboot.txt doesn't seem to be copying to ~~/.retroshare/<peerID>/ correctly, and it doesn't seem to be in the package that's built. I've been grabbing it from the source tarball "trunk/libbitdht/src/example/bdboot.txt". This completely prevents DHT from functioning, and seems to make connecting to new friends impossible. Also using this software on Ubuntu and from the repository the developers run and on Windows without this issue, so I doubt it's an upstream problem. stqn commented on 2012-02-20 19:47 Updated to 0.5.3b. @jonas: thanks for the confirmation! Anonymous comment on 2012-02-14 01:19 @stqn, It worked for me, thanks. stqn commented on 2012-02-09 03:33 Updated to 0.5.3a. Note that there might be other "0.5.3a" releases in the coming days... This package works with today's source archive! I haven't actually tried installing and running this package because I'm already running the svn version, so tell me if anything's wrong. At least it builds ;). stqn commented on 2012-02-08 03:03 If someone's feeling adventurous, I have uploaded a retroshare-svn package to the AUR :). There has been many improvements since 0.5.2a, including better connectivity and chat rooms. 0.5.3a should be available in the near future, though. Anonymous comment on 2012-02-03 17:11 thanks, stqn. stqn commented on 2012-01-14 14:26 @feilen, I'm building from SVN and -lixml was already included (in revision 4677), that's why I didn't need to add it. feilen commented on 2012-01-14 03:05 @stqn I also needed -lixml stqn commented on 2012-01-12 15:22 @too, try this: - makepkg --nobuild - edit retroshare-gui/src/RetroShare.pro and add "-ldl -lcrypto -lX11" to the linux "LIBS += ..." line (line 40). - makepkg --noextract Anonymous comment on 2012-01-12 12:42 Also have the same issue as BlackLotus89 but i'm completely new to linux/arch so i don't know what to do now... stqn commented on 2012-01-08 14:34 @BlackLotus89, I've got the same error when building from SVN (rev. 4762). I think it's caused by a change in openssl 1.0.0.f, but I haven't found what. BlackLotus89 commented on 2012-01-08 13:54 Failed to build /usr/bin/ld: ../../libretroshare/src/lib/libretroshare.a(authssl.o): undefined reference to symbol 'RAND_seed' /usr/bin/ld: note: 'RAND_seed' is defined in DSO /usr/lib/libcrypto.so.1.0.0 so try adding it to the linker command line /usr/lib/libcrypto.so.1.0.0: could not read symbols: Invalid operation Didn't debug it stqn commented on 2011-10-13 06:12 It's useless to copy libbitdht.a and libretroshare.a. Anonymous comment on 2011-08-20 20:32 Updated to the latest version and it all looks to work. Tristero: If you end up finding the time and want to maintain the package again, please get in touch. Anonymous comment on 2011-08-15 20:39 Sorry, I have to orphan this PKGBUILD. I would really like to maintain it, but at least for the next months, I definitively won't have enough spare time. I would like to thank all people who made suggestions for improvements of the build or pointed me to problems. Anonymous comment on 2011-07-14 11:33 Thanks for this suggestion. I will respect that when providing the PKGBUILD for the next version. stqn commented on 2011-07-07 20:57 Also I noticed the languages and Qt style sheets are missing. I think it would be better to install RetroShare to /opt/retroshare/ with the "lang" and "qss" directories and bdboot.txt at least (and maybe also "license" and "sounds".) Then /usr/bin/retroshare could be a script that runs cd /opt/retroshare && ./RetroShare. stqn commented on 2011-07-07 14:39 This is probably an upstream problem, but the bdboot.txt file needed to bootstrap the DHT doesn't seem to be included in the package. The only (Unix) script that mentions it is "makeSourcePackage.sh" and contains this line: cp retroshare-0.5/src/libbitdht/bitdht/bdboot.txt Seems like they forgot the destination directory :). Copying this file (trunk/libbitdht/src/bitdht/bdboot.txt) to ~/.retroshare/<SSLID>/ was needed to make the DHT work for me. Anonymous comment on 2011-07-06 18:39 Updated to 0.5.1d. Anonymous comment on 2011-06-02 12:17 Updated to 0.5.1c. If you like to compile the plugins or retroshare-nogui into the package, you have to edit lines 23 and 27 of the PKGBUILD according to the comments. Anonymous comment on 2011-05-27 11:42 Retroshare 0.5.1c is out Can you update, please ? Anonymous comment on 2011-03-10 17:59 Version 0.5.1b-2: added libgnome-keyring, mesa, libxss to dependency array Anonymous comment on 2011-03-10 14:19 extra/mesa and extra/libxss are required to build retroshare. raw commented on 2011-03-10 09:02 libgnome-keyring (from extra) is required to build retroshare. Please add this to (build?) dependencies. without that, it is missing gnome-keyring.h file. Anonymous comment on 2011-03-07 16:09 Version 0.5.1b has a new dependency: which is not present in AUR currently. The RetroShare-PKGBUILD just compiles this lib from the RS-tarball where it is included. Perhaps it makes sense to create a separate AUR-package for libbitdht? Anonymous comment on 2011-03-07 16:03 Updated from 0.5.0g-2 to 0.5.1b-1. - I had to remove the optional experimental support for the plugins and other features (blogs. etc.) because I did not get that part of code to compile. Obviously, those part of the code are unfinished and not supposed to be compiled in a release version (it seems, parts of the code reference headers which are not present in the tarball). Anonymous comment on 2011-01-03 19:10 Updated from 0.5.0g-1 to 0.5.0g-2. - Fixed build error in UPnPBase.h by changing #include statement. Sorry for latency! drdrewdown commented on 2010-11-24 05:06 what file & where does that #include <string.h> need to be? help a n00b out!?! Anonymous comment on 2010-11-17 19:01 You need to add #include <string.h> to the file. Anonymous comment on 2010-11-17 18:44 I can confirm this. I added the header and will provide patches when the build suceeds. marenz commented on 2010-11-17 17:50 fails to compile: upnp/UPnPBase.h:466:38: Fehler: »memcpy« wurde in diesem Gültigkeitsbereich nicht definiert (not defined in this scope). Sounds like a header is missing. Anonymous comment on 2010-08-10 17:30 Updated from 0.5.0-1 to 0.5.0g-1. - (Mere coincidence. ;-) Won't manage to keep track with the smaller updates.) Anonymous comment on 2010-04-26 15:52 *** PLEASE READ THIS BEFORE SETTING THE OUT-OF-DATE-FLAG ON THIS PKGBUILD *** This PKGBUILD is intended to point to the *CURRENT STABLE RELEASE* of retroshare. It will not be automatically upgraded to point to new "alpha" versions and I do not regard it as out-of-date unless there is a new non-alpha stable release of retroshare. The current stable release of retroshare on 26 April 2010 is version 0.5.0 as it is pointed out here: hence I see no pending upgrade and do not have heard about serious bugs which require an upgrade. (You may prove me wrong of course.) If you experience problems raised by the PKGBUILD itself then please report it and of course I will do my best to fix the problem as soon as possible. I will unflag this PKGBUILD in the hope that it will remain unflagged till the next stable version is released or other important reasons for an upgrade occur. Anonymous comment on 2010-04-17 09:18 Version 0.5.0 - 1 : * Does not contain retroshare-nogui due to compile errors that are to be fixed. * To compile with unreleased features like plugins, blogs etc. modify line 25 of the PKGBUILD. * To compile with a openssl version < 1.0.0 read the comments in the PKGBUILD.
https://aur.archlinux.org/packages/retroshare/?comments=all
CC-MAIN-2017-34
refinedweb
4,095
67.65
might help you for setting the correct parameters of LV_FINDINFO-structure: int CMyGridList::FindItemData( // --- In : dwItemData : Original data to search for // --- Out : // --- Returns : The index of the item that has this original data associated with it // --- Effect : This functions calls the underlying window procedure directly // instead of sending a message { ASSERT(::IsWindow(m_hWnd)) LV_FINDINFO lvfi; memset(&lvfi, 0, sizeof(LV_FINDINFO)); lvfi.flags = LVFI_PARAM; lvfi.lParam = (LPARAM)dwItemData; return (int) DefWindowProc(LVM_FINDITEM } I didn't know, that you have such a lot of items. Bye, atari Bye, atari Maybe you could use GetItemText() instead of FindItem() something like this: CString s,search_string="Whatever you want to search"; for (int i=0;i<yourlistCtrl.GetItem { s=GetItemText(i,column); if (s==search_string) { AfxMessageBox("I have found it"); break; } } But some other examples you find in the sorting-section of the above web-site. Bye, atari Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface. I am trying to find any MFC methods that will do the same job ( eg. FindItem ) but the (speed) performance must not be compromised.... :) Any ideas? Thanks a lot, guys David Chong I have looked at the LV_FINDINFO structure but I am not sure what values to set. If I have not forgotten, there is a index and a subindex field of the structure... can u give me a simple example ( take the second column to be searched )?? Thanks.. right now I am setting it to LVFI_PARTIAL which is no good cause it searches the first column. David Chong Thanks for your help. I will go through your example ( and try to implement it )... anyway, I have tested the first solution u gave me and the speed is acceptable , the only worse thing is that my sorting ( on the second column ) using a custom function (recurvise sorting) is taking bout 4 seconds while the searching is less than or about a second... so the problem here can be considered solved... the challenge now is to reduce my sorting time... !!! Bye.. :) Have a nice day David Chong
https://www.experts-exchange.com/questions/10064671/How-do-u-find-string-in-a-CListCtrl.html
CC-MAIN-2018-22
refinedweb
368
62.48
Curl Syntax in Elasticsearch with Examples Curl syntax We use HTTP requests to talk to ElasticSearch. A HTTP request is made up of several components such as the URL to make the request to, HTTP verbs (GET, POST etc) and headers. In order to succinctly and consistently describe HTTP requests the ElasticSearch documentation uses cURL command line syntax. This is also the standard practice to describe requests made to ElasticSearch within the user community. An example HTTP request using cURL syntax looks like this: A simple search request using cURL. curl -XPOST "" -d' { "query": { "match_all": {} } }' The above snippet, when executed in a console, runs the curl program with three arguments. The first argument, -XPOST, means that the request that cURL makes should use the POST HTTP verb. The second argument, “” is the URL that the request should be made to. The final argument, -d'{…}’ uses the -d flag which instructs cURL to send what follows the flag as the HTTP POST data. Whenever you see a request formatted using cURL syntax, you can either: - Copy it and execute it in a console (given that you have cURL installed). - Read it and translate it into whatever HTTP client that you are using. - Paste it into the left part of Sense. When using the last option, pasting cURL formatted requests into Sense, Sense will recognize the cURL syntax and automatically transform it to a request formatted the Sense way. Sense also offers functionality for doing the opposite. When you have a request in Sense, you can click the wrench icon to bring up a dialog offering an option to “Copy as cURL”. The Copy as cURL dialog in Sense. Hello world For now, just run the below HTTP requests in Sense and take them at face value. First, let’s index a simple document: Indexing a simple document using cURL. curl -XPOST "" -d' { "text": "Hello world!" }' Now, let’s see if we can find it by searching for “hello”: A search request searching for the word ‘hello’. curl -XPOST "" -d' { "query": { "query_string": { "query": "hello" } } }' The response from ElasticSearch to the second HTTP request should look like the one below, containing a single hit. Example response from ElasticSearch to the above request. { "took": 12, "timed_out": false, "_shards": { "total": 12, "successful": 12, "failed": 0 }, "hits": { "total": 1, "max_score": 0.19178301, "hits": [ { "_index": "my-first-index", "_type": "message", "_id": "AUqiBnvdK4Rpq0ZV4-Wp", "_score": 0.19178301, "_source": { "text": "Hello world!" } } ] } } Curl syntax is programming language agnostic making it perfect to show HTTP interactions in a way that is both succinct and independent of any programming language. However, in the real world, except when debugging, we usually interact with ElasticSearch from our programming language of choice. Let’s look at a couple of examples of how the above requests could be implemented in actual applications. Node.JS example Elasticsearch Node.js client is official client for Node.js. For Node.JS, we use the official JavaScript client which can be installed in a Node.JS application using npm install elasticsearch. A simple application that indexes a single document and then proceeds to search for it, printing the search results to the console, looks like this: A simple implementation of the Hello World example in Node.JS. var elasticsearch = require('elasticsearch'); var client = new elasticsearch.Client({ host: 'localhost:9200' }); //An object that we'll index var theMessage = { text: "Hello world!" }; //Indexing the above object client.index({ index: "my-first-index", type: "message", body: theMessage }).then(function() { setTimeout(search, 1100); }); //Searching and printing the results function search() { client.search({ index: "my-first-index", type: "message", body: { query: { query_string: { query: "hello" } } } }).then(function(response) { console.log("Number of hits: " + response.hits.total); response.hits.hits.forEach(function(hit) { console.log(hit._source.text); }) }); } Note that we add a waiting period between indexing and searching. We do this because an indexed document won’t immediately be searchable after indexing. We have to wait for the index to be refreshed which by default happens every second. It’s possible to require ElasticSearch to immediately refresh the index when indexing a document but that’s bad performance wise and therefore we opt to wait a little. .NET example In the Node.JS example, we (naturally) used JavaScript and the official ElasticSearch client which more or less maps directly to ElasticSearch’s HTTP/JSON API. Therefore, the code for our Node.JS application looked quite similar to the original cURL based example.). Next, we create a class which we’ll index and search for instances of. A C# class representing a message. namespace HelloElasticSearch { public class Message { public Message(string text) { Text = text; } public string Text { get; private set; } } } The entry point of our application which implements the Hello World example by indexing a message and then searching for it looks like this: Basic example of indexing and searching using C# and the NEST client library. using System; using System.Threading; using Nest; namespace HelloElasticSearch { class Program { static void Main(string[] args) { //Create a client that will talk to our ES cluster var node = new Uri(""); var settings = new ConnectionSettings( node, defaultIndex: "my-first-index" ); var client = new ElasticClient(settings); //Creating and indexing a message object var theMessage = new Message("Hello world!"); client.Index(theMessage); //Waiting for the index to be refreshed Thread.Sleep(1100); //Search for messages and print the results var response = client.Search<Message>( body => body.Query( q => q.QueryString( qs => qs.Query("hello")))); Console.WriteLine("Number of hits: " + response.Total); foreach (var hit in response.Hits) { Console.WriteLine(hit.Source.Text); } } } }
http://mindmajix.com/elasticsearch/curl-syntax-with-examples
CC-MAIN-2016-44
refinedweb
920
57.16
look VoIP Keep Your Number VoIP Keep Your Number VoIP Keep Your Existing Phone Number Changing your phone service to Lingo VoIP phone service is easy, even better since you can keep Keep servlet session alive - Development process Keep servlet session alive Hi, I am developing an application in java swing and servlet. Database is kept on server. I am using HttpClient for swing servlet communication. I want to send heartbeat message from client JAVA JAZZ UP - Free online Java magazine JAVA JAZZ UP - Free online Java magazine Our this issue contains: Java Jazz Up Issue 3 Index...; Valued Java Jazz Up Readers Community We invite you to post Java-technology Java - Java Beginners , the book store keep track the number of the books bought and total amount spent..., and then resets the total amount spent to 0. Write a program that can process up to 1000 November 2007 Issue of Java Jazz up magazine November 2007 Issue of Java Jazz up magazine Java News Open source solution... Java project. NetBeans IDE The NetBeans IDE, product of Sun Java Basic Tutorial for Beginners Java Basic Tutorial for Beginners - Learn how to setup-development environment and write Java programs This tutorial will get you started with the Java...) More tutorials for beginners Getting Started with Java Learn Java Problem - Java Beginners Java Problem Write a program 2 input a positive integer n and check wheter n is prime or not and also know the position of that number in the prime..., Code to solve the problem : import java.io.*; public class PrimeNumber JAVA JAZZ UP - Free online Java magazine JAVA JAZZ UP - Free online Java magazine Our this issue contains: Java Jazz Up Issue 1 Index.... Reader?s Forum Welcome to the Java Jazz Up tomcat server start up error - Struts tomcat server start up error Hai friends..... while running tomcat server ,I got a problem..... Sep 5, 2009 4:49:08 AM... on the java.library.path: C:\Program Files\Java\jre6\bin;.;C:\WINDOWS\Sun\Java\bin;C Difference in two dates - Java Beginners for more information:... on that. The thing is, that I need to find the difference between the two dates in JAVA...(); Now I want to keep this in my Database...... So after few days exe set up software - Java Server Faces Questions exe set up software hi i want a exe file creator software. i am doing a project in swings. now i need exe converter. pls send simple code - Java Beginners simple code to input a number and check wether it is prime or not and print its position in prime nuber series. Hi friend, Code to help in solving the problem : import java.io.*; class PrimeNumber { public String Array - Java Beginners each value one by one. if it is string keep it in a string variable... it once up on a time, yes it worked. String st = new String("3d41d6 small java project - Java Beginners small java project i've just started using java at work and i need to get my self up to speed with it, can you give me a small java for beginners project to work on. your concern will be highly appreciated Setting Up SSI on WAMP Setting up SSI on WAMP Server Server Side Includes (SSI) - Definition The Server Side Includes is a simple interpreted server side scripting used... for SSI directives. Here, you will have to keep in mind that you will have Learn Java for beginners professionals as well as other learners as to how to keep up with it. The Java course...Learning Java for beginners has become an easy task now, with the popularity... Java Beginners tutorial Home page please help me how to set up Netbeans for JSP please help me how to set up Netbeans for JSP Hi roseindian.net, the following page is what i have seen when i run jsp project.What I can do,please...-For: 10.140.135.201 Cache-Control: max-age=259200 Connection: keep-alive Some possible pop up pop up how to create pop up in html java - Java Beginners up to a specific limit? Q2- write a program in java to check a given number for Fibonacci term? Q3- write a program in java to generate prime number up...-conversion I hope this will help you airline reservation java code - Java Beginners airline reservation java code Write a program that simulates... to simulate the box effect as in the diagram above, but try to keep the output... reset the bookings and free up ALL seats once again. Things to consider sort java - Java Beginners sort java 1. A statistics company wants to keep information of families. The information of a family is the family name, the number of members and first name of each member. The families are sorted alphabetically by family name java - Java Beginners java how can we show pop up menu with keypress event? do we need to give body of all three methos i.e. keypress,keyrelease,and keyprint program code for this question - Java Beginners an up-to-date text file in which they keep data about each of their customers...: Write a Java application, ProduceBills.java, that reads the name of the file Sorting in java - Java Beginners Sorting in java Hello.. I want you to help me with this question.. 1. A statistics company wants to keep information of families. The information of a family is the family name, the number of members and first name of each java programming - Java Beginners java programming hello friends! My name is David.I am a new to JAVA i really need exposure in the Language.I would appreciate it if you guys can... explanation) of to my mail anytime so that i can brush up myself.My e-mail write a program in java Adding up the subscript(st,nd,rd,th) to the number of days in a input string write a program in java Adding up the subscript(st,nd,rd,th) to the number of days in a input string write a program in java Adding up the subscript(st,nd,rd,th) to the number of days in a input string ex:If a user enters Beginners in Java Beginners in Java Hi, I am beginners in Java, can someone help me... tutorials for beginners in Java with example? Thanks. Hi, want to be command over Java, you should go on the link and follow the various beginners java question - Java Beginners java question Given the string "hey how are you today?" how many tokens would you have after breaking up the string using whitespace as a delimiter? Hi Friend, Try the following code: import java.util.*; public java beginners - Java Beginners the following links: beginners what is StringTokenizer? what is the funciton Java - Java Beginners are also great for setting up quick tests to see how Java works. The applications...Java Console application What is Java Console application? Hi friend,A Java Console application can only display textual data. Console Java help - Java Beginners Java help I didnot get the code ,therefore I am posting my question again.. Thanks in advance ...:) Programming Assignment: A) Consider... prescription B) The pharamacy want now to keep record of each patient Java Stacks - Java Beginners Java Stacks Hello..Help me with this assignment plzz. Programming Assignment: A) Consider the outpatient pharamacy at University Hospital... B) The pharamacy want now to keep record of each patient contains all Learn to Set Up An Internal Private Repository For An Organization Learn to Set Up An Internal Private Repository For An Organization... have set up an internal Maven Repository for our organisation so... to download the library files if your development team is big. When setting up a local Java - Java Beginners Java Java is call by value or call by referance? Hi... variables affect the caller?s original variables. Java never uses call by reference. Java always uses call by value. import java.io.*; import java.awt. HELP - Java Beginners HELP Hello sir ,how i can make Java Programs Set up File ,Please give me steps to make core java - Java Beginners change the fields in the caller?s objects they point to. In Java, you cannot... System.out.println("Massage 2: i= " + i + ", d= " + d); Double(i, i); //Java... original variables. Java never uses call by reference. Java always uses call by value Maximize Sales By Setting up Your Shopping Cart Maximize Sales By Setting up Your Shopping Cart Setting up a shopping cart... the features which boost up your sales. One of the main features is the auto responders... checkout list. This feature helps the administrator keep track of the aborted Java Compilation - Java Beginners Java Compilation I want to write a program that takes a positive integer from the keyboard. I want my program to sum all the integers from 1 up..., the sum is = 15 Here is what i came up with: import java.util.Scanner JAVA LOOPS - Java Beginners JAVA LOOPS Hi I need a Java program that can toss a coin over and over until it comes up head 10 times. It should also record the number of tails. Hi Friend, Try the following code: class Toss{ public final java code - Java Beginners java code Dear sir i need one java code * * * * * * * * * * * * * * * this model only i dont want need this type i need up one only ** *** **** ***** Hi friend Algorithm_3 - Java Beginners the following links:... index up to n-1 index. The algorithm follows the same steps iteratively unlit linked list in java - Java Beginners information. list in java Hi, how to implement linked list in java using...(); for (int i = 0; i < N; i++) { // look up a value in the list // using Java Program - Java Beginners Java Program Hi I'm having trouble with this program, i keep getting errors. Can you help me. Thanks Write a program to create a file named "numbers.dat". Then create an algorithm that adds all even numbered integers from 1 Java - Java Beginners Java I've been trying to figure out this program but I keep getting errors and its not working out. Can someone help me? this is the program... either use the value 3.1416 for Pi or use the Java provided value named Math.PI. Java Program - Java Beginners Java Program Hi, I'm have complications with this program. I keep getting errors and my coding is off. Can you help me? Write a program called OfficeAreaCalculator.java that displays the following prompts using two label Hiiiii - Java Beginners wanted to keep Java simple and found that operator overloading made code more...Hiiiii Hi, tell me all operator are overloaded in java Thanks Hi Ragini, It is true that Java does not allow operator java - Java Beginners ListSelectionListener simply set up types that you implement.You can define its Java Programming Tutorials for beginners Java Programming tutorials for beginners are made in such a way... simple so that not only Java professionals but Java beginners can also learn it easily. For the beginners in Java we bring our best of the best collection Java Coding - Java Beginners Java Coding How do I code the following: Code a switch statement that tests the value of an int variable named weightInt. This variable contains the weight of a shipment rounded up to the nearest multiple of 5. If the value java program - Java Beginners java program I worte out this program that was supposed to simulate a die rolling and then the program printing out each roll, the program also printing the number of of times each face came up/the percentage of the times. I java - Java Beginners java Q: write a program in java which input a positive natural N and output all combination of consecutive natural which add up to give N . Example : N=15 then the output should be 1 2 3 4 5 4 5 6 java - Java Beginners () { //Create and set up the window. JFrame frame = new JFrame("Drop example...); //Create and set up the content pane. JComponent newContentPane = new...:// Thanks Array in Java - Java Beginners program allows any number of numbers to be entered, up to 50 numbers. The output java - Java Beginners () { //Create and set up the window. JFrame frame = new JFrame("Drop...); //Create and set up the content pane. JComponent newContentPane... for more information. Java Program - Java Beginners Java Program Hi I'm having trouble with this problem, I keep getting errors. Write a program GuessGame.java that plays the game ?guess the number? as follows: Your program chooses the number to be guessed by selecting java button - Java Beginners java button i want to make form with checkboxes, after this i need button thich will open new pop-up page, where will be shown only this checkboxes whitch have been marked. please help me pleas wright me on my e-mail address NEW IN JAVA - Java Beginners ) subtraction,(other arithmetic operations have not been include to keep JAVA Error - Java Beginners JAVA Error i have made my own calculator GUI..and i want the text...() { //Create and set up the window. JFrame frame = new JFrame...: Thanks. Hello Just use codes - Java Beginners Java codes Ex#1. Write a java programe that declares 25 characters. Fill up the array with the letters of the English Alphabets(A-Z) and print out... on the monitor. Ex#3. Write a java program that declares an array containing java - Java Beginners an ACCEPT Set up a temporary stack. Copy the stack over, checking for the surname... the list. Technicalities 1. Use Java 1.4 Java Program HELP - Java Beginners Java Program HELP Hi I'm having trouble with this program, i keep getting errors. Can you help me. Thanks Write a program to create a file named "numbers.dat". Then create an algorithm that adds all even numbered integers Methods in Java - Java Beginners questions, which each are lalabeledith 4 answers, i was hoping it would end up looking up something similar to this. Question 1: Question will be here Java for beginners Java for beginners Java for beginners Which is the best resource... Java video tutorial for beginners. Thanks Hi, Here are the best resources for Learning Java for beginners: Java Video tutorial Java tutorials error in program when trying to load image in java - Java Beginners to add an image to my GUI using java graphics. I have cleaned up all my compiler errors but my program still won't run. I keep getting this type of message and I..." and add the logo to the GUI using Java graphics. this is the main codes java programming - Java Beginners contains the output from the ATM. Look up on google 'java TextArea' to view javadoc...java programming heloo there, hopw all of u guys are fine my question is how to program a atm machine consept by using java ?? im having problem Java array - Java Beginners Java array Q 1- write a program that counts the frequency...-- programming java hello would be displayed as hello java programming...[]) { String str[] = "programming java hello".split(" "); System.out.println java programing - Java Beginners java programing Write a program that reads numbers fromthe keyboard into an array of type int[]. You may assume that there will be 50 or fewer entries in the array .Your program allows any numbers of numbers to be entered , up Abstract class - Java Beginners Abstract class Why can use abstract class in java.?when abstract class use in java.plz Explain with program. abstract class abs{ public... but a template 4 the subclasses .thats all clear....u have to keep 3 things in ur mind What is Abstraction - Java Beginners What is Abstraction What is abstraction in java? How is it used in java..please give an example also Hi Friend, Abstraction is nothing... is made up of different components,does not need to know how the different Tomcat5.5 - Java Beginners Tomcat5.5 how to setup and run tomcat 5.5 in windows xp? to set up tomcat ...jus u have to do 2 steps 1.set ur java_home 2. set ur catlina_home it means specifying java and tomcat bin directory path java compilation error - Java Beginners java compilation error I need to know how to correct a compiler error for my program to run. The error I keep getting is unclosed string literal. The code it's firing on looks like this public String toString() { return Java Program- Complications - Java Beginners Java Program- Complications Hi, I'm have complications with this program. I keep getting errors. Write a program called OfficeAreaCalculator.java that displays the following prompts using two label components: Enter how to start with java - Java Beginners how to start with java sir i am new to java and i need the guidence... is based on jsp so suggest me the way to follow and cope up with this technology. framework - struts database - postgreSQL and java and jsp is used java beginners doubt! java beginners doubt! How to write clone()in java strings programming - Java Beginners programming for java beginners How to start programming for java beginners Java Printer Listener - Java Beginners Java Printer Listener I want some programs to make listener for all... to pop up our application before printing using java Hi friend, I am... for more information. program for Hashmaps - Java Beginners to keep track of the insertion order. Here is the code of HashMap import.... Thanks. Amardeep Java Developer Training . There are separate training program for beginners so that they can learn from the start and work there way up. The Java Developer training program includes the Servlet...Java Developer training are provided by Roseindia for the Java developers Java for beginners - Java Beginners :// Thanks...Java for beginners Hi! I would like to ask you the easiest way to understand java as a beginner? Do i need to read books in advance Inheritance - Java Beginners Inheritance class StdOps { //method: fileRead(String s) //purpose: opens up file s and reads (output to the screen)- one int per...");} //method: filewrite(String s, int[] a) //purpose: opens up file s and writes Compilatation problem - Java Beginners but after installing 1.4 and setting up the classpath also i am getting... link: Java guide for beginners Java guide provided at RoseIndia for beginners is considered best to learn...-to-date with recent releases in Java, one can also turn up to these guides. Once... and understand it completely. Here is more tutorials for Java coding for beginners
http://www.roseindia.net/tutorialhelp/comment/91697
CC-MAIN-2015-06
refinedweb
3,094
56.66
libidn-framework From GNU IDN Library - Libidn. This podspec uses a fork of libidn to fix a few minor issues related to CocoaPods integration. UsageUsage To run the example project, clone the repo, and run pod install from the Example directory first. InstallationInstallation libidn is available through CocoaPods. To install it, simply add the following line to your Podfile: pod "libidn" Maintenance NotesMaintenance Notes Upgrading libidn: - Download latest release 1.x from. The 2.x series does not include stringprep, which is needed by this wrapper library. - Copy over updated files that are in /libfolder - Comment out #include <config.h>" - Replace # include <idn-int.h>and #include "unistr.h"with #include <stdint.h> AuthorsAuthors - Chris Ballinger - Podspec maintainer - Simon Josefsson [email protected] - Designed and implemented libidn. - For more see AUTHORSin libidn source code. LicenseLicense libidn is available under the LGPL license, but the podspec and example code in this repo is MIT. See LICENSE for more details.
https://cocoapods.org/pods/libidn
CC-MAIN-2018-47
refinedweb
157
52.36
This patch creates a list of allowed filesystems per-namespace. The goal is to prevent users inside a container, even root, to mount filesystems that are not allowed by the main box admin. My main two motivators to pursue this are: 1) We want to prevent a certain tailored view of some virtual filesystems, for example, by bind-mounting files with userspace generated data into /proc. The ability of mounting /proc inside the container works against this effort, while disallowing it via capabilities would have the effect of disallowing other mounts as well. 2) Some filesystems are known not to behave well under a container environment. They require changes to work in a safe-way. We can whitelist only the filesystems we want. This works as a whitelist. Only filesystems in the list are allowed to be mounted. Doing a blacklist would create problems when, say, a module is loaded. The whitelist is only checked if it is enabled first. So any setup that was already working, will keep working. And whoever is not interested in limiting filesystem mount, does not need to bother about it. Please let me know what you guys think about it. Glauber Costa (4): move /proc/filesystems inside /proc/self per-namespace allowed filesystems list show only allowed filesystems in /proc/filesystems fslist netlink interface fs/Kconfig | 9 +++ fs/Makefile | 1 + fs/filesystems.c | 108 ++++++++++++++++++++++++------ fs/fsnetlink.c | 145 ++++++++++++++++++++++++++++++++++++++++ fs/namespace.c | 5 +- fs/proc/base.c | 64 +++++++++++++++--- fs/proc/root.c | 1 + include/linux/fs.h | 11 +++ include/linux/fslist_netlink.h | 35 ++++++++++ include/linux/mnt_namespace.h | 20 ++++++ 10 files changed, 368 insertions(+), 31 deletions(-) create mode 100644 fs/fsnetlink.c create mode 100644 include/linux/fslist_netlink.h -- 1.7.7.4
http://article.gmane.org/gmane.linux.kernel.cgroups/723
CC-MAIN-2017-30
refinedweb
287
60.92
I run a pair of GNU/Linux VPS's, one running Plex as a client and the other as a storage server for media. They both run on "the cloud" hosted by different providers. I've been noticing lately that transfer rates between them over SSHFS have been lagging, causing buffering and drop issues for some of my media streams. I tested directly between the hosts using Iperf3 and while not spectacular between two large hosting providers, it's fine for streaming SDTV content. me@plex:~$ iperf3 -c 10.10.10.100 -p 5201 --bytes 1000000000 Connecting to host 10.10.10.100 , port 5201 [ 4] local 10.10.10.99 port 56634 connected to 10.10.10.100 port 5201 [ ID] Interval Transfer Bandwidth Retr Cwnd [ 4] 0.00-1.00 sec 57.0 MBytes 478 Mbits/sec 165 3.94 MBytes [ 4] 1.00-2.00 sec 45.0 MBytes 378 Mbits/sec 17 1.99 MBytes [ 4] 2.00-3.00 sec 43.8 MBytes 367 Mbits/sec 0 2.02 MBytes [ 4] 3.00-4.00 sec 42.5 MBytes 356 Mbits/sec 0 2.15 MBytes [ 4] 4.00-5.00 sec 48.8 MBytes 409 Mbits/sec 0 2.41 MBytes [ 4] 5.00-6.00 sec 52.5 MBytes 440 Mbits/sec 0 2.76 MBytes [ 4] 6.00-7.00 sec 60.0 MBytes 503 Mbits/sec 0 3.02 MByte I then moved on and tested the mount point. I mount the media storage filesystem from plex client to storage server using SSHFS. So I performed a crude check on the SFTP mount point using cat and a standard utility called pipe viewer (pv). me@plex:/mnt/media/tv/show/S01$ cat show.mkv | pv -rb --progress >/dev/null 4.88MiB [ 300KiB/s] indeed, file read hovers around ~300KB/s (with multiple stalls) were just bad. Now there are a slew of tweaks that can be done, via the ssh protocol lighter MACs, Ciphers, via SSHFS buffer cache, VFS tweaks etc.. and the network, buffer, window sizes etc.. I decided to sidestep all the tweaks and try a different SFTP implementation entirely. I remembered a hacker news post not too long ago and decided download a binary release of SFTPGo. SFTPGo is a standalone SFTP server written in Go, that does not rely on the system authentication mechanisms and can utilize multiple SQL authentication back-ends such as SQLite, Mysql etc.. but I wanted a quick way to use public/private key authentication and good thing it supports this via its "portable" option. First we'll create an ssh public/private key pair on the Plex client VPS me@plex:~ ssh-keygen -t ecdsa -f ~/.ssh/id_ecdsa_sftpgo We then add a section in ~/.ssh/config on the client that describes the storage server Host storage_server Hostname 10.10.10.100 Port 4444 User sftpdude IdentityFile ~/.ssh/sftpgo_ecdsa Ciphers aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com MACs umac-128-etm@openssh.com,umac-128@openssh.com,hmac-sha1-etm@openssh.com,hmac-sha1,hmac-sha2-512-etm@openssh.com,hmac-sha2-512 Now we'll move to the storage server and create a dedicated directory and download the latest release of SFTPGo and install it manually me@storage:/ sudo mkdir /opt/sftpgo me@storage:/ sudo chown me:me !$ me@storage:/ cd !$ me@storage:/opt/sftpgo wget -O - | tar Jxf - Next create a wrapper script on the storage server and copy in the client's public key that was created earlier in ~/.ssh/id_ecdsa_sftpgo.pub me@storage:/opt/sftpgo/ cat sftpgo_start.sh #!/bin/sh sftpgo=/opt/sftpgo/sftpgo port=4444 pubkey='ecdsa-sha2-nistp256 AAAAE2V....3YPCHWceWD2QcQFG=' dir=/mnt/media $sftpgo portable --username sftpdude --public-key "$pubkey" --sftpd-port $port --directory $dir --permissions '*' We run the newly created script on the storage server me@storage:/opt/sftpgo/ /opt/sftpgo/ssftpgo_start.sh We connect to the storage_server via sshfs me@plex:~ /usr/bin/sshfs -f storage_server:/tv /mnt/media/tv2 -o ServerAliveInterval=15 -o rw,reconnect,idmap=user and retry via the crude cat | pv me@plex:/mnt/media/tv2/show/S01$ cat show.mkv | pv -rb --progress >/dev/null 23.8MiB [2.84MiB/s] and lo and behold .. much faster transfer rates without tweaking and just switching implementations. Of course it's far slower than a raw byte transfers (iperf3) but we are utilizing FUSE which in itself is a bottleneck traversing user-space/kernel boundaries, but it's good enough for this use case. Securing things OpenSSH has decades of security under its belt and comes from the iron clad OpenBSD folks and we want to protect the system as much as possible from any weird side effects, bugs, and/or exploits typical of long running programs. While it is written in a garbage collected language (Go) which eliminates many classes of memory induced bugs, it is better to be safe than sorry. So if you're running a popular Linux distro today you most likely have systemd installed by default. Systemd is an initd/framework for starting/managing the system and it's services. It is what we'll use to to monitor, manage and secure the SFTPGo service. First thing we do is think about that what the service needs to do to perform its job; it starts up, creates a pub/priv key file if /opt/sftpgo/id_ecdsa doesn't exist, listens on a specified port, and reads/writes to /mnt/media/. So let's create a systemd service file that incorporates this behavior. So here's the systemd service file me@storage:/etc/systemd/system cat sftpgo@me.service [Unit] Description=SFTP Go AssertDirectoryNotEmpty=/mnt/media/ [Service] User=%i ExecStart=/opt/sftpgo/sftpgo_start.sh WorkingDirectory=/opt/sftpgo ExecReload=/bin/kill -s HUP $MAINPID KillMode=mixed Type=simple Restart=on-failure RestartSec=10 StartLimitInterval=20s StartLimitBurst=3 NoNewPrivileges=yes PrivateTmp=yes PrivateDevices=yes DevicePolicy=closed ProtectSystem=strict ProtectHome=yes ReadWritePaths=/opt/sftpgo /mnt/media/tv RestrictAddressFamilies=AF_INET #requires systemd 235+ and kernel 4.11+ IPAccounting=yes IPAddressDeny=any IPAddressAllow=10.10.10.0/24 [Install] WantedBy=multi-user.target Alias=sg.service Basically we prevented read/write access anywhere except /opt/sftpgo and /mnt/media/tv. We restricted access to /home or any other filesystems via the ProtectHome, ProtectSystem stanzas. We also restricted socket creation to the AF_INET protocols while only accepting connections from Plex client ip address range. Systemd provides a host of facilities one can use to secure their services without that much effort in tandem with the kernel 4.x+ namespacing, eBPF, cgroup controls. Most of systemd's lock down parameters are explained here, there's even more we can do such as system call, namespace filtering, but we'll need to profile the binary some more before implementing that. Now we enable and start our new service me@storage:~ sudo systemctl enable sftpgo@me me@storage:~ sudo systemctl start sftpgo@me me@storage:~ sudo systemctl status sftpgo@me And check some transfer stats after transferring some files (since we enabled IPAccounting=yes) me@storage:~ sudo systemctl show sftpgo@me -p IPIngressBytes -p IPEgressBytes IPIngressBytes=20382896 IPEgressBytes=677305852 99% of the time I have no need to replace the standard SFTP server implementation on my Linux/*BSD hosts, but it was worth it this time for some flexibility and the bump in speed. Though the OpenSSH SFTP implementation is actually faster than SFTPGo, so clearly something is wrong between these hosts that I need to troubleshoot down the road. But, just the fact that I can decouple the standard GNU/Linux user authentication mechanism from SFTP and name the user whatever I want as long as the script has the correct read/write permissions is a plus for me. Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/joshbaptiste/replacing-openssh-sftp-with-sftpgo-gkc
CC-MAIN-2021-21
refinedweb
1,299
57.98
import "gopkg.in/kubernetes/kubernetes.v0/pkg/clientauth" Package authcfg defines a file format for holding authentication information needed by clients of Kubernetes. Typically, a Kubernetes cluster will put auth info for the admin in a known location when it is created, and will (soon) put it in a known location within a Container's file tree for Containers that need access to the Kubernetes API. Having a defined format allows: - clients to be implmented in multiple languages - applications which link clients to be portable across clusters with different authentication styles (e.g. some may use SSL Client certs, others may not, etc) - when the format changes, applications only need to update this code. The file format is json, marshalled from a struct authcfg.Info. Clinet libraries in other languages should use the same format. It is not intended to store general preferences, such as default namespace, output options, etc. CLIs (such as kubectl) and UIs should develop their own format and may wish to inline the authcfg.Info type. The authcfg.Info is just a file format. It is distinct from client.Config which holds options for creating a client.Client. Helper functions are provided in this package to fill in a client.Client from an authcfg.Info. Example: import ( "pkg/client" "pkg/clientauth" ) info, err := clientauth.LoadFromFile(filename) if err != nil { // handle error } clientConfig = client.Config{} clientConfig.Host = "example.com:4901" clientConfig = info.MergeWithConfig() client := client.New(clientConfig) client.Pods(ns).List() type Info struct { User string Password string CAFile string CertFile string KeyFile string BearerToken string Insecure *bool } Info holds Kubernetes API authorization config. It is intended to be read/written from a file as a JSON object. LoadFromFile parses an Info object from a file path. If the file does not exist, then os.IsNotExist(err) == true MergeWithConfig returns a copy of a client.Config with values from the Info. The fields of client.Config with a corresponding field in the Info are set with the value from the Info. Package clientauth imports 4 packages (graph). Updated 2016-07-25. Refresh now. Tools for package owners.
https://godoc.org/gopkg.in/kubernetes/kubernetes.v0/pkg/clientauth
CC-MAIN-2019-30
refinedweb
350
51.65
ClassCastException after redeployAlexander Hachmann Oct 11, 2006 9:30 AM Hi there, I am quiet frustrated with having a strange behavior I do not understand. I have an EAR Application containing an EJB and a WAR. In the EJB I have a small HelloWorld Class being remote and local. I Call this class from the Servlet in the War. Which works perfectly fine. Now when I change the Code in the HelloWorld Class (simply changing the returned text) and redeploy this EAR, I get a ClassCastException when calling this Object. When I hav the WAR deployed itself in a different ctxPath, that servlet keeps working fine. My Bean: @Stateless @Local(MyDAO.class) @LocalBinding(jndiBinding="EpgData/LocalDao") @Remote(MyDAO.class) @RemoteBinding(jndiBinding="EpgData/RemoteDao") public class MyDAOImpl implements MyDAO { public String getObject() { // TODO Auto-generated method stub return "Hi There?! Someone"; } } my servlet: public void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { arg1.setContentType("text/html"); PrintWriter out = arg1.getWriter(); Context ctx; try { ctx = new InitialContext(); out.println("2----------------------------------------------------------------<br>"); Object o; try { o = ctx.lookup("EpgData/LocalDao"); MyDAO hello = (MyDAO)o; out.println(hello.getObject()); } catch (NamingException e) { // TODO Auto-generated catch block out.println("Second: "+e); }catch (ClassCastException e){ e.printStackTrace(out); out.println(reflect(ctx.lookup("LOVE"))); } } catch (NamingException e) { // TODO Auto-generated catch block out.println("Outer: "+e); } } 1. Re: ClassCastException after redeployAlexander Hachmann Oct 11, 2006 9:32 AM (in response to Alexander Hachmann) I would be very happy if anyone could help me. Any Ideas? Thx, Alexander 2. Re: ClassCastException after redeployjaikiran pai Oct 11, 2006 10:17 AM (in response to Alexander Hachmann) Where are placing the remote and home interfaces of your beans. Is it in two separate locations(once in war and once in a jar)? If yes, then maintain it at only one place and remove those interfaces from the war. Have a look at: Here's an extract from the same: I get ClassCastException. Also, look at: Specifically, the jmx-console method mentioned over there 3. Re: ClassCastException after redeployAlexander Hachmann Oct 11, 2006 11:33 AM (in response to Alexander Hachmann) Yes, that helped. Thank you. Does this mean, that I have to build different packages if I wish to deploy one of those Packages on a diferent Server? I hoped, that I could simply put this Package on a different Server and remap the JNDI Name to the remote object. But for this Situation there are the Interfaces missing. So this was not where its going with EJB3? Regards, Alexander 4. Re: ClassCastException after redeployjaikiran pai Oct 11, 2006 11:41 AM (in response to Alexander Hachmann) If you packaging your war inside the ear(which also includes the ejb jars), then the remote/home interfaces need not be in the war file, since the war is *part of the ear application* which contains the necessary interfaces. However if you want the war to be a separate archive(outside the ear), then you will have to ship the remote/home interfaces of these ejbs since your war is no longer a part of the ear application - the war and the ear will act as two separate independent applications 5. Re: ClassCastException after redeployAlexander Hachmann Oct 12, 2006 5:20 AM (in response to Alexander Hachmann) Yes, this what i expected to happen, But now I have the situation, that when I have taken the war out of the ear, I still need to leave out the Interfaces from the war. When i deploy the archives at the same time, everything works fine. But when I now change the interfaces implementations and redeploy the ear, i get a class cast exception. I know, that this sounds like the opposite of what i wrote in the first post. And I am confused about that. What I did now, is that i put the Interfaces in a single jar-file which i deploy itsself. Now i can modify the implementation without any problems. Is it that way, that the Deployer perhaps does not recognise, that the Interfaces in the new EAR file are the same as the ones in the war file? Then the Classlaoder would load the interfaces again. But the ones in the ear are then different ones to the ones in the war. Anyone a short comment whether this asumption could be right? thx, Alexander 6. Re: ClassCastException after redeployjaikiran pai Oct 12, 2006 8:37 AM (in response to Alexander Hachmann) So you want to have a separate war containing the remote/home interfaces and also an ear containing these remote/home interfaces. You want these 2 to behave as two separate applications independent of each other. You will have to do classloader isolation as mentioned in Section "Isolation" at: Briefly, you will have to add the following entry to your jboss-web.xml(present in your war file) : <jboss-web> <class-loading <loader-repository> someName.someOtherName:loader=someUniqueName <loader-repository-config>java2ParentDelegation=false</loader-repository-config> </loader-repository> </class-loading> ..... </jboss-web> And add the following to jboss-app.xml(present in ear file): <jboss-app> <loader-repository> someName2.someOtherName2:loader=someOtherUniqueName <loader-repository-config> java2ParentDelegation=false </loader-repository-config> </loader-repository> </jboss-app> This will actually create 2 separate classloaders, one for the ear application and the other for the war application. You can then use the war separately from the ear file.
https://developer.jboss.org/thread/120975
CC-MAIN-2019-04
refinedweb
899
56.55
October 9, 2017 | Written by: David Provan Categorized: Compute Services | How-tos | Integration Share this post:. As we dug deeper to find previous artifacts and frameworks that we could take advantage of, we found Spring Social as one of the Spring Projects. It has core support for both Twitter and Facebook and linked to a community project for Google Social. All of our previous RESTful implementations on Liberty Buildpack had used JAX-RS and we have found using that framework simple and powerful. The annotations were simple and for the most part our apps were simple enough to utilize just that and be successful. As a team, we discussed if we wanted to mix JAX-RS and Spring Social, or did we set this project up with Spring REST and use one set of annotations. It’s important to note here that you can very much combine both Spring and JAX-RS, our decision was primarily being made based on code style and developer convenience rather than technical factors. Setting up a Sprint REST app One of the many attractions we had with JAX-RS was the simplicity of setting up and RESTful providers and associated methods for handling GET, POST, PUT and DELETE requests; annotate the method and done. Spring REST, unsurprisingly, does it the same way. Below you can see the annotations on a JAX-RS class and how that maps to the Spring annotations to achieve the same goal. JAX-RS @Provider @Path("/helloworld") public class PreferencesProvider { @Path("/{text}"); @GET public Response getPreferences(@PathParam(“text”) String text) { return Response.ok(text); } } </code> Spring REST <code> @RestController @RequestMapping("/helloworld") public class PreferencesProvider { @RequestMapping(value = "/{text}", , method = RequestMethod.POST) public ResponseEntity<?> getPreferences(@PathVariable String text) { return ResponseEntity.ok(text); } } As you can see, from a code perspective, there isn’t much of a change to the general approach; the annotations are different but their use is obvious. The real difference is how you then tell Spring to activate the application as a RESTful app. Setting up web.xml If you had previous experience with JAX-RS you will be familiar with the following web.xml fragment: <servlet> <servlet-name>javax.ws.rs.core.Application</servlet-name> <load-on-startup>1</load-on-startup> <enabled>true</enabled> </servlet> <servlet-mapping> <servlet-name>javax.ws.rs.core.Application</servlet-name> <url-pattern>/<u>api</u>/*</url-pattern> </servlet-mapping> This provided the info to liberty as it loaded the war, it told it the context path to use and then said “hey I am JAX-RS” and the code scan of the annotations then loaded in the appropriate providers. Spring isn’t a million miles away from this, however the approach is a little different. The web.xml looks like this: <?xml version="1.0" encoding="UTF-8"?><web-app <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/api</url-pattern> </servlet-mapping> </web-app> Then, along with web.xml, we add a spring-servlet.xml into the WEB-INF directory of your project: <beans xmlns="" xmlns:</code> <context:component-scan <mvc:annotation-driven /> </beans> The context:component-scan tag tells spring where to go find components with the annotations. You should set the base-package attribute to the name of your package in your war file. Deploying to Bluemix Now, as always with bluemix, the easy part; the deployment. Build your war and push to bluemix with either the Bluemix CLI or the Dev Ops tools. Gradle We are deploying our apps with gradle, for reference here is our gradle build file in case the dependencies prove useful. You can start the with the web-starter-boot from spring but our dependancies just list what is needed for Spring REST to work. buildscript { repositories { mavenCentral() } dependencies { <u>classpath</u> "org.springframework.boot:spring-boot-<u>gradle</u>-<u>plugin</u>:1.5.7.RELEASE" } } apply <u>plugin</u>: 'java' apply <u>plugin</u>: 'eclipse' apply <u>plugin</u>: 'idea' apply <u>plugin</u>: 'org.springframework.boot' apply <u>plugin</u>: 'war' war { baseName = 'NameOfYourApp' version = '0.0.1' } repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile group: 'org.springframework', name: 'spring-core', version: '4.3.11.RELEASE' compile group: 'org.springframework', name: 'spring-context', version: '4.3.11.RELEASE' compile group: 'org.springframework', name: 'spring-beans', version: '4.3.11.RELEASE' compile group: 'org.springframework', name: 'spring-expression', version: '4.3.11.RELEASE' compile group: 'org.springframework', name: 'spring-web', version: '4.3.11.RELEASE' compile group: 'org.springframework', name: 'spring-<u>webmvc</u>', version: '4.3.11.RELEASE' compile group: 'org.springframework', name: 'spring-<u>aop</u>', version: '4.3.11.RELEASE' compile group: 'org.springframework', name: 'spring-context', version: '4.3.11.RELEASE' compile group: 'com.fasterxml.jackson.core', name: '<u>jackson</u>-core', version: '2.9.1' compile group: 'com.fasterxml.jackson.core', name: '<u>jackson</u>-annotations', version: '2.9.1' compile group: 'com.fasterxml.jackson.core', name: '<u>jackson</u>-<u>databind</u>', version: '2.9.1' compile group: 'org.slf4j', name: '<u>jcl</u>-over-slf4j', version: '1.7.25' } Conclusion We hope this is a useful starter for getting Spring REST up and running on the liberty buildpack, as we said before we don’t see a huge difference between Spring and JAX-RS in terms of ease of development it was more a developer familiarity choice. Moving our code to spring certainly allows us to take advantage of the other areas of usefulness that spring provides.!
https://www.ibm.com/blogs/bluemix/2017/10/using-spring-rest-liberty-buildpack/
CC-MAIN-2018-17
refinedweb
940
51.34
GPIO Mappings¶ This document explains how GPIOs can be assigned to given devices and functions. Note that it only applies to the new descriptor-based interface. For a description of the deprecated integer-based GPIO interface please refer to gpio-legacy.txt (actually, there is no real mapping possible with the old interface; you just fetch an integer from somewhere and request the corresponding GPIO). All platforms can enable the GPIO library, but if the platform strictly requires GPIO functionality to be present, it needs to select GPIOLIB from its Kconfig. Then, how GPIOs are mapped depends on what the platform uses to describe its hardware layout. Currently, mappings can be defined through device tree, ACPI, and platform data. Device Tree¶ GPIOs can easily be mapped to devices and functions in the device tree. The exact way to do it depends on the GPIO controller providing the GPIOs, see the device tree bindings for your controller. GPIOs mappings are defined in the consumer device’s node, in a property named <function>-gpios, where <function> is the function the driver will request through gpiod_get(). For example: foo_device { compatible = "acme,foo"; ... led-gpios = <&gpio 15 GPIO_ACTIVE_HIGH>, /* red */ <&gpio 16 GPIO_ACTIVE_HIGH>, /* green */ <&gpio 17 GPIO_ACTIVE_HIGH>; /* blue */ power-gpios = <&gpio 1 GPIO_ACTIVE_LOW>; }; Properties named <function>-gpio are also considered valid and old bindings use it but are only supported for compatibility reasons and should not be used for newer bindings since it has been deprecated. This property will make GPIOs 15, 16 and 17 available to the driver under the “led” function, and GPIO 1 as the “power” GPIO:); The led GPIOs will be active high, while the power GPIO will be active low (i.e. gpiod_is_active_low(power) will be true). The second parameter of the gpiod_get() functions, the con_id string, has to be the <function>-prefix of the GPIO suffixes (“gpios” or “gpio”, automatically looked up by the gpiod functions internally) used in the device tree. With above “led-gpios” example, use the prefix without the “-” as con_id parameter: “led”. Internally, the GPIO subsystem prefixes the GPIO suffix (“gpios” or “gpio”) with the string passed in con_id to get the resulting string ( snprintf(... "%s-%s", con_id, gpio_suffixes[]). ACPI¶ ACPI also supports function names for GPIOs in a similar fashion to DT. The above DT example can be converted to an equivalent ACPI description with the help of _DSD (Device Specific Data), introduced in ACPI 5.1: Device (FOO) { Name (_CRS, ResourceTemplate () { GpioIo (Exclusive, ..., IoRestrictionOutputOnly, "\\_SB.GPI0") {15} // red GpioIo (Exclusive, ..., IoRestrictionOutputOnly, "\\_SB.GPI0") {16} // green GpioIo (Exclusive, ..., IoRestrictionOutputOnly, "\\_SB.GPI0") {17} // blue GpioIo (Exclusive, ..., IoRestrictionOutputOnly, "\\_SB.GPI0") {1} // power }) Name (_DSD, Package () { ToUUID("daffd814-6eba-4d8c-8a91-bc9bbf4aa301"), Package () { Package () { "led-gpios", Package () { ^FOO, 0, 0, 1, ^FOO, 1, 0, 1, ^FOO, 2, 0, 1, } }, Package () { "power-gpios", Package () {^FOO, 3, 0, 0}, }, } }) } For more information about the ACPI GPIO bindings see Documentation/acpi/gpio-properties.txt. Platform Data¶ Finally, GPIOs can be bound to devices and functions using platform data. Board files that desire to do so need to include the following header: #include <linux/gpio/machine.h> GPIOs are mapped by the means of tables of lookups, containing instances of the gpiod_lookup structure. Two macros are defined to help declaring such mappings: - - con_id is the name of the GPIO function from the device point of view. It - can be NULL, in which case it will match any function. - idx is the index of the GPIO within the function. - - flags is defined to specify the following properties: - - GPIO_ACTIVE_HIGH - GPIO line is active high - GPIO_ACTIVE_LOW - GPIO line is active low - GPIO_OPEN_DRAIN - GPIO line is set up as open drain - GPIO_OPEN_SOURCE - GPIO line is set up as open source - - GPIO_PERSISTENT - GPIO line is persistent during - suspend/resume and maintains its value - - GPIO_TRANSITORY - GPIO line is transitory and may loose its - electrical state during suspend/resume In the future, these flags might be extended to support more properties. Note that GPIO_LOOKUP() is just a shortcut to GPIO_LOOKUP_IDX() where idx = 0. A lookup table can then be defined as follows, with an empty entry defining its end. The ‘dev", .table = { GPIO_LOOKUP_IDX("gpio.0", 15, "led", 0, GPIO_ACTIVE_HIGH), GPIO_LOOKUP_IDX("gpio.0", 16, "led", 1, GPIO_ACTIVE_HIGH), GPIO_LOOKUP_IDX("gpio.0", 17, "led", 2, GPIO_ACTIVE_HIGH), GPIO_LOOKUP("gpio.0", 1, "power", GPIO_ACTIVE_LOW), { }, }, }; And the table can be added by the board code as follows: gpiod_add_lookup_table(&gpios_table); The driver controlling “foo.0” will then be able to obtain its GPIOs as follows:); Since the “led” GPIOs are mapped as active-high, this example will switch their signals to 1, i.e. enabling the LEDs. And for the “power” GPIO, which is mapped as active-low, its actual signal will be 0 after this code. Contrary to the legacy integer GPIO interface, the active-low property is handled during mapping and is thus transparent to GPIO consumers. A set of functions such as gpiod_set_value() is available to work with the new descriptor-oriented interface. Boards using platform data can also hog GPIO lines by defining GPIO hog tables. struct gpiod_hog gpio_hog_table[] = { GPIO_HOG("gpio.0", 10, "foo", GPIO_ACTIVE_LOW, GPIOD_OUT_HIGH), { } }; And the table can be added to the board code as follows: gpiod_add_hogs(gpio_hog_table); The line will be hogged as soon as the gpiochip is created or - in case the chip was created earlier - when the hog table is registered.
https://www.kernel.org/doc/html/latest/driver-api/gpio/board.html
CC-MAIN-2018-43
refinedweb
885
53.1
So I checked the .Net framework forum, and there was no 'general' section, nor was there a 'Windows.Forms' section (but there was a WPF section...). I attempted posting a similar question to this post in the VB.Net forum, with no assistance. The only reason is because the job is in VB. But really the question I have is not really VB dependent and is a .Net issue. Because I prefer C# over VB, and most of the skilled .Net users I've seen around the forum seem to also prefer C#, I'm going to post this here. My Question: So I have a simple on screen keyboard control. It's just a custom Control with a bunch of buttons laid out like a Numpad. When it's clicked I use SendKeys to simulate a key press of that number. Of course when the user presses each button, the focus is given to the button being clicked and I need to manually return it back to the control that had the focus prior. I do this by listening to the leave event of all controls I considered 'managed' and remember the last one that had focus, and return said focus. Rather simple. When returning focus these controls generally remember the state of their selection if they were (if a TextBox it remembers what, if any, text was highlighted by the user. And where the input carriage belongs). But one stupid Control type gives me a giant pain in the arse. DataGridView The DataGridView as I've come to learn (keep in mind I come from other languages, then to mono, and now to actual .Net and only recently started playing with the Windows.Forms namespace... I hate it, sorry), it uses a smart little method of reducing memory required by the Control. When you go to edit any cell an 'EditingControl' is created for the cell temporarily, then once the cell is left and validated, that 'EditingControl' is disposed of in some manner. Smart in some respects, but deals one majour blow to my system. When leaving the DataGridView that is being edited mode to strike this button and returning back to the DataGridView, the EditingControl had been disposed of and doesn't remember its state. Calling 'Focus' brings it back into focus, and the cell is in edit more (because the DataGridView remembers), but the cell itself is in a default selected mode (for a text cell the text is all highlighted, not good if we want subsequent key strikes). With some hacking a work mate of mine found different ways to deal with it. All of them hacky, and none of them really working out exactly how we hope. The best one he found was when leaving a Control we check if it is a DataGridView, set the forms active control to the 'EditingControl' (yeah, that's the super hacky part I hate, but it keeps it from getting disposed), then when the button for the numpad is clicked we check if the last control was a DataGridView or not, if not we call Focus, if is we call BeginEdit. But as one would suspect this hack causes the 'EditingControl' to get stuck on screen, as I expected something of the likes to occur. So I ask of you guys, do you have any experience with this one hell of an annoying Control, this problem, and have any ideas how to deal with it? The specific functionality we expect is that when we return focus to the last active control before hitting the numpad, that the selected/highlighted state of the control is how it was when we left. All controls accept for DataGridView act as expected... but editable DataGridViews play a huge role in the project. This post has been edited by lordofduct: 02 November 2010 - 08:12 AM
http://www.dreamincode.net/forums/topic/197955-return-focus-to-a-windowsformsdatagridview/
CC-MAIN-2017-17
refinedweb
644
68.91
I now have the final list of sessions that I will be attending at VMworld. As I noted last time I had a lot of waitlists which it now appears I have not made the cut for most of the sessions. That means I will be at our booth (#2422) almost all of today (Aug 31, 2009) and at the times when I am not attending a session. <?xml:namespace prefix = o ns = “urn:schemas-microsoft-com:office:office” /> There is a great opportunity to win a 32GB Zune HD. All you have to do is to follow the Microsoft Virtualization experts on Twitter. By the way this is open to folks who are not attending VMworld as well. So follow along with us!! You can follow me here. I am heading over to the Moscone Center to register and see if I can get into some of the labs being offered today. Vijay Tewari Principal Program Manager, Windows Server Virtualization Join the conversationAdd Comment enter was excellent thanks
https://blogs.technet.microsoft.com/virtualization/2009/08/31/follow-us-on-twitter-and-get-a-chance-to-win-a-zune-hd/
CC-MAIN-2018-30
refinedweb
169
71.85
Our saltstack is based on hostnames (webN., dbN., etc.). But for various things I need IPs of those servers. For now I had them stored in pillars, but the number of places I need to sync grows. I tried to use publish + network.ip_addrs, but that kinda sucks, because it needs to do the whole salt-roundtrip just to resolve a hostname. Also it's dependent on the minions responding. Therefore I'm looking for a way to resolve hostname to IP in templates. I assume that I could write a module for it somehow, but my python skills are very limited. You could use a custom grain. Create file _grains/fqdn_ip.py in the state tree directory: import socket def fqdn_ip(): return { 'fqdn_ip': socket.gethostbyname(socket.getfqdn()) } In template: {{ grains.fqdn_ip }} Another way is use dnsutil module (requires dig command on minion): {{ salt['dnsutil.A']('host.name.tld')[0] }}
https://codedump.io/share/Liss1k7VZMQQ/1/how-to-get-ip-address-of-hostname-inside-jinja-template
CC-MAIN-2017-43
refinedweb
150
69.48
Development/Tutorials/Plasma4/Ruby/SimplePasteApplet Warning: This tutorial has not yet been completely tested and might contain incorrect information or examples. Contents Abstract This tutorial will explain how to make simple KDE Plasma applet using Ruby. The applet will be a simple version of the paste applet. It will allow the user to put a bit of text on the clipboard. Getting started Before you get started you need to make sure to have the following installed on your computer. - KDE 4.2 - Ruby 1.8 - KDE 4.2 Ruby bindings These packages can usually be installed through your distributions package manager. Package layout Plasma applets written in Ruby can be distributed as a plasmoid package. A minimal Ruby plasmoid package has the following structure: - contents/ - code/ - main.rb - metadata.desktop The Ruby code for the plasmoid should be put in a file called main.rb in the contents/code folder of your package. The metadata.desktop file holds metadata about your plasmoid. This includes your name, name of your applet and a description. The metadata.desktop file is in the common .desktop file format, which looks a lot like an old INI file. A minimal metadata.desktop file looks like this: Code Let's first start with the most basic Ruby applet and work from there. Every Plasma applet you're going to make in Ruby has to have a module. A minimal Ruby Plasma applet looks like this: require 'plasma_applet' module RubyTest class Main < PlasmaScripting::Applet def initialize parent super parent end def init set_minimum_size 150, 150 end end end The module name must match the name you specify in metadata.desktop on the X-KDE-PluginInfo-Name line.>, plasmapkg will now install your applet. mkdir ruby-test-applet cd ruby-test-applet - Copy or create metadata.desktop mkdir contents cd contents mkdir code cd code - Copy or create main.rb cd ../../.. plasmapkg -i ruby-test-applet Now that your applet is installed, you can view it.. A label on an applet When you have a very basic applet running, you can go two ways. You can put QWidgets on your applet, or draw the applet yourself by implementing the paintInterface method. I like to use standard widgets most of the time, so we're going to place some QWidgets on the plasma applet. Plasma has a couple of themed widgets. A list can be found in the Plasma API. To place these widgets on your applet, you need a layout. The layout you'll be using most of the time will be the GraphicsLinearLayout, which basically puts your widgets in a horizontal or vertical line. When putting a Plasma::Label on an applet in a GraphicsLinearLayout, you'll get the following code: require 'plasma_applet' module RubyTest class Main < PlasmaScripting::Applet def initialize parent super parent end def init set_minimum_size 150, 150 label = Plasma::Label.new self label.text = 'This is a label on a plasmoid, hello Plasma!' layout = Qt::GraphicsLinearLayout.new self self.layout = layout layout.add_item label end end end In the init method we create a Plasma::Label and assign it a text. The first argument to the constructor of Plasma::Label (the new) is the parent of the label, in this case our applet. Next we create a GraphicsLinearLayout, assign it to the applet and put our label on it. To view your applet, run plasmapkg -u <folder name> and plasmoidviewer <plasmoid name>. plasmapkg -u ruby-test-applet plasmoidviewer ruby-test This will show you a nice and simple Hello World in Plasma. Let's continue by adding a line edit and a button with some functionality. class for that. Adding it is exactly the same as adding the label. With a line edit and button in place, we should let the button do something when it's clicked. Qt, the library on which KDE is based, uses a mechanism called 'signals and slots'. You could compare it to action or event handlers in other languages or frameworks. Normally, one would connect a certain signal (event) to a certain slot (event handler method). Since we're using Ruby, we can't only do that, we can connect a signal to a code block. The syntax for this is easy: button.connect(SIGNAL(:clicked)) do # do something end Now, when the button gets clicked, the code in the block gets executed. We will do something simple when the button gets pressed. Qt makes it very easy to put some text on the clipboard, so let's do that. To put text on the clipboard we need Qt::Application.clipboard. This object has the very convenient method text= which puts text on the clipboard. Putting it all together, we have to following code: require 'plasma_applet' module RubyTest class Main < PlasmaScripting::Applet def initialize parent super parent end layout.add_item line_edit button = Plasma::PushButton.new self button.text = 'Copy to clipboard' layout.add_item button button.connect(SIGNAL(:clicked)) do Qt::Application.clipboard.text = line_edit.text end end end end Where to go from here Now that you have this simple but working Ruby Plasma applet, you can expand it. You can start by trying out some of the other Plasma widgets available. The official Plasma API is unfortunately written for C++. But with a little imagination and some logic you should be able to make use of it. You could also try looking at some Ruby Plasma examples. These are written a bit different then the example described above, but they should still be useful. If you have any questions about Plasma development there are several ways to ask for help. First of all there is the Plasma mailinglist. Secondly you can hop by on IRC, #plasma on irc.freenode.org. As a third option you could try asking you question on the KDE forums. Good luck, and don't forget to publish your Plasma applet on kde-look.org!
https://techbase.kde.org/index.php?title=Development/Tutorials/Plasma4/Ruby/SimplePasteApplet&oldid=37587
CC-MAIN-2020-50
refinedweb
983
67.25
Archive Implementing IEPNGFix as a Reusable Control Even with IE 8.0 on the horizon, a great deal of our internal users are still using IE 5.5 and 6.0. While, for the most part, our current coding techniques are unaffected, we did move to using PNG files quite a while ago and are faced with rendering issues as the target audience for a few of our produces expands. To solve those issues, I’ve been using TwinHelix’s IE PNG Fix behavior with a great deal of success; however, I dislike keeping track of multiple files and references between projects. It made more sense to make it a reusable control and include it in our shared architecture library. When Angus releases a new implementation, then I only need to update the control and push out the updated libraries rather than touching HTML in each project. Here’s how: 1. Download the latest version of IE PNG Fix from here. 2. Add the IEPngFix.htc, blank.gif, and IEPngFix_tilebg.js (if using 2.0 Alpha 3) into your project. Mark all three files as Embedded Content. 3. Create a basic CSS file that can be added to pages and call the IEPngFix behavior. Use the full path to the Web Resource (we’ll add those in the next step). It’s sensitive to the namespace of your project. img, div, .pngfix, input { behavior: url(‘<%=WebResource(“Resources.IEPngFix.htc”)%>’); } 3. Modify the Properties/AssemblyInfo.cs file and add the approprate Web References. [assembly: WebResource(“Resources.IEPngFix.css”, “text/css”, PerformSubstitution = true)] [assembly: WebResource(“Resources.IEPngFix.htc”, “text/x-component”, PerformSubstitution = true)] [assembly: WebResource(“Resources.IEPngFix_blank.gif”, “image/gif”)] [assembly: WebResource(“Resources.IEPngFix_tilebg.js”, “text/javascript”)] Notice that the HTC behavior file is an “x-component”. For a full list of MIME references, check out the w3schools.com. Also, perform substitution allows us to use dynamic calls of resources—within resources, such as in our CSS file. 4. Create a new class that inherits from CompositeControl. This control will add the javascript and CSS references into our projects. Override the OnPreRender method and populate the calling Page’s header with the links to our two files. protected override void OnPreRender(EventArgs e) { // Base Code: // Include JavaScript for tiled background support. string javascriptInclude = Page.ClientScript.GetWebResourceUrl(GetType(), “Resources.IEPngFix_tilebg.js”); var jsLink = new HtmlLink { Href = javascriptInclude }; jsLink.Attributes.Add(“type”, “text/javascript”); Page.Header.Controls.Add(jsLink); // Include Css file that calls HTC. string cssInclude = Page.ClientScript.GetWebResourceUrl(GetType(), “Resources.IEPngFix.css”); var cssLink = new HtmlLink { Href = cssInclude }; cssLink.Attributes.Add(“rel”, “stylesheet”); cssLink.Attributes.Add(“type”, “text/css”); Page.Header.Controls.Add(cssLink); base.OnPreRender(e); } That’s it. Build and add the new control to your project. You can then add a new forms page and drop the control into the page. I prefer, however, to keep a “DefaultPage” and inherit my pages from it—add once, apply to all.🙂 protected void Page_Load(object sender, EventArgs e) { Page.Controls.Add(new IEPngFix()); } Here we can see the rendered control. The PNG has a transparent background and without IEPngFix shows up as a white box rather than seeing the black background of the page. Works like a champ! Thanks again to Angus Turnbull for this excellent behavior! Changing AnkhSVN 2.0 Released – How’s it look? When I first started using Subversion full time for all of my personal projects, I stuck with the VisualSVN server and AnkhSVN as a Visual Studio client. Both were free, easy to install, and easy to use. However, after a few weeks, the AnkhSVN client could almost be called “annoying.” It trampled over the existing SCC plugins for SourceSafe (for work) and made a mess out of several of my project uploads. I ended up going back to using TortioiseSVN and doing everything through Explorer. When AnkhSVN 2.0 was released, I figured I’d give it another shot. The site claims quite a bit—including several unique additions: - All of those look great—especially the SCC package and changes window. But how does it compare once installed? After installation and starting up VS2008, everything looks normal. Brief Look Pending Changes Window The new pending changes window is FANTASTIC—much improved over the old 1.x versions. I did run into a snafu when trying to resize the window where the scrollbars didn’t update on the screen; however, I’m not sure if it’s a VSS or AnkhSVN issue. SCC Package Under Options > Source Control, AnkhSVN shows up just like it should. What does boggle me is that all of the Subversion commands and menus are available no matter what—even when the VSS SCC is enabled. It still has the stink of VSS and SVN trying to step on one another (“pick me! control your project with me! no, I’m better! pick me!”). Log/History Viewer I really like the new history viewer. It’s clean and easy to read; however, if you change the options at the top—there doesn’t appear to be a way to “change it back” and see the history again, close the view and review. Annoyances - Opening a project from Subversion (File > Subversion > Open from Subversion) will open a project just fine, copy it down, but never opens it. You have to go back and open the solution after it’s created the local structure. Not huge, but annoying. - When viewing history; you cannot view the history of a single file (that I’ve found) in the Repository Explorer. I’m still planning to give it a whirl for the next couple of weeks and see what happens. Hopefully over a couple weeks I’ll have more time to code—it’s been a busy July so far! FIX:. Adding Multiple System Monitors ala Perfmon I use Perfmon a LOT. The logging and diagnostic software provided to us is, well, it’s just not that great. Very slow to use and get around and every time I want a specific counter, I have to go ask for it because it’s someone’s “job” to add those. Ugh. That’s no way to live. Until now, I typically have a Perfmon console for each of my major application and SQL servers. Why? Because I was never smart enough to figure out how to add additional System Monitor controls into a single performance console. Well, now I figured it out! - File > Add/Remove Snap-in - Click Add… - Select the ActiveX Control - A Wizard will start; scroll down and select System Monitor Control - Give your new counter a name! - Repeat this until you’ve added your servers. From there, configure each System Monitor control as needed. From here, you can either add counters manually or use this brilliant PowerShell script. FireFox 3.0 Release Candidate 1 Hits the Wire I’ve moved from the last beta up to release candidate 1 of FireFox 3 and am quite impressed. You can read all about the latest version here. FireFox opens up just as quick (if not quicker) on first run than IE 7 (on Vista). NoScript, the latest del.icio.us, IETab, and Adblock Plus all work like a champ. I also like the very compact theme that they’ve packaged with RC1–-Strata. The coolest “tip” that I’ve found is the “Undo Close Tab”—did FireFox 2 have this? I need to look sometime. In the tab bar (when tabs are open or if you have it visible all the time), the “Undo Close Tab” reopens and rebrowses to wherever the last … well, closed tab was… brilliant for those times you accidently close the wrong tab! I’ve browsed around a few dozen sights, dinked with some of the AJAX idea sides, and so far so good regarding rendering. I’m pleased with this release so far.🙂 TIP : Extracting Files from an MSI File Ever had an MSI file that you needed a library or something out of, but didn’t want to install it? Amazingly enough, you CAN get to those files. The Windows Installer (msiexec.exe) can be ran at the command line to extract files directly using an administrative install. How? msiexec /a “YourMSIPackage.msi” /qb TARGETDIR=”DRIVE:\YourTargetPath” Switches used: /a – Administrative installation /qb – Basic UI (simple GUI progress bar) This is a lot easier than hacking it using WinRAR.🙂
https://tiredblogger.wordpress.com/category/windows-xp/
CC-MAIN-2016-44
refinedweb
1,398
67.25
Project Euler #17: Number to Words Project Euler #17: Number to Words + 13 comments Thanks all for discussion! I want to share some hints, that helped me to complete this challenge. All of them were mentioned in the discussion. - Test yout code against powers of 10: 10, 100, 1000 etc - Make sure you have not misspelled some numerals (e.g. four, forty which are correct) - Test your code against 'border' cases (e.g. 10000000010) - Make sure your have included border case for 0, which is 'Zero' (as i found out it was not in the test cases, but it is right way to do) Again much thanks to all people participated in discussion, the thread was really helpful. All of aforementioned items are a summation of the thread. + 7 comments For non native English people: 0 - 19 "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten","Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" 20-90: "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" 1000-1000000000 "Thousand", "Million", "Billion", "Trillion" + 1 comment A C solution: #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> char digits[20][10] = {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; char tens[11][10] = {"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; void word(int num){ if(num/100) printf("%s Hundred ", digits[num/100]); if((num%100) < 20 && (num%100) > 0) printf("%s ",digits[num%100]); else if((num/10)%10){ printf("%s ", tens[(num/10)%10]); if(num%10) printf("%s ", digits[num%10]); } } int main() { int t; scanf("%d", &t); while(t--){ long long int num; scanf("%lld", &num); int tn = num / 1000000000000; int bn = (num / 1000000000) % 1000; int mn = (num / 1000000) % 1000; int th = (num / 1000) % 1000; int hd = num % 1000; //printf("%d %d %d %d %d\n", tn, bn, mn, th, hd); if((tn + bn + mn + th + hd) == 0) printf("Zero"); if(tn){ word(tn); printf("Trillion "); } if(bn){ word(bn); printf("Billion "); } if(mn){ word(mn); printf("Million "); } if(th){ word(th); printf("Thousand "); } if(hd){ word(hd); } printf("\n"); } return 0; } Please note that spacing is big issue. So place only one space after every word. Also remove all leading and trailing spaces. Sort 73 Discussions, By: Please Login in order to post a comment
https://www.hackerrank.com/contests/projecteuler/challenges/euler017/forum
CC-MAIN-2022-05
refinedweb
395
58.92
From Python to Rust: Part 3. In our last article we looked at how we can use Strings in Rust to store Genome data (DNA sequences). We will be using Strings extensively in our future code as they are very convenient when it comes to storing and manipulating DNA/RNA data. In this article we are taking a look at one more, very important data structure that we are going to need for more advanced algorithms. After we compare both Dictionaries (Python) and Hash Maps (Rust), we will implement a DNA reverse_complement function. Segment 1: Dictionary and a Hash Map Let’s create two new files called data_structures in each folder (Python/Rust), and add an empty functions: For Python, we create a function dicts() and for Rust, we have _hash_maps() as that is what those data structures are called. Let’s start by taking a quick look at Python Dictionary, so we have a reference point for our Rust Hash Map version. def dicts(): test_dict = {} test_dict['Key_1'] = 'Value_1' test_dict['Key_2'] = 'Value_2' test_dict['Key_3'] = ['Value_1', 'Value_2'] print(test_dict['Key_1']) if test_dict['Key_3']: print(test_dict['Key_3']) print(test_dict['Key_3'][1]) for key, value in test_dict.items(): print(key, value) This is very easy, right? On the line 2 we create an empty dictionary and on lines 3-5 we add Key-Value pairs. Line 5 adds a List as a Value. On the line 7 we print the Value that ‘Key_1’ is pointing at, which is a string ‘Value_1’. On the line 9, we make sure that our ‘test_dict’ has a key ‘Key_3’, and if yes, we print its Value. In this case, Line 10 will print a List and the line 11 will print the second value of the list ‘Value_2’. And the last part is a For loop which accesses ‘items’ of our dictionary, which are Key-Value pairs, iterates through them and prints out both. If we now call this function in our main.py file, we should see this output: Now let’s see how we can replicate this in Rust: use std::collections::HashMap; fn _hash_maps() { let mut test_hm = HashMap::new(); test_hm.insert("Key_1", vec!["Value_1"]); test_hm.insert("Key_2", vec!["Value_2"]); test_hm.insert("Key_3", vec!["Value_1", "Value_2"]); // println!("{}", test_hm["Key_1"]); println!("{:?}", test_hm["Key_1"]); if test_hm.contains_key("Key_3") { println!("{:?}", test_hm["Key_3"]); println!("{:?}", test_hm["Key_3"][1]); } for (key, value) in &test_hm { println!("{} {:?}", key, value); } } On the line 1 we are including a HashMap module as it is not included in Rust by default, unlike Vectors. On the line 4 we create an empty Hash Map (a dictionary in Python). On lines 5–7 we insert 3 Key-Value pairs the same way as in Python, but in Rust we need to call ‘insert’ method on our Hash Map. If we want to add a Vector with multiple values, like we do on the line 7, we need to make a Vector a default Value type for the whole Hash Map. This is even if we add a single Value like we do on lines 5 and 6. Line 9 is there but is commented out. You can see that we are trying to print a Value that has a Key “Key_1”, using ‘{}’. This will generate the following error: error[E0277]: `std::vec::Vec<&str>` doesn't implement `std::fmt::Display` --> src/dna_toolkit.rs:24:20 | 24 | println!("{}", test_hm["Key_1"]); | ^^^^^^^^^^^^^^^^ `std::vec::Vec<&str>` cannot be formatted with the default formatter | = help: the trait `std::fmt::Display` is not implemented for `std::vec::Vec<&str>` = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead = note: required by `std::fmt::Display::fmt` = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) Amazing that the Rust compiler not only tells us that something is wrong but also suggests a fix. Let’s use {:?} to format our output, which is a Vector in this case. The rest of the code is almost identical to Python. The only difference is in Rust, we use ‘contains_key‘ method to check if a Key is in our Hash Map. Last For loop has the same structure, and does not even require items() method like Python does. Here is the final version: Segment 2: DNA Reverse Complement function Now that we are armed with Dictionaries/Hash Maps, let’s take our existing DNA Reverse Complement function and port it to Rust. In this function we want to map one type of character to another, and given a string, use that map as a translator to generate a new string. We also want to reverse the result before we return it. Let’s go back to dna_toolkit.py/.rs files and add a new function. So here is our Python version: def reverse_complement(dna): """ Generating a complement string and returning reveresed version. """ trans_dict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} complement_dna = "" for nuc in dna: complement_dna += trans_dict[nuc] return complement_dna[::-1] Nice, clean, and easy right? This function accepts a string and returns a string. We just predefine a ‘trans_dict’, translation dictionary on the line 6, which we use as a mapper. On line 7 we create an empty string we will use to accumulate a new set of values in. For loop on line 9 just loops through each character in the string of dna we passed to that function and checks them against the dictionary, and appends a mapped character to the ‘complement_dna’ string. Last line 12 returns a reversed version of ‘complement_dna’. So if we run our code now, we should see this: We pass “ATCG” into our new function, it is being mapped against our mapping dictionary and “TAGC” is being generated. Reversed version is returned, and we see ‘CGAT’ in our output window. Here is ‘Pythonic’ version of the same code. Let’s hope Rust will gain that type of functionality in the future. You could start your own Rust ‘crate’ and replicate this type of functionality and share it with the community. def reverse_complement(self): """ Generating a complement string and returning reveresed version. """ mapping = str.maketrans('ATCG', 'TAGC') return self.seq.translate(mapping)[::-1] Here is the Rust version: fn _reverse_complement(dna: &String) -> String { // Generating a complement string and returning // reveresed version. let trans_hashmap: HashMap<char, char> = [('A', 'T'), ('T', 'A'), ('C', 'G'), ('G', 'C')] .iter() .copied() .collect(); let mut complement_dna = String::new(); for nuc in dna.chars().rev() { complement_dna.push(trans_hashmap[&nuc]); } return complement_dna; } Same as Python, it accepts a string and returns a string. On line 4 we attempt to replicate Python as much as we can. The part after = is an array, so we need to convert it into a collection, copy that collection into a Hash Map and return an iterator. That is why we have those 3 methods after our Hash Map. I suggest you read about these methods here: .iter(), .copied() and here .collect(). Line 9 is a new empty string (from our previous article). Lines 11, 12 and 15 are almost the same as Python. The only difference being that in Rust, we use ‘dna.chars().rev()‘ to loop through reversed set of characters from ‘dna‘ and return a string, while In Python we loop through the normal string, and then we reverse it before returning it. Subtle but important difference. Note, that our mapper ‘trans_hashmap’ is immutable. We can make it mutable and use .insert() method like this: let mut trans_dict = HashMap::new(); trans_dict.insert('A', 'T'); trans_dict.insert('T', 'A'); trans_dict.insert('C', 'G'); trans_dict.insert('G', 'C'); But a static, immutable version should be a faster solution. In this case we have a fixed set of characters that will not change. So the original approach makes more sense. Here is the final result: We need to tweak the value we pass to be printed in Rust. If we try to pass just “ATCG”, Rust will tell us that we are passing a slice ‘str’ but our function is expecting a reference to a string ‘&String’. So we need to convert ‘str’ to a String and pass it by reference. Now let’s finish by using our random DNA generator and look at the final result for both languages: Alright. This is it for this article. See you in the next one. Links - Rust HashMap video #1: - Rust HashMap video #2: GitLab: Recommended Rust programming books: (UK / US) For video versions of these articles, check out my playlist here:
https://rebelscience.club/2020/06/from-python-to-rust-part-3/
CC-MAIN-2020-45
refinedweb
1,412
72.56
The last Ajax feature we will look at in this chapter is remote validation. This is a hybrid of the model validation techniques I showed you in Chapter 29. The validity of a property is evaluated by an action method invoked using an Ajax call at the client. The first step in setting up remote validation is to add an action method to the controller to perform the evaluation. Listing 30-15 shows such a method, which I have added to the RegistrationController class since this is the controller that contains the validation logic from Chapter 29. Listing 30-15. Adding a remote validation action method to a controller using System; using System.Linq; using System.Web.Mvc; using EventRegistration.Models.Domain; using EventRegistration.Models.Domain.Repository; ... No credit card required
https://www.safaribooksonline.com/library/view/applied-aspnet-4/9781430234678/performing_remote_validation.html
CC-MAIN-2018-13
refinedweb
131
50.73
This the third part in a four part series about how to use Python for heart rate analysis. In this part you will learn about how to improve peak detection using a dynamic threshold, signal filtering, and outlier detection. > - Part 1: Opening the data, detecting the first peaks and calculating the BPM; - Part 2: Extracting complex measures from the heart rate signal; - Part 3: Signal filtering, improving detection with a dynamic threshold; - anyway. The data was collected with a simple data logger based on an ATTiny45, as described in another post. Some Theory and Background So far we’ve been over how to analyze a heart rate signal and extract the most widely used time domain and frequency domain measures from it. However, the signal we used was ideal. Now consider this signal: A challenge! This is the other extreme of the signal qualities you will run into. To be honest I cheated and generated this signal by measuring while I was attaching the sensor to my finger (between 0 and about 4000). Immediately after this the blood vessels in the finger need to adapt to being compressed by the sensor (at about 4000-5000), after which the signal becomes stable. At about 7500, 9000 and 12000 I forcefully moved the sensor over my finger to create extra noise. I was surprised at how well the sensor suppresses noise by itself, so well done guys at pulsesensor.com. Although this signal is manually ‘destroyed’ at points, in practice it can will happen that parts of your data contain noise or artefacts. The sensor might move which creates noise, it might not be correctly attached or become detached during the measurement, the participant might sneeze, move, or any other noise inducing factor might interfere. We will see how to deal with this in a few stages: - Getting started, evaluate the result of passing this signal to our algorithm from part two; - Careful: Sampling Frequency; - Filter the signal to remove unwanted frequencies (noise); - Improving detection accuracy with a dynamic threshold; - Detecting incorrectly detected / missed peaks; - Removing errors and reconstructing the R-R signal to be error-free. Getting Started First let’s see how our algorithm from part 2 handles this signal. Download the dataset here. (...) line 37, in detect_peaks maximum = max(window) ValueError: max() arg is an empty sequence Great, it doesn’t. What is happening? Some may have noticed it before, our detect_peaks() function will break in one eventuality: when the heart rate signal goes from being smaller than the moving average, to becoming equal to it without moving above it for at least two data points in a row. The most likely case of this happening is if the signal drops to zero for a period of time. The function will then skip to the else statement and try to detect peaks in the ROI, but no ROI has been marked because the signal never rose above the moving average, so max(window) throws the error because an empty list has no maximum. This happens If you didn’t notice this in the code before, don’t worry, neither did I at first. Now to update the detect_peaks() function: def detect_peaks(dataset): window = [] peaklist = [] listpos = 0 for datapoint in dataset.hart: rollingmean = dataset.hart_rolling] For now also comment out line 19, we will get to this later on. def rolmean(dataset, hrw, fs): mov_avg = pd.rolling_mean(dataset.hart, window=(hrw*fs)) avg_hr = (np.mean(dataset.hart)) mov_avg = [avg_hr if math.isnan(x) else x for x in mov_avg] #mov_avg = [x*1.2 for x in mov_avg] dataset['hart_rollingmean'] = mov_avg And plot again, this time with peak detection: The module is not throwing errors anymore and is detecting peaks, but it is hardly the result we’re looking for. Let’s start by looking at noise reduction to see if we can improve the signal. Sampling Frequency Before getting to signal filtering let’s determine the sample rate of our file. The file from the previous two parts was 100Hz, what about this one? In practice the actual recording frequency may vary with different devices or systems. It can also be (slightly) different than what the devices are rated for. The accuracy of all the calculated measures is dependent on accurately knowing the sample rate, so this is important to check. Even a difference of 100Hz and 101Hz can lead to significantly different results if you combine data from various sources. I usually log either ‘world time’ or ‘time since start of recording’ with every data line for the purpose of calculating and verifying sample rate afterwards. With this it is straightforward to calculate the sampling rate: #Simple way to get sample rate sampletimer = [x for x in dataset.timer] #dataset.timer is a ms counter with start of recording at '0' measures['fs'] = ((len(sampletimer) / sampletimer[-1])*1000) #Divide total length of dataset by last timer entry. This is in ms, so multiply by 1000 to get Hz value #If your timer is a date time string, convert to UNIX timestamp to more easily calculate with, use something like this: unix_time = [] for x in dataset.datetime: dt = datetime.datetime.strptime(Datum, "%Y-%m-%d %H:%M:%S.%f") unix_time.append(time.mktime(dt.timetuple()) + (dt.microsecond / 1000000.0)) measures['fs'] = (len(unix_time) / (unix_time[-1] - unix_time[0])) The sample rate of the file provided here is actually 117Hz! The measures can now be calculated automatically using the determined sample rate. Note that this is not the whole story, apart from sample rate you should also check your data for sampling spread; are all samples spaced evenly apart, e.g. are there no ‘gaps’ or ‘skips’ in the datastream? If your data contains gaps and skips, provided they are only a few samples long at maximum, consider interpolating the missing values before processing. If your sampling rate varies much over time you’re in trouble, use a different datalogging device. Now that we know the sampling frequency more accurately, we can move on to signal filtering. Signal Filtering The first thing you should do when encountering artefacts or noisy signals is try to filter your signal. Why? Because in any real-life measuring situation your signal, whatever it may be, will consist of a signal part and an error part. This is because the perfect sensor does not exist, so it will always pick up interference from sources other than the one you are trying to measure. An example of common interference is power line noise. The AC power from the wall contacts in most countries has a frequency of 50Hz (some, such as the U.S., use 60Hz). This noise is present in many raw ECG-measurements as well. An often used filter to reduce noise is the Butterworth Filter, which is characterized by a very even response to frequencies within the specified range. It acts as a ‘frequency gate’; suppressing frequencies beyond the specified cutoff range, more so as the frequencies move further away from it. This cutoff point is not a hard line. What I mean is that if you set the cutoff frequency at for example 5Hz, a signal of 5.1Hz will still be let through the filter, it will just be slightly reduced in amplitude (or ‘volume’, if that makes more sense). A signal of 10Hz on the other hand will only get through very weakly, if at all. This is also dependent on the filter order, as is illustrated nicely here. Still difficult to understand? Think about it like this: you’re at a party and two people are talking to you simultaneously, leading to a situation where you cannot understand either of them. Now place a filter between you and the two others. The filter will reduce the speaking volume of person 1 without altering the volume of person 2. Now you can understand person 2 just fine. This is what the filter does except with frequencies. Anyway, let’s get to coding and see if the signal can benefit from filtering. First download and open the dataset if you have not done it yet, define the filter using scipy.signal, filter and finally plot the signal. Assuming you’re working with the code from the previous part, define the filter and plot as such: from scipy.signal import butter, lfilter #Import the extra module required #Define the filter def butter_lowpass(cutoff, fs, order=5): nyq = 0.5 * fs #Nyquist frequeny is half the sampling frequency normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='low', analog=False) return b, a def butter_lowpass_filter(data, cutoff, fs, order): b, a = butter_lowpass(cutoff, fs, order=order) y = lfilter(b, a, data) return y dataset = get_data('data2.csv') dataset = dataset[6000:12000].reset_index(drop=True) #For visibility take a subselection of the entire signal from samples 6000 - 12000 (00:01:00 - 00:02:00) filtered = butter_lowpass_filter(dataset.hart, 2.5, 100.0, 5)#filter the signal with a cutoff at 2.5Hz and a 5th order Butterworth filter #Plot it plt.subplot(211) plt.plot(dataset.hart, color='Blue', alpha=0.5, label='Original Signal') plt.legend(loc=4) plt.subplot(212) plt.plot(filtered, color='Red', label='Filtered Signal') plt.ylim(200,800) #limit filtered signal to have same y-axis as original (filter response starts at 0 so otherwise the plot will be scaled) plt.legend(loc=4) plt.show() Now there doesn’t seem to be much improvement in this signal. If you look closely the lines are a little smoother, but there wasn’t a lot of high-amplitude, high-frequency noise there to begin with. It could even be argued that filtering slightly worsens the parts with the lower frequency noise, because there it suppresses the R-peaks a little as well. This is a good example of why you should always plot your signal when you decide to filter it. Filtering the signal changes it, and it is up to you to decide whether this change is for the better. An example of where a Butterworth Filter was very useful, is this noisy signal I worked with in another project: No question this improved the signal enough to process it further. Improving Detection Accuracy With a Dynamic Threshold The first and maybe most obvious way to reduce the incorrect labeling of the secondary peaks is to raise the moving average we use as a threshold. But raise to what level? This will be different for many different signals. We need measures to help determine which threshold level is probably the most accurate. A few simple measures can help, we can: - Look at signal length and count how many peaks there are vs how many we would expect; - Determine and use the standard deviation of RR intervals (let’s call it RRSD). The amount of detected peaks holds valuable information but only works to reject obvious incorrect thresholds. Depending on your application (most of mine are with people sitting still), we can reject unlikely bpm values. For example I reject thresholds resulting in average bpm of <30bpm and >130bpm. In other situations (physical excercise) the threshold can be different. The RRSD tells us something about how spread out the differences between all RR-intervals are. Generally if there is not too much noise, the detection that has both the lowest RRSD that is not zero and also a believable BPM value will be the best fit. RRSD must not be zero because that means there is no heart rate variability, which is a strong indication of mistakes in the detection of R-peaks. This simple approach works because missing a beat will lead to an RR interval that is about twice as big as the average RR interval, while incorrectly labeling a beat will lead to an RR interval that is at most about half as big as the average RR interval, but generally smaller. Both situations lead to an increased RRSD. In essence we exploit the fact that the heart rate signal contains a fairly stable, recurring pattern. To illustrate let’s plot four peak detection rounds in a subselection of the dataset, with the moving average raised by 0%, 10%, 25% and 35% (top to bottom): In the second-to-last plot all R-peaks are detected correctly and nothing has been marked as an R-peak incorrectly. Note that, although the BPM on its own could be valid for all four plots (none of them is an absolute mess), the RRSD strongly points to the plot which is most correct. I say ‘most correct’ because there are situations where some errors will remain no matter how you position the threshold, more on this later. Also note how the missing of a single peak in the last plot already causes the RRSD to increase quite a bit compared to the third one. Now how to implement this? We cannot simply run 10.000 variations, each with a slightly more raised moving average. Apart from that this would cost us severely in overall performance of the algorithm, it would also be very redundant because many iterations would yield the same correct result (and many others the same incorrect result!). A possible solution is to check with intervals, and afterwards evaluate the most likely RRSD and BPM pair, like this: def detect_peaks(dataset, ma_perc, fs): #Change the function to accept a moving average percentage 'ma_perc' argument rolmean = [(x+((x/100)*ma_perc)) for x in dataset.hart_rollingmean] #Raise moving average with passed ma_perc window = [] peaklist = [] listpos = 0 for datapoint in dataset.hart: rollingmean = rol] measures['rolmean'] = rolmean calc_RR(dataset, fs) measures['rrsd'] = np.std(measures['RR_list']) def fit_peaks(dataset, fs): ma_perc_list = [5, 10, 15, 20, 25, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 150, 200, 300] #List with moving average raise percentages, make as detailed as you like but keep an eye on speed rrsd = [] valid_ma = [] for x in ma_perc_list: #Detect peaks with all percentages, append results to list 'rrsd' detect_peaks(dataset, x, fs) bpm = ((len(measures['peaklist'])/(len(dataset.hart)/fs))*60) rrsd.append([measures['rrsd'], bpm, x]) for x,y,z in rrsd: #Test list entries and select valid measures if ((x > 1) and ((y > 30) and (y < 130))): valid_ma.append([x, z]) measures['best'] = min(valid_ma, key = lambda t: t[0])[1] #Save the ma_perc for plotting purposes later on (not needed) detect_peaks(dataset, min(valid_ma, key = lambda t: t[0])[1], fs) #Detect peaks with 'ma_perc' that goes with lowest rrsd Now run and plot on the dataset (timed the entire algorithm so far including loading and preprocessing at about 151ms, single core performance on an i7-4790, so it’s still still pretty quick. Multithreading will speed this up a lot): That is already a lot better. It’s not dropping any correct R-peaks, but there are still a few incorrect detections remaining, and there is also the part from 0 to about 5000 which contains little to no heart rate signal. We will come back to this noisy segment and see how to detect and exclude segments of noise in part 4. For now let’s take out the noisy part at the beginning and see how we can detect and reject outliers. Finding Incorrectly Detected Peaks The last thing to look at is how to detect and reject abnormal peak positions. One way to do this is to make use of the fact that the heart rate changes gradually rather than abruptly. Your bpm for example will not skip from 60bpm to 120bpm in a single beat or vice versa, so let’s make use of that. Again this means returning to RR-intervals. Remember that if a peak is skipped in the detection, or two peaks are marked in stead of one, the resulting RR-interval will be a lot larger or smaller than the average interval. We can set a threshold and mark intervals that exceed it, similar to how we detected the peaks. For the data I collect this is enough. There is, however, one potential complication. If you analyze a very long signal at once, wherein the heart rate changes a lot over time, this can lead to incorrect rejections. Imagine a signal with a gradually increasing heart rate, starting from 60 bpm and ending at 180bpm. This means a steady trend of decreasing RR-intervals, which is indicative of the speeding up of the heart rate rather than mistakes in the detection of R-peaks. By using just thresholds based on the mean RR-interval, this will result in a rejection of the first and last portion of the signal. If this happens in your data you could detrend RR_list first. Using scipy.signal, this is easy: from scipy import signal RR_list = measures['RR_list'] #First retrieve list from dictionary RR_list_detrended = signal.detrend(RR_list, type='linear') However, if your signal contains a period of large increases followed by similarly large decreases in heart rate, you will need to employ other methods. The solution is beyond the scope of this tutorial series, but if you have this problem you may want to use a high pass filter with a very low cutoff frequency. Another way could be to split the signal in to smaller portions (so that the increase and decrease trends are separated), detrend linearly and average the measures. If the smaller portions are not of equal length, be sure to weight the measures before averaging. Naturally, do not calculate any measures with the detrended RR-signal, only use it for the detection of errors in peak marking. Back to outlier rejection. For the thresholds, in practice I’ve found a threshold level of the mean of RR-differences with a band of 250-300ms on both ends works well. Using the previous code and limiting the dataset to [5000:15000] (to exclude the noisy beginning for now), implement like so: RR_list = measures['RR_list'] #Get measures peaklist = measures['peaklist'] ybeat = measures['ybeat'] upper_threshold = (np.mean(RR_list) + 300) #Set thresholds lower_threshold = (np.mean(RR_list) - 300) #detect outliers cnt = 0 removed_beats = [] removed_beats_y = [] RR2 = [] while cnt < len(RR_list): if (RR_list[cnt] < upper_threshold) and (RR_list[cnt] > lower_threshold): RR2.append(RR_list[cnt]) cnt += 1 else: removed_beats.append(peaklist[cnt]) removed_beats_y.append(ybeat[cnt]) cnt += 1 measures['RR_list_cor'] = RR2 #Append corrected RR-list to dictionary plt.subplot(211) plt.title('Marked Uncertain Peaks') plt.plot(dataset.hart, color='blue', alpha=0.6, label='heart rate signal') plt.plot(measures['rolmean'], color='green') plt.scatter(measures['peaklist'], measures['ybeat'], color='green') plt.scatter(removed_beats, removed_beats_y, color='red', label='Detection uncertain') plt.legend(framealpha=0.6, loc=4) plt.subplot(212) plt.title("RR-intervals with thresholds") plt.plot(RR_list) plt.axhline(y=upper_threshold, color='red') plt.axhline(y=lower_threshold, color='red') plt.show() Resulting in: It seems we got all the little buggers. The result is a plot with all correctly detected R-peaks marked green. The incorrect ones are marked red. The generated list measures[‘RR_list_cor’] has the RR-list without those belonging to incorrect peaks in it. In part 4 we will look into how to mark and exclude noise segments and a few other optimizations. Rounding up Now tidy up all code, and also update some functions to accept new variables and insert the peak rejection function. 44 Comments RobinJuly 17, 2017 Hi Paul, Thank you for great tutorial. I have a question about filtering. I have a heart rate data in bmp. But there are unreasonably low and high values of 30 bmp and 200 bmp. Would you please suggest the appropriate filter to get rid of such values. Paul van GentJuly 21, 2017 Hi Robin. Do you have more information about the data? Is it just BPM values? Or do you have raw data that you converted to BPM? WadaaneJuly 21, 2017 Hello, I’m a biomedical engineering student, and I’ve been following this tutorial. I wanted to know if you abandoned the project and that you won’t publish the part 4. Or if you posted it in another website. Thank you, you’ve been so helpful. Paul van GentJuly 21, 2017 Hi Wadaane. Definitely not abandoned! Please keep an eye on the project’s github:. Once I’m past the present deadline drama at work (until about first week of august), I’ll finish the to-do list there first, then publish the tutorial shortly after. BeckySeptember 7, 2017 I’m getting all ‘nan’ values back from the lfilter- will look into this in other places too but any idea on why that might be? It appears that the a and b values I’m getting back from butter are at least floats not ‘nan’s. I also wondered about the message about pd.rolling_mean being deprecated – any reason not to move away from that? Looking forward to part 4!! Paul van GentSeptember 7, 2017 Hi Becky. – Does your data passing through the filter contain NaN’s? I’m not 100% sure but I believe the filter does not tolerate it – You can also check for filter instability As fas ar the deprecation goes: once you feel you understand the code take a loot at the github implementation. I dropped all pandas dependencies for that. You can find a moving average function there. BeckySeptember 11, 2017 Okay great, thank you! AlexSeptember 16, 2017 Hi Paul, Can I use the code provided in the blog post to extract feature from ECG signal? I have processed/downsampled ECG signal and all I want to do is to extract features. Could it be possible with code discussed? Paul van GentSeptember 19, 2017 What are you referring to as “features”? You mean peak locations? Or something else? AlexSeptember 19, 2017 rmssd, sdnn, sdsd etc. Paul van GentSeptember 22, 2017 That is the main purpose of the algorithm. RorySeptember 21, 2017 Hi Paul Your tutorials have been a great help to me. I have recently come across a data set that has very high P waves. This causes lots of false positives. How would you suggest I approach this problem? Paul van GentSeptember 22, 2017 Hi Rory. That depends. If the P-waves are (almost) as high as the R-waves, you might have a problem. If they’re smaller, however, a simple preprocessing ‘trick’ might be to cube the signal first (or use a higher power) to exaggerate the differences between the higher and less high waves. Do you need all the features the algorithm extracts? A simple FFT of the signal might suffice if you need only the BPM. RorySeptember 27, 2017 Yeah the P-waves are about just as high as the R-waves, so squaring does not really help me. Also I have tried FFTs before, but I have a signal sampled at 1000Hz and at least 30min in length (we actually want to work with 24 hour data sets). That is just too much data and my computer freezes. So at the moment I am looking at some non linear methods, like wavelet transforms. Thanks for your input. I appreciate it. Also in your algorithm. After you do the peak rejection. I think you should recalculate the RR-intervals, because at the moment you are just throwing away those portions of the data and if you have many rejected peaks, your overall data set length is reduced. Paul van GentSeptember 27, 2017 You could also think about splitting your data: do FFT’s on smaller portions of data at a time and get the average for the 24 hour period. Wavelet transforms might also definitely be worth checking out, yes! As for the peak rejection: the measures are calculated based on intervals between adjacent R-R pairs (so without rejected peak in between), which is not dependent on data set length. Recalculating the RR intervals would not affect this. However, if there are many rejected peaks, there is a chance that there is more error present in the calculated terms (after all, if in the end 50% of the peaks is used, that means 50% of the variance is not taken into account, which is risky especially for shorter time spans). An estimated quality measure for both the raw signal, as well as for the confidence of the calculated measures, will be implemented in the near future on the github. And in part 4, if I ever get around to that…. RorySeptember 27, 2017 Hmmm yeah a windowed FFT. I’ll try that. Okay I understand. Something you might want to do in part 4 is a kind of validation for your algorithm, where you can use annotated data sets from the PhysioNet database to check the performance of your algorithm. Once again thanks for your input and I look forward to see what you do in part 4 if you ever get to it. Paul van GentSeptember 27, 2017 Thanks, I’ve sent you a mail as well. AlexSeptember 22, 2017 I am waiting for your respone amulyaOctober 11, 2017 hi im trying to detect ecg from an eeg signal does the same hold good Paul van GentOctober 12, 2017 Hi Amulya. As long as you can get a good signal-to-noise ratio, then sure! It doesn’t really matter where on the body you measure the ECG, as long as you separate a decent signal from the background noise. EEG is relatively high frequency compared to normal resting heart rate, with maybe the exception of the Delta waves, which can cross into heart rate frequencies. As long as you have the EEG from an awake and alert individual you should be fine, and can likely filter the EEG frequencies (>4 Hz) out. Let me know if you run into trouble. -Paul amulyaOctober 23, 2017 thanks paul AleNovember 26, 2017 Hey, very cool tutorial! Are you planning to write the last section soon? Paul van GentDecember 4, 2017 Hi Ale. I get this question a lot. Part 4 is actually written mostly. However, as part of my current PhD project I’m writing a paper about the finished algorithm (including an embedded C implementation). As soon as this is published, early 2018 I hope, everything goes online here as well as on Github! AbhishekFebruary 27, 2018 Hi Paul. Great job on your project. Really helpful. I am currently doing a research project on a similar topic and have a small doubt. While calculating Time Domain features from the ECG data, should the time duration of the signal be the same or the number of peak points considered be the same? Any help from your side would be great. Thanks! Paul van GentFebruary 28, 2018 Hi Abhishek. Nice to hear from you. I’m not sure I understand the question completely, could you elaborate a little bit? Also, what kind of project are you performing? I might have some extra tips :). – Paul AbhishekMarch 1, 2018 My project is regarding the association of HRV in Diabetic patients and its importance in Indian Traditional Medicine. My question: I want to compare results (features) from 2 different devices (same sampling frequency) on 2 different datasets. For feature extraction (both time and frequency domain), should the time duration of the original signal (say 5 minutes ECG recording) be the same or the number of RR intervals (say 500 values) be the same? Thanks for replying. Appreciate your help! Paul van GentMarch 1, 2018 Hi Abhishek. That sounds super interesting, good luck! I understand the question now, thanks. In this case I would compare signals of comparable time length, but make sure that if there is noise in one of the signals, you’re not comparing very few vs a lot R-R intervals. Some discrepancy there is fine, but as soon as for example you start to compare 25 RR vs 300 RR you’re in trouble. To be honest I don’t think it matters an awful lot though. Are the heart rate signals time dependent (for example measured simultaneously with the two devices), or is it important to measure for N minutes after a treatment intervention? If not, you can get away with comparing reasonably similar signal lengths in stead of exactly similar. Edit: Regarding frequency domain measures, make sure you use the version from my github. It has some improved stability fixes and speed-ups. – Paul AbhishekMarch 1, 2018 Okay. It’s a silly doubt but thanks for clarifying. I am using parametric PSD estimation. Let’s see how it goes. Thank you! Paul van GentMarch 1, 2018 Keep me updated. No worries, in data science silly doubts often make the difference! Good to think things through completely. NITESH SINGH NITESH SINGHApril 15, 2018 sir can u please tell me how to take timer in data sheet Paul van GentApril 23, 2018 I’m not sure what you mean. Do you have more details? ParisMay 16, 2018 Dear Paul, thank you for your tutorial, it really helped a lot. A question: would you consider 145 an acceptable value for rmssd? I am looking at hrv through ppg in my experiments, I have cubed the raw ppg signal to emphasise peaks, and i’ve increased the moving average by 10%. Still, for a few participants the hrv is around 120-150. The rest vary between 35 and 85 (which are considered acceptable, i think). I’ve noticed that in participants for which I get these outliers, often i detect parts of their raw ppg signal where primary peaks and secondary peaks are not too far from eachother. I’ve tried to power up the raw signal to even pow(rawSignal, 50), but that messes up the “reliable” participants. Since the experiment has 2 conditions (stressful/non-stressful) maybe the outliers can help me detect the non-stressful conditions (where hrv should be higher). What do you think? Thanks again, Paris Paul van GentMay 17, 2018 Dear Paris, You’re welcome! Take a look at the Github as well as it contains some more tweaks and fixes. 145 should not be a normal RMSSD value, from the top of my head I would not expect it to exceed 90-100. Are you seeing a lot of false positives in this case (non-peaks marked as peaks)? If you’re willing, please share a sample of your anomalous data with me so I can have a look: info@paulvangent.com Before using the seemingly anomalous measures as deciding factors in your experiment, let’s have a look at it together to see nothing strange is going on :). Cheers, Paul Carlo RafaelSeptember 15, 2018 Dear Paul, Is it possible to “predict” bpm? palkabSeptember 16, 2018 Hi Carlo. Yes and no. You need to give a little more context. What are you trying to achieve? Carlo RafaelSeptember 22, 2018 can you create a model for predicting heart rate based on the past data? palkabSeptember 22, 2018 Yes you can, but it will not be accurate. For example if I’m sitting on the couch and start running, how will the model know this? I’d say there are too many variables. What are you trying to do it for? Carlo RafaelSeptember 23, 2018 Nothing im just wondering palkabSeptember 28, 2018 Alright. Well the answer is that you can predict almost anything, but you need to capture the relevant variance in order to do so. To make it less abstract: for heart rate you would for example probably also like to measure physical activity, maybe with an accelerometer, and use that as input for your model as well. In a practical example: If I’m sitting on the couch and don’t move much then my heart rate is relatively stable, but as soon as I get up and start walking muy HR will increase as well. If you want to predict that, you need a way to capture me getting up and waking around as well so you can predict the HR increase. Hope that answers your question. – Paul Carlo RafaelSeptember 29, 2018 Oh I see. Thanks paul. Uhm when will you release the part 4 of the tutorial paul ? I think it will really help me for my project thanks palkabOctober 2, 2018 Hi Carlo. It depends on when publication of the papers I’ve written happens. I expect official approval within 10 days, so somewhere then it will come online. Most of part 4 is already written. – Paul Kevin JoseApril 9, 2019 Hi, I’m interested in your work. May I know whether is it possible to find blood pressure and oxygen saturation from heart rate values. If possible could you provide me with the mathematical relation between them or the code to find them? palkabApril 17, 2019 Hi Kevin, Yes there are ways to extract this from the PPG signal. Take a look at the paper here: Cheers Paul ShaneJune 21, 2019 Dear Paul, Thank you so much for what you’ve done, it’s a really useful tutorial for a new guy who’s going to learn DSP using Python. I’ve went through all three toturial and got the results like your image. But now I encourte a tough problem, when I use another group of data, I couldn’t fix it. The problems I concluded such as 1. The new data is 250 Hz, which influence the choice of window size. Can I ask how to choose a suitable window size based on the frequency of a new group of data? 2. The new data has more noise and baseline drift, I tried use Butterworth bandpass filter ([0.5 Hz, 45Hz], order =(2,6)) to clean my data, but it looks like it didn’t work. Can I ask how to properly design a digital filter to remove baseline and noise? 3.The peak detection seems miss sereral point even these point above the moving average value, which imfluence the RR list colection and outlier rejection. I think the previous two problem highly influence the third problem. I am looking forward to your reply. Thank you for your time! Best regards, Shane
http://www.paulvangent.com/2016/03/30/analyzing-a-discrete-heart-rate-signal-using-python-part-3/?replytocom=120
CC-MAIN-2020-24
refinedweb
5,677
63.7
OfxMessageSuiteV2::setPersistentMessage — Post a persistent message on an effect, using printf style varargs, and set error states. New for V2 message suite. #include "ofxMessage.h" \returns kOfxStatOK- if the message was sucessfully posted kOfxStatErrBadHandle- the handle was rubbish kOfxStatFailed- if the message could not be posted for some reason Persistent messages are associated with an effect handle until explicitly cleared by an effect. So if an error message is posted the error state, and associated message will persist and be displayed on the effect appropriately. (eg: draw a node in red on a node based compostor and display the message when clicked on). If messageType is error or warning, associated error states should be flagged on host applications. Posting an error message implies that the host cannot proceeed, a warning allows the host to proceed, whilst a simple message should have no stop anything.
http://openeffects.org/documentation/reference/re91.html
CC-MAIN-2018-26
refinedweb
144
50.87
These three patches (for discussion only, NOT to be applied) implement a mutex system that lets the user limit the number of libguestfs instances that can be launched per host. There are two uses that I have identified for this: firstly so we can enable parallel-tests (the default in automake >= 1.13) without blowing up the host. Secondly oVirt has raised concerns about how to limit the number of libguestfs appliances that can run to prevent this from interfering with their ordinary guests. The mutex is easy to use: You specify a POSIX semaphore file and the maximum number of instances you want to allow to run at the same time, eg: LIBGUESTFS_MUTEX_FILE=/guestfs.mutex LIBGUESTFS_MUTEX_LIMIT=3 export LIBGUESTFS_MUTEX_FILE LIBGUESTFS_MUTEX_LIMIT As long as each handle has the same settings, the limit is applied transparently, with handles over the limit waiting for earlier ones to finish. (These can of course also be set through the API). There is also a way to have libguestfs choose a suitable limit for you, and the system is entirely optional so that *not* setting these variables results in no limits -- ie. the same as current behaviour. Unfortunately this doesn't quite work because the design of POSIX semaphores is a slightly braindead. It's not possible to have the semaphore be automatically recovered if the process crashes. See: As a result when you try to run the tests you'll find that the semaphore count slowly creeps up until the test suite stops running. In any case, POSIX semaphores are annoying in other ways; for example they don't live in the true filesystem, but in their own separate namespace (exposed under /dev/shm). To get around this I'll have to reimplement this using filesystem locks. Rich.
https://www.redhat.com/archives/libguestfs/2013-February/msg00087.html
CC-MAIN-2020-05
refinedweb
294
59.43
Automatic differentiation with dual numbers Project description HyperJet — Algorithmic Differentiation with Hyper-Dual numbers for Python and C++ A header-only library for algorithmic differentiation with hyper-dual numbers. Written in C++17 with an extensive Python interface. Installation pip install hyperjet Quickstart Import the module: import hyperjet as hj Create a set of variables e.g. x=3 and y=6: x, y = hj.DDScalar.variables([3, 6]) x and y are hyper-dual numbers. This is indicated by the postfix hj: x >>> 3hj Get the value as a simple float: x.f >>> 3 The hyper-dual number stores the derivatives as a numpy array. Get the first order derivatives (Gradient) of a hyper-dual number: x.g # = [dx/dx, dx/dy] >>> array([1., 0.]) Get the second order derivatives (Hessian matrix): x.hm() # = [[d^2 x/ dx**2 , d^2 x/(dx*dy)], # [d^2 x/(dx*dy), d^2 x/ dy**2 ]] >>> array([[0., 0.], [0., 0.]]) For a simple variable these derivatives are trivial. Now do some computations: f = (x * y) / (x - y) f >>> -6hj The result is again a hyper-dual number. Get the first order derivatives of f with respect to x and y: f.g # = [df/dx, df/dy] >>> array([-4., 1.]) Get the second order derivatives of f: f.hm() # = [[d^2 f/ dx**2 , d^2 f/(dx*dy)], # [d^2 f/(dx*dy), d^2 f/ dy**2 ]] >>> array([[-2.66666667, 1.33333333], [ 1.33333333, -0.66666667]]) You can use numpy to perform vector and matrix operations. Compute the nomalized cross product of two vectors u = [1, 2, 2] and v = [4, 1, -1] with hyper-dual numbers: import numpy as np variables = hj.DDScalar.variables([1, 2, 2, 4, 1, -1]) u = np.array(variables[:3]) # = [1hj, 2hj, 2hj] v = np.array(variables[3:]) # = [4hj, 1hj, -1hj] normal = np.cross(u, v) normal /= np.linalg.norm(normal) normal >>> array([-0.331042hj, 0.744845hj, -0.579324hj], dtype=object) The result is a three-dimensional numpy array containing hyper-dual numbers. Get the value and derivatives of the x-component: normal[0].f >>> -0.3310423554409472 normal[0].g >>> array([ 0.00453483, -0.01020336, 0.00793595, 0.07255723, -0.16325376, 0.12697515]) normal[0].hm() >>> array([[ 0.00434846, -0.01091775, 0.00647611, -0.0029818 , -0.01143025, -0.02335746], [-0.01091775, 0.02711578, -0.01655522, 0.00444165, 0.03081974, 0.04858632], [ 0.00647611, -0.01655522, 0.0093492 , -0.00295074, -0.02510461, -0.03690759], [-0.0029818 , 0.00444165, -0.00295074, -0.02956956, 0.03025289, -0.01546811], [-0.01143025, 0.03081974, -0.02510461, 0.03025289, 0.01355789, -0.02868433], [-0.02335746, 0.04858632, -0.03690759, -0.01546811, -0.02868433, 0.03641839]]) Reference If you use HyperJet, please refer to the official GitHub repository: @misc{HyperJet, author = "Thomas Oberbichler", title = "HyperJet", howpublished = "\url{}", } Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/hyperjet/
CC-MAIN-2021-21
refinedweb
496
58.89
Created on 2014-09-20 23:50 by rhettinger, last changed 2016-09-09 23:48 by orsenthil. This issue is now closed. The use of urllib for REST APIs is impaired in the absence of a "Accept: */*" header such as that added automatically by the requests package or by the CURL command-line tool. # Example that gets an incorrect result due to the missing header import urllib print urllib.urlopen('').headers['Content-Type'] # Equivalent call using CURL $ curl -v ... * Connected to graph.facebook.com (31.13.75.1) port 80 (#0) > GET /raymondh HTTP/1.1 > User-Agent: curl/7.30.0 > Host: graph.facebook.com > Accept: */* > Patch looks good. Will need similar addition in urllib2 and inclusion of tests. Can you explain how the result is incorrect? >>> f = urllib.request.urlopen('') >>> json.loads(f.read().decode()) {'link': '', 'id': '562805507', 'last_name': 'Hettinger', 'gender': 'male', 'first_name': 'Raymond', 'name': 'Raymond Hettinger', 'locale': 'en_US', 'username': 'raymondh'} Well, the result with loading using json will be same. but without sending Accept */*. The content-type returned is text/javascript; charset=UTF-8 and with sending of Accept */* the content-type is set to application/json; charset=UTF-8 (which is more desirable). > The content-type returned is text/javascript; charset=UTF-8 and with > sending of Accept */* the content-type is set to application/json; > charset=UTF-8 (which is more desirable). Is that a bug in urllib, or in Facebook's HTTP implementation? Frankly, we shouldn't jump to conclusions just because one specific use case is made better by this. Forcing an accept header may totally change the output of other servers and break existing uses. (and besides, the content-type header is unimportant when you know what to expect, which is normally the case when calling an API) The RFC <> says “A request without any Accept header field implies that the user agent will accept any media type in response”, which sounds the same as “Accept: */*”. I don’t understand why adding it should make a real difference. If you really desire only application/json, you should probably include “Accept: application/json” in the request. Otherwise, it would probably be more robust to make your program accept both types. I have come across the same deal with application/atom+xml vs text/xml vs application/xml. I propose rejecting this one, in favour of the caller adding their own “Accept: */*” (or more preferably, “Accept: application/json”) header. What do you think, Raymond or Senthil? > What do you think, Raymond Before dismissing this, we should get a better understanding of why "Accept: */*" is so widely used in practice. Here's what we know so far: * The header made a difference to the Facebook Graph API. * Curl (a minimalist) includes "Accept: */*", Host, and User-Agent. * Firefox includes "*/*" at the end of its list of acceptable types. * Kenneth Reitz's requests module uses "Accept: */*" by default. * The poolmanager in urllib3 uses "Accept: */*" by default and has a comment that that and the "Host" header are both needed by proxies. * I'm also seeing "Accept: */*" in book examples as well. See and According to all the HTTP 1.1 RFCs, having */* at the end means you accept any other content type if none of the higher priority ones are available (otherwise you risk a 406 Not Acceptable error). So that explains why Firefox has */* tacked on. Requests copied from Curl: <>. Similarly, it is in urllib3 “because that’s what cURL had by default”. Brief discussion at <>, where they decided to leave things as they already were. So all roads seem to lead to Curl. Curl’s “initial revision” (Dec 1999) had “Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*”, which was changed to “Accept: */*” in <> in 2004. I don’t see any reasons given. I just left a question on Git Hub about this, so maybe we might get some sort of answer. Wget also includes “Accept: */*”. But it gives no explanations either, and it was present right from the “initial revision” also in Dec 1999 (presumably Source Forge started about then). The Curl programmer replied basically saying there was no scientific reason, but since Curl was previously sending a custom Accept header, it was safer to leave a bare-bones Accept header in than completely remove it. Plus he thought it might be slighly more compatible with websites. Update: After more research, I learned that while 'Accept: */*' should not have an effect on the origin webserver, it can and does have an effect on proxy servers. Origin servers are allowed to vary the content-type of responses when given different Accept headers. When they do so, they should also send "Vary: Accept". Proxy servers such as NGinx and Varnish respond to the "Vary: Accept" by caching the different responses using a combination of url and the accept header as the cache key. If the request has 'Accept: */*', then the cache lookup returns the same result as if the 'Accept: */*' had been passed directly to the server. However, if the Accept header is omitted, the proxy cache can return any of the cached responses (typically the most recent, regardless of content-type). Accordingly, it is a good practice to include 'Accept: */*' in the request so that you get a consistent result (what the server would have returned) rather than the inconsistent and unpredictable content-types you would receive in the absence of the Accept header. I believe that is why the other tools and book examples use 'Accept: */*' even though the origin wouldn't care. Putting it another way: To an origin server, 'Accept: */*' means it can return anything it wants. To a proxy server, the absence of an accept header means in can return anything it has cached (possibly different from what the origin server would have returned). In contract, to a proxy server, 'Accept: */*' means return exactly what the origin server would have returned with the same headers. “Proxy servers such as NGinx and Varnish: . . . if the Accept header is omitted, the proxy cache can return any of the cached responses.” This is not really my area of expertise, but this behaviour is inconsistent with my understanding of how Accept and Vary are supposed to work in general. I would expect a cache to treat a missing Accept field as a separate “value” that does not match any specific Accept value. See <>. Also, what about a server that sets “Vary: Cookie”, to send a response that depends on whether the user has already seen the page. Do these NGinx and Varnish caches respond with a random response if Cookie is missing? I still think if you care about the media type, it is better practice to specify what types you want with a more explicit Accept value. And if you don’t care about the media type, the NGinx/Varnish behaviour may not be a problem anyway. So, leaping in on the Requests side of things for a moment, two notes. Firstly: copying curl is rarely a bad thing to do, especially for a behaviour curl has had for a long time. However, in this case the stronger argument is that just because the RFCs say that Accept: */* is implied doesn't mean it can safely be omitted. In practice, origin servers behave unexpectedly when the header is omitted, and in general behave more predictable when it is emitted. For that reason, it should be added by Python's standard library. HTTP/1.1 is a protocol where "as deployed" means much more than "as specified", sadly. I’m still not convinced. But my argument about the user specifying Accept if they care about the media type works both ways, so I am not that fussed if others want to make the change. Are there any examples of servers that behave worse than the application/json vs text/json example? E.g. returning XML vs JSON or something? New changeset e84105b48436 by Raymond Hettinger in branch '2.7': Issue #22450: Use "Accept: */*" in the default headers for urllib I fully second Corey's comment. New changeset 00da8bfa2a60 by Raymond Hettinger in branch '3.5': Issue #22450: Use "Accept: */*" in the default headers for urllib.request @Martin, I weight in 'curl's behavior for de-facto things that differ slightly from standards. It's simply what folks have gotten used to, and sometimes expect. @Raymond, unit-tests will be a good addition too.
https://bugs.python.org/issue22450
CC-MAIN-2020-29
refinedweb
1,401
63.9