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 |
|---|---|---|---|---|---|
Introduction of C#
C# has been developed by Microsoft Corporation within the .NET team, and approved as a standard by ECMA and ISO/IEC later. C#, which is one of the programming languages designed for the Common Language Infrastructure, is intended to be a simple, modern, object-oriented and common-purpose programming language
There are some fundamental elements that all C# executable programs have and that’s what the C# programmer need to understand. After reviewing the code in below, I’ll explain the basic concepts that will follow for all C# programs we will develop.
// Namespace Declaration
using System;
// Program start class
class Hello
{
// Main begins program execution.
static void Main()
{
// Write to console
Console.WriteLine(“Hello to All C# Programmers”);
}
}
First of all, we should talk about case-sensitive of C#. The word “Main” is not as same as its lower case spelling, “main”. They are different identifiers.
The namespace declaration, “using System;”, indicates that we are referencing the System namespace. Namespaces contain groups of code that can be called upon by C# programs. With the “using System;” declaration, we are telling the program that it can reference the code in the System namespace without pre-pending the word System to every reference.
The class declaration, class Hello, contains the data and method definitions that the program uses to execute. A class is one of a few different types of elements that the program can use to describe objects. This particular class has no data, but it does have one method. This method defines the behavior of this class.
The one method within the Hello class present what this class will do when executed. The method name, “Main”, is reserved for the starting point of a program. “Main” is often called the “entry point” and if we ever receive a compiler error message saying that it can’t find the entry point, it means that you tried to compile an executable program without a “Main” method. In addition, every method must have a return type. In this case it is void, which means that Main does not return a value. Every method also has a parameter list following its name with zero or more parameters between parenthesis. For simplicity, we did not add parameters to Main., “Hello to All C# Programmers”.
References:
C# Language Reference, Anders Hejlsberg and Scott Wiltamuth
ECMA C# and Common Language Infrastructure Standards | http://blog.beamstyle.com.hk/2010/09/ | CC-MAIN-2019-09 | refinedweb | 399 | 55.64 |
().
Please note that this way you will get the latest development sources of Gengen, and
autoconf in order for this to
succeed.
if (i < 10)
printf("the value of i is %d", i);
It is not so difficult to write this piece of C++ code:
cout << "if (i < 10)" << endl;
cout << " printf(\"the value of i is %d\", i);" << endl;
or the C code:
printf("if (i < 10)\n");
printf(" printf(\"the value of i is %%d\", i);\n");
provided that you remember to escape the
" (and in the
C code, also the
%).
Suppose now that the previous piece of code has to be generated many
times by your program, and every time instead of
i another
symbol has to be generated (decided at run time). In this case,
supposing that this value is contained in a variable
symb,
the code for generating this code would be a little bit more
complex:
cout << "if (" << symb << "< 10)" << endl;
cout << " printf(\"the value of " << symb << " is %d\", "
<< symb << ");" << endl;
And the C version would be even more obfuscated.
Probably you didn't even realize that you forgot to leave
a space before the
< 10; basically this is due to the fact
that this piece of code mixes the code that has to be generated
with the code that generates it, and this tends to make this part
of program less easy to maintain. Especially if some day you
have to change the code that has to be generated, you'll have
to act on this part of the program, and probably you'll have to
execute some tests in order to be sure that you did it right.
If the code that you have to generate is a slightly more complex, the task may easily become a pain in the neck!
Wouldn't it be nice if you could write the code to be generated in a separate file, let's call it template, say test1.cc_skel this way
if (@i@ < 10)
printf("the value of @i@ is %d", @i@);
and have a tool that generates a generator, that you
can instantiate at run-time with the value that has to be substituted to
the parameter
i? If such a tool existed, and it generated
a file test1_c.h with a C struct
test1_gen_struct, then
you could write simply this code, in another file, say
test1_gen_c.c:
#include <stdio.h> #include "test1_c.h" int main() { struct test1_gen_struct gen_struct;
gen_struct.i = "foo";
generate_test1(stdout, &gen_struct, 0);
printf("\n");
gen_struct.i = "bar";
generate_test1(stdout, &gen_struct, 0);
printf("\n");
return 0;
}
Alternatively, if it generated a file test1.h with a C++ class
test1_gen_class, then you could write simply this code, in
another file, say test1_gen.cc:
#include <iostream> using std::cout;
using std::endl;
#include "test1.h" int main() { test1_gen_class gen_class; gen_class.set_i("foo");
gen_class.generate_test1(cout);
cout << endl;
gen_class.set_i("bar");
gen_class.generate_test1(cout);
cout << endl;
return 0;
}
and when you run it you would obtain the expected output:
if (foo < 10)
printf("the value of foo is %d", foo);
if (bar < 10)
printf("the value of bar is %d", bar);
Well, Gengen does right this! Now the code that has to
be generated and the code that generates it are separated and they can
be maintained more easily: if you want to change the code that has to be
generated you act on the file test1.cc_skel; alternatively, say
you need to change the value that will be substituted for
i, you
just change the file test1_gen.cc or test1_gen_c.c.
Notice that the method
generate_test1 accepts an output stream
(indeed in this example the standard output stream
cout is used),
thus the stream abstraction facilities can be exploited. Similarly, the
C function
generate_test1 accepts a
FILE*, so you can use
the C file abstraction.
Indeed in order to generate the C++ file test1.h with the class
test1_gen_class, I simply had to run the following command:
gengen -i test1.cc_skel --file-name test1.h --gen-name test1
and in order to generate the C file test1_c.h with the structure
test1_gen_struct, I simply had to run the following command:
gengen -i test1.cc_skel --file-name test1_c.h --gen-name test1 \
--output-format=c
If I caught your attention and you would like to know more about these options and more advanced features of Gengen, I hope you read on :-) | http://www.gnu.org/software/gengen/ | CC-MAIN-2014-52 | refinedweb | 728 | 67.69 |
Overview
DB2 reaches a wide audience of developers covering both the .NET and J2EE™ platforms. These developers have their own strong preferences in terms of application development API's and application development tools. IBM has always recognized the importance of these two camps and catered to both their needs.
For Windows® Java™ developers, IBM has a strong offering in terms of JDBC™ and JCC drivers, standalone DB2 Development Center, and the integrated plug-ins for the WebSphere® and Rational Studio® IDE's.
For .NET Windows developers, IBM has recognized the strong demand for a tighter level of integration into that environment. IBM is strongly committed to the .NET platform, specifically Visual Studio .NET, where it has been part of the Microsoft Visual Studio Integrator Program (VSIP) since early 2002. IBM has delivered a native .NET managed provider and a tightly integrated set of tools for the Visual Studio 2002 and 2003 IDE's.
This article focuses on IBM's current .NET support on the Windows client platform.
Integration features
Some of the main integration points on the .NET platform and Visual Studio .NET include:
- DB2 .NET Managed Provider - The native DB2 .NET managed provider enables application developers to build and run applications using the standard ADO.NET programming model. This native provider provides an improved level of support over the ODBC and OLE DB generic managed providers for DB2.
- Solution Explorer - The DB2 database project templates allow for script-based development as part of the standard set of Visual Studio solutions supporting multi-configuration, source control management, project, and project item build order, as well as editing and debugging of SQL scripts using the built-in editor and debugger.
- Server Explorer - The IBM Explorer provides the same look and feel as the Visual Studio server explorer, enabling catalog access and rapid .NET application development using drag-and-drop functionality.
- SQL Wizards - The rich set of easy-to-use wizards allows for the creation of new server-side tables, views, indexes, triggers, procedures, and functions from either the Solution Explorer or the Server Explorer.
- SQL Editor - The built-in Visual Studio text editor has been extended to provide native support for DB2 SQL scripts having "intelisense" and syntax colorization as well as advanced script options.
- SQL Debugger - The built-in Visual Studio debugger has been extended to provide debugging support for DB2 SQL routines, allowing for source level debugging of cross-platform SQL stored procedures as part of the DB2 database project.
- Dynamic Help - The Visual Studio context-sensitive help has been extended to provide online help for the DB2 .NET managed provider and the Visual Studio AD tools.
- DB2 Tools Toolbar - The various DB2 development and administration centers may be launched directly from the Visual Studio IDE using the DB2 Tools toolbar.
Availability
The DB2 AD Tools for Visual Studio .NET were shipped initially as part of DB2 and DB2 Connect V8.1.2. The functionality described here is part of the DB2 and DB2 Connect V8.2, which was released in October of 2004.
Platform support matrix
The following table helps to illustrate the level of support for each of the DB2 server platforms. Note that the distributed column refers to the Windows and UNIX® server platforms.
Table 1. DB2 platform support matrix
IBM Informix database support (IDS)
IBM Informix® .NET native data provider is shipped with IBM Informix Client SDK. Version 2.90 of the SDK contains limited tooling support for the IDS .NET managed provider. The Data tab of the Visual Studio ToolBox is extended to list the IDS ADO.NET objects. You can drag and drop these objects on your win and Web form containers. You can also customize these objects using custom editors.
When you install the IDS client SDK, the .NET managed provider and the Visual Studio tooling are automatically installed and configured.
IBM DB2 Everyplace support (DB2e)
There are two versions of the DB2e managed provider, namely,
Data.DB2.DB2e, which runs on the .NET
Framework, and
IBM.Data.DB2.DB2e.CF, which runs on the
.NET Compact Framework.
Basic RAD tooling is provided for the
Data.DB2.DB2e provider only since
V8.1.4. This tooling provides integration with the VS.NET Data Toolbox where the
developers can set properties of the DB2e ADO.NET objects such as
DB2eConnection,
DB2eCommand,
DB2eDataAdapter, and so on.
DB2 managed provider
The DB2 .NET managed provider allows for data-centric application development using the standard ADO.NET programming model. Although .NET developers have the choice of using the ODBC, the OLE DB, or the native provider to develop their DB2 applications, the native provider should be your first choice when it comes to RAD tooling and performance.
Provider object model
Like all the other ADO.NET providers, the DB2 managed provider implements the same
set of standard ADO.NET classes and methods. These classes are defined under the
IBM.Data.DB2 namespace.
Figure 1. DB2 ADO.NET object model
The main set of classes includes:
DB2Connection- The data connection class enables you to specify the connection string used to connect to your target DB2 server. Connection pooling is enabled by default. The open and close method calls may actually translate into reserving and releasing a live connection from the application connection pool.
DB2Command- The command object allows for executing any supported SQL statement or stored procedure using a data connection object. Command execution also supports an optional timeout value.
DB2DataAdapter- The data adapter object contains the four optional commands for the select, insert, update, and delete operations, which may be SQL statements or stored procedure calls.
DB2DataReader- You typically use the DB2DataReader for fast forward-only access to disconnected result sets that are returned from executing SQL statements or stored procedure calls.
Performance implications
As stated earlier, although you have the choice of using the ODBC or OLE DB providers, the .NET native provider will yield the best performance due to the elimination of the extra ODBC, OLE DB layers on top of DB2.
The lab has done internal performance testing of the three supported managed providers where we tested data retrieval of two different row sizes with varying number of rows. The results clearly showed that the native DB2 .NET managed provider gave the best performance numbers.
Some of the performance enhancements that were included in the DB2 .NET managed provider include MTS support, loosely coupled transactions, delayed enlistments, and others.
Figure 2. DB2 Providers Performance
Scripting wizards
One of the key new enhancements for the DB2 V8.2 Development Add-In is the set of functionally rich scripting wizards for generating the required CREATE DDL for tables, views, triggers, indexes, stored procedures, and functions.
Wizards overview
There are two integration points for launching the DB2 scripting wizards; namely, from the DB2 Database Project in the Solution Explorer view, and from the DB2 Data Connection in the IBM Explorer view.
The scripting wizards guide you through the steps required to customize the generated DDL and SQL statements for creating new DB2 schema objects and routines.
When the wizards are launched from the IBM Explorer, you can execute the generated DDL directly, or optionally add it to a new or existing DB2 database project.
When you launch the wizards from the Solution Explorer, the generated script is added to your DB2 database project for later compilation or project build. The DB2 scripting wizards give you a great advantage over the generic Database Project for SQL Server.
Table wizard (and import dialog)
The table wizard allows for generating the
CREATE TABLE DDL for the DB2
family of servers. You can specify advanced value options (identity, generated, and
so on), unique keys, foreign keys, primary keys, and check constraints.
One key feature of the table wizard is the ability to import column definitions for other tables and views in the data connection using a common import columns dialog that is also used by a number of other add-in wizards and dialogs. This feature allows for the ability to clone tables as well as define the foreign key columns.
Index wizard
The index wizard allows for defining the
CREATE INDEX DDL for the DB2
family of servers. You can specify advanced options on the index as well as define
multiple columns in the same index with ascending or descending order clause. The
wizard automatically detects the column definitions of the base table being indexed.
Trigger wizard
The trigger wizard allows for defining the
CREATE TRIGGER DDL for the
DB2 family of servers. You can create triggers for tables and views where the table
and view definition is automatically detected. Instead Of triggers are also
supported. You can customize all of the trigger DDL options including the when to
trigger, the frequency, and the action to name a few.
View wizard
The view wizard allows for defining the
CREATE VIEW DDL for the DB2
family of servers. You can use the built-in schema intelisense support to easily
define the required SQL query for your view.
SQL procedure wizard
The SQL stored procedure wizard allows for defining the
CREATE
PROCEDURE DDL and routine body for the DB2 family of servers. You can
define zero or more result sets, automatically discover or import parameters, and
use the schema intelisense to code the routine body. The wizard also allows you to
specify the advanced SQL build options for z/OS SQL stored procedures or use the
connection level default build options.
SQL function wizard
The SQL user-defined function wizard allows for defining the
CREATE
FUNCTION DDL and routine body for a scalar or tabular function for the
DB2 family of servers. The return types as well as any input parameters are
automatically discovered. You can use the schema intelisense to code the body of the
function routine.
DB2 database project
Using the Visual Studio Solutions Explorer you can create one or more DB2-specific scripting projects to manage the execution of your server scripts. The script files may contain any supported DDL, DML, and DCL SQL statements.
Project overview
DB2 database project
The DB2 database project is a full-featured Visual Studio project template supporting multiple configurations, compile/build, project build order, source control management and versioning, and startup routines.
You can create new project items using text-based script templates or directly
launch any one of the scripting wizards detailed earlier to generate the required
CREATE DDL for the various DB2 objects.
The full-featured support of the DB2 database project makes it far superior to the limited generic SQL Server database project.
Multiple configurations support
Solutions in Visual Studio support a multi-configuration option where project items may be built with a different set of project and project item properties, depending on the selected configuration.
The DB2 database project fully supports this multi-configuration feature. The build for debug or build for release, which applies to SQL stored procedures on Linux, UNIX, and Windows, makes use of this feature to generate the required debugging information for these stored procedures. Additionally, you could specify a different set of z/OS® SQL build options per configuration and a different target data connection per configuration for compiling your script files. You can thus deploy the same set of scripts from the testing data connection to the production data connection with a simple configuration name switch.
Item build order
The default build order for your project script items is to build them in the order they were added to the project. More often than not, you will require a different script build order based on script dependencies. An example would be the need to first create the set of tables before creating the stored procedure that access them.
You can use the project items build order, a feature unique to the DB2 database project, to define the configuration specific script items build order.
Source version control
As with most other project templates in Visual Studio, the DB2 database project has implemented the proper interfaces for integrating with any configured source control management system such as Clear Case or Visual Source Safe.
SQL editor
The standard Visual Studio .NET text editor and language services have been extended to support the DB2-specific script syntax colorization, data connection schema intelisense, advanced scripting options, and SQL code fragments insertions.
Some of the advanced scripting options includes the ability to specify collapsible code sections (also known as hidden text), compile error ignore, result sets output capture, and platform-specific compilation.
Startup procedure
Using the DB2 database project properties, you can specify the compilation data connection as well as the startup stored procedure and parameter values. This startup stored procedure is invoked when you run or debug the DB2 database project. The default action is to roll back after executing the stored procedure. This can be modified using the user options XML file.
IBM Explorer
The IBM Explorer is a new view introduced to support DB2-specific managed provider
data connections. This view offers greater functionality to the Server Explorer data
connections. This additional functionality did not, however, alter the Server
Explorer RAD programming paradigm.
The IBM Explorer data connections display catalog information using a tables, views, procedures, and functions folders. In addition to these catalog folders, the new data adapters folders allows for defining re-usable ADO.NET data adapters that may be shared across applications and with other team members.
Discovery
When adding data connections, you can add local and remote database connections. Remote connections may be discovered if the DB2 Admin Server is enabled on the server platform. You can alternately add remote connections that have been catalogued locally or by simply specifying the host_name:port_number for the server field.
Multiple named connections and filtering
Using the IBM Explorer, you can add multiple data connections to the same target DB2 server and database each having a unique name. Multiple connections combined with the folder level filters, can be used to project different views on the same database. The filtering capability allows you to reduce the amount of catalog information to what is relevant to your application components.
Caching and refresh
One of the early design goals of the IBM Explorer was to enable developers to work in disconnected mode. The catalog information is cashed locally on the client workstation. Subsequent launch of the Visual Studio IDE will re-use this cached catalog information.
To help users recognize stale data, a time-stamp property is shown at the folder level to reflect the last date and time when the cached information was retrieved. You have the option of refreshing the cache from the server at any time.
Support for tables and views
The tables and views folders may be filtered prior to any catalog data retrieval.
Using these folders you can launch the appropriate wizard to create new tables and
views. You can retrieve table and view data, alter the data, and propagate the
updates back to the server. You can also drop these objects or generate the
CREATE DDL script for them for further editing.
The details view on the tables and views allows you to manage the indexes and triggers for these objects.
You can drag tables and views and drop them on form designers to automatically generate and configure the required ADO.NET component tray objects.
Support for procedures and functions
Procedures and functions folders may be filtered prior to any catalog data
retrieval. You can create new SQL procedures and functions directly from these
folders by launching the appropriate scripting wizard. You can also execute a test
run of these objects. By default, a rollback is issued after the procedure or
function is executed from the IBM Explorer. You can force a commit after the
execution by alter the appropriate value in the
userOptions.xml file.
Additionally, you can drop procedures and functions or view the cataloged source
code for them for further editing.
You can drag procedures and functions and drop them on form designers to automatically generate and configure the required ADO.NET component tray objects.
Re-usable data adapters
The ADO.NET data adapters are powerful data objects in that they encapsulate the insert, update, delete, and query operations. Developers spend a great deal of time defining and customizing these data adapters; however, sharing them among forms, across projects, or among users is next to impossible.
The IBM Explorer data connection has introduced this new folder under DB2 data connection allowing users to define and re-use data adapters. The same set of RAD features may be used to drag and drop these adapters onto win and Web form designers as well as to preview and modify the data retrieved by these data adapters.
Once data adapters are defined in your data connection, you can automatically generate data sets for these adapters and add the data set definitions to your project. This can be done without having to drag and drop the adapter onto your form designer. You can then use your formatted and typed dataset in your application development, including the ability to generate data forms using the data form wizard.
One powerful feature of the re-usable data adapters is the ability to deploy them to the DB2 embedded WebSphere application server or to generate IIS web methods for deployment as web services. This zero-code operation allows for fast deployment of your data connection SQL or stored procedures as Web services.
Another interesting feature of the re-usable data adapters is the ability to import and export one or more data adapters as XML files for sharing with other users or for check-in/check-out into source control management.
DB2 RAD and Visual Studio .NET
The DB2 V8.2 Development Add-In for Visual Studio .NET provides two key application development capabilities; namely, developing server-side schema and logic as detailed earlier using scripts, and developing client-side or middle tier ADO.NET application components using rapid application development (RAD) features.
Drag-and-drop from IBM Explorer
You can drag any of the IBM Explorer schema and logic objects and drop then on your winform and webform designers. The drag-and-drop operation will automatically generate the required ADO.NET connection, command, and data adapter objects and add them to the form's component tray.
Additionally, you can drag and drop your preconfigured ADO.NET data adapters from the Adapters folder of your connection and drop them onto your component tray.
Toolbox controls
When
working with component-based objects, such as a form or Web service designer, you
can drag and drop objects directly from the Data section of your toolbox and drop
them onto the designer canvas. The
DB2Connection,
DB2Command, and
DB2DataAdapter objects are
automatically added to the toolbox when the DB2 .NET managed provider is registered
on your system.
Unlike drag-and-drop from the IBM Explorer, toolbox objects must be configured using the custom ADO.NET editors outlined below for proper operation.
Connection string editor
The connection string editor allows you to configure your component tray
DB2Connection object. The connection string is automatically
generated based on the IBM Explorer data connection you choose and the user/password
entered.
Data adapter wizard
The DB2 data adapter configuration wizard may be used to set the options of your component tray data adapters including the data connection, select command, insert command, delete command, and update command.
The wizard can be used to define commands that execute direct SQL or commands that call stored procedures.
You can also define the shape of your select command, be it an SQL statement or stored procedure call, by either discovering the result set or manually defining the one or more returned result sets.
For stored procedures, you can map the input and output parameters of the stored procedure to the data set source columns as defined in the select command.
Command editor
The command editor may be used to configure
DB2Commands found in the
component tray. The same set of UI elements used to define the various data adapter
commands are used in the standalone command editor. SQL parameters found in your SQL
statement are automatically discovered but can also be manually defined.
Generate data set
Once you have configured your data adapter, you can generate the data set definition that will host your data adapter disconnected result sets. The generate data set dialog allows you to both generate new data sets and include the resulting set data tables in an existing project data set.
Once the data set is defined, you have the option of including the data set object instance in your component tray for rapid data source mapping to form controls in your forms designer.
CLR procedures and functions
DB2 has a long history of supporting a multitude of stored procedure programming languages, including C, Java, Perl, Cobol, and REXX, to name a few. It was only natural to add support for CLR-based stored procedures and functions supporting all of the CLR languages such as C# and Visual Basic.
DB2 released support for CLR stored procedures and functions long before any other
database server, including Microsoft SQL Server. This included engine support where
the CLR procedures and functions are executed, managed provider support using the
DB2Context object, and the Visual Studio AD tools.
A new Visual Studio project template was added to the standard list of C# and Visual Basic projects, namely, a DB2 Class Assembly project. This project template is almost identical to the C#/VB Class Assembly project, but with the added automatic reference to the IBM.Data.DB2 namespace and assembly, as well as the pre-canned class samples for stored procedures. You can use this project template to define multiple CLR stored procedures and functions.
Once
your CLR project is compiled, you can then generate the required DB2 DDL script to
define the one or more CLR stored procedures and functions. The built-in DB2 CLR
Procedure Wizard may be used to automatically detect projects in your solution that
may have candidate CLR procedures. The CLR wizard will then allow you to customize
the generated DDL and data type mapping. Once generated, the DDL script is then
added to a DB2 database project in your solution for later deployment. The project
assemblies are also added to the list of assemblies that must be deployed to the
target DB2 server as part of the DB2 database project build process.
You can manage the list of CLR assemblies to be deployed to your server using the Assemblies menu action on your DB2 database project. You can add, remove, as well as choose the debug versus release version of the assemblies to be deployed.
Once deployed, CLR procedures behave like any other language stored procedures and may be used as part of your applications.
SQL debugger
The integrated cross-language Visual Studio debugger was extended to support the back-end DB2 SQL debugger. You can now step into nested SQL stored procedure calls, set line breakpoints, variable value change breakpoints, as well as modify variable values while executing your database server routine.
The initial debugger support is built into the DB2 database project where you can specify the startup-stored procedure which will be executed in debug mode. This support was limited to the DB2 for Linux, UNIX, and Windows servers.
Moving forward, the debugging support is receiving greater attention where the list of platforms supported will be expanded to include z/OS and iSeries. Additionally, directly launching the debugger from the Server Explorer or as part of a full-blown application debug session is also under investigation.
Online help and user options
There is a rich set of user customization options supported by the DB2 AD Tools for
Visual Studio. Some of these options are exposed directly from the standard Visual
Studio Tools->Options menu under the IBM Tools folder.
Additional options may be accessed directly using the
%APPDATA%\IBM\DB2\vsnet\userOptions.xml file.
When you register the DB2 AD Tools and Managed Provider, the online help for both the tools and managed provider are automatically registered with the Visual Studio built-in help facility. You can access both the dynamic as well as the content-based help. Additional online help may also be found using the DB2 Information Center, which can be launched from the DB2 Tools toolbar.
Resources
- The tutorial DB2 z/OS SQL procedures in VS.NET - build options demonstrates the use of the advanced features of the IBM DB2 Development Add-In for Visual Studio .NET to create and deploy SQL stored procedures from a development environment to a production DB2 for z/OS database environment.
- The tutorial ADO.NET data adapters using DB2 UDB V8.2 procedures walks you through the steps required to build an ADO.NET application that uses SQL stored procedures to select, insert, update, and delete rows from database tables and views.
- The tutorial DB2 Data Bound ASP.NET Form using VS.NET demonstrates how to use the DB2 Development Add-In for Visual Studio .NET to build a rich ASP.NET WebForm in C# using design-time and run-time data binding.
- The tutorial Binding DB2 Stored Procedures to Visual Basic WinForms demonstrates the use of the Visual Basic WinForms project template and the IBM DB2 Development Add-In to create a client application that accesses stored procedures and tables residing in a DB2 UDB for z/OS database. This tutorial also applies to DB2 on distributed platforms.
- The tutorial Developing a VB.NET Federated Application for Microsoft Access demonstrates the use of the ODBC wrapper technology available through DB2 Information Integrator and the IBM DB2 Development Add-In to create a client application that accesses tables residing in a Microsoft Access database. To showcase the ease of using these IBM technologies, we will walk you through the steps required to build a sample application.
- To learn more about DB2, visit the developerWorks DB2 zone. You'll find technical documentation, how-to articles, education, downloads, product information, and more.
- Get involved in the developerWorks community by participating in developerWorks blogs.. | http://www.ibm.com/developerworks/data/library/techarticle/dm-0502alazzawe/ | CC-MAIN-2015-35 | refinedweb | 4,339 | 53.81 |
Let's start off with something special:
Also, it seems like there's a delay for newly created E-Hentai accounts when you try to access sad panda with it. My new account wasn't able to get into sad panda.
this is all assorted stuff i have marked to read
>>108540641
I really need more slutty idols stuffs now (ex: fairy pixies)
Do you have some?
>>108537849
I read this before but that fucking twist still made me laugh. I still liked the "God, I wish they'd all die/No problem!" one better, though.
Speaking of prostitution, anyone knows any good stuff with prostitution where the girls don't enjoy it, but also not where they're forced into it against their will?
>>108540821
i dont sorry, my pc crashed the other day so this is all i have
>>108540880
It's a pity then. You're out of fav slots on exh?
>>108540869
You should read the one with the prof and those tribal lolis. Pic related.
>>108540641
You sure like your bestiality
Is it weird to fap to the same doujin over and over again?
I have concluded my fapping/edging on this doujin 3 days in a row now, I can't stop.
>>108541502
No.
>>108541502
I can't stop cumming whenever re-read this
Is there anything with lolis wearing sexy lingerie?
Can someone make a script that allows you to tag a gallery with like 3 letters? I don't want favorites because I'd basically use it as a "if read" type thing or to know if I've downloaded it before, or need to redownload it since it was lost.
Recommend me some more good slutty lolis FUCK
I've already seen Henreader's stuff and Byuu Byuu Bitch but I don't particularly like the art style
>>108541502
no
i fap to the same tanks all the time
I dont understand. Why do all these links lead to a picture of a panda? Sorry for the newfaggotry
Is there a tag name for when during sex the guy stops, making the girl (who previously didn't want to have sex) beg for more? Do you have good ones of those?
I just found this one. I'm really enjoying it
>>108541502
I've been fapping to Delightfully Fuckable and Unrefined for the past three days.
>>108543109
and I take it you've read all of Higashiyama Show already? He has better slutty lolis than the one you posted. The one with the three guys is my favorite by far.
>>108541168
Link?
Any good healthy recommendations?
How do you guys organize your porn? I just have a couple thousand zipped doujinshi in a single folder.
>>108545451
There is Manga Organizer on githhub.
And I'm developing something like that too.
>>108545501
Me too
I ask this in every thread: anyone got any links with fit girls? For whatever reason no one draws fit girls. It makes me sad.
Quick question
How do I get refcontrol to play nice with sadpanda?
It won't load thumbnails no matter what I do unless I disable it, regardless of settings
>>108546092
I think you need to make exhentai.net send the normal referrer.
>>108544222
You missed one
>>108546181
I have, doesn't change a thing
>>108546030
Dr.P draws some. I can't remember any specific ones off hand, though.
>>108546258
And it's not some other addon like requestpolicy?
>>108544222
>and I take it you've read all of Higashiyama Show already?
I read the manga he did that was a part of.
>>108546331
I'm using request policy but that's not the issue, disabling it makes no difference
If I enable refcontrol, shits fucked, if I disable it's fine
>>108543109
>>108546407
Then you read the one I was talking about, it was "Three Question Marks" and continued in "Garden of Earthly Delights". But his other stuff is good too.
>>108546216
Ah yeah, thanks. Hope there will be enough of that series for a full tank, it's golden.
>>108546876
Nothing comes up when I search "Three Question Marks". Is it only in a larger manga or something?
>>108544222
Saw the first two links you posted but not the third or >>108546216, thanks.
>>108547305
It's a chapter in Japanese Preteen Suite, the same volume Addiction is in.
>>108546030
how fit are we talking about?
>>108546030
>no one
Right, because your fetish is not the most popular means absolutely no one draws it.
Here's one I liked for a start:
There's a muscle tag, but most of it is pretty bad. Try going through tanlines and tomboy tags too, most of good fit girls will fit into at least one of those.
>>108537849
>
>that ending
There is justice on this world.
>>108541502
Nope. Totally normal especially if that particular doujin is of high caliber.
>still fapping to pic related
>>108547904
Are you me? Three times to the main story, twice to the sequel, and I didn't even finish it yet.
Shame there's absolutely no NTR out there that comes even close to this.
>>108547904
I can't stop fapping to this and the sequel.
I intentionally avoid fapping to shit I've already read/watched, but my boner grows stronger every time I read this again.
I think that's the definition of a masterpiece.
>>108547374
Then I must have read it already.
>>108541502
No. When I find something I like I fap to it a few times and move on, but if I really like it I'll keep going back to it.
I can't even count the number of times I came to these.
>>108547975
>>108548021
The dialogue and her internal monologues narrating how she slowly gets corrupted is hot as the raging sun.
>yfw no part 3 because the trio got arrested
This stuff is great.
>>108548415
>Guro
I can't fap to this.
Except for Fatalpulse's for some reason I can't place, and even then it's really light.
>>108548517
Eh, I'm not that into it in doujins. But I fucking love stuff like what Wabaki88 and As109 draws
Is it me or does searching on sadpanda only work half of the time?
>>108548766
Guro's just disgusting to me entirely other than Fatalpulse's stuff, including those. I just can't grasp how someone could fap to maiming like that.
>>108548999
I can't understand how people can fap to being turned into statues.
I can't understand why people fuck cars.
Fetishes aren't supposed to be understood. They just are.
>>108548999
I don't understand it either, but it works for me
I try not to think about it too much
>>108541932
>>108546645
st.exhentai.net maybe? I don't think I see anything else related to exhentai in my whitelist.
Got any good loli gangbang?
>>108549380
>st.exhentai.net maybe?
Elaborate?
Now I bet you're gonna tell me JKP ain't a god
>>108549461
Add st.exhentai.net to the whitelist of refcontrol.
>>108549552
He's one of the only artists who consistently does vomit so I give him props there but most of his stuff is 2extreme4me in one way or another.
>>108549620
That worked
Thank you Anon
>>108548999
Searching works all the time but you have to be precise.
>mfw I can't remember my password nor recover them thus, had to create a new account
>mfw the method of entering sad panda has changed and the newly created accounts will no longer able to gain access to the site straight away
>mfw I don't know what I need to do in order to enter
>>108550157
Tried everything?
Fuck I wish I knew about this earlier.
Even legendary and magnificent equipment for fucking free.
>>108550027
I just searched for one artist and nothing came up and then searching the exact same thing I got results.
Typos aren't a possibility because I searched his name by opening the tag for him in a new tab from the doujin itself.
>>108550253
>All those rules
What is this, the Brawl Club?
>>108550251
Yep, I just can't seem to get my password back.
As for the newly created account, it seems like someone from exhentai made changes to the whole access thing where it looks like new accounts are not able to enter the site straight...
Not sure if there's a cool down period or I need to fulfill certain activities in E-Hentai, I'm not too sure
>>108550510
Write mail to the mods (there's mail address in FAQ).
>>108550510
Same thing happened with me anon. Created an e-hentai account and still got sadpanda. Just wait a couple days and it will all work out.
>>108550811
What about secret secret club?
How do you play off accidentally posting a sadpanda link to people who don't sadpanda?
>>108550590
Not sure if it's a good idea to email them about it directly.
It seems like you get banned for having multiple accounts, which is the case for me right now.
>>108551024
I don't, because I'm not a normalfag like you.
>>108551024
I can't see how that could even happen.
>>108551082
If I recall correctly, they also said that if you don't reconnect on your old account, it won't be considered as multi account.
Confirmation Joe ?
>>108550811
Is this confirmed or are you guessing?
>>108551024
"Someone sent me this link but all I can see is a stupid panda picture. I have no idea what it is, have you ever seen it somewhere before?"
>>108551024
The only 2 sites I visit is 4chan and sadpanda, so I don't think that can happen.
And anyway it's called sadpanda for a reason. Normalfag will see a sadpanda, ask what is it, you say "dunno some panda lol", normalfag fucks off.
The end
>>108551349
"That link says hentai bro"
>>108551537
What is hentai, bro?
>>108550337
Searching for an artist manually and using their tag link are NOT the same thing.
>>108550590
Won't do anything.
>>108551182
Yep. But I try to dissuade people from making new ones just because they can't get to their old ones, it's very wasteful since you won't be allowed to go back.
>>108551394
>implying sad panda isn't full of annoying normalfags
Have you ever been to the forums? Supposedly it's a requirement for getting an access into some galleries, or so this retarded attention whoring tripshit that always lurks these threads claims, but I honestly can't suffer the place.
>>108551537
"Guess so but all I see is a panda picture, I guess the dude who sent it thinks he's taking the piss on me, oh well forget it."
>>108551182
I hope that is the case... Because from what I can remember, I think I had another account, which totals out three E-Hentai accounts.
>first account: created years ago, used it for sad panda, forgot password
>second account: due to forgotten password - created this account months ago (I think), used sad panda till today
>third account: again forgot password for the second account, just created this account and now can't enter sad panda
With this in mind, the first two accounts will never be accessed again because I just don't know the password for them.
That said, holy mother of clusterfuck. I need to get a habit of recording my passwords. I hope the mods understand my situation if they ever find out about my accounts...
>>108551669
Oh, Joe, I wanted to ask.
If there is any to search for artist more efficient, I guess?
For example, if I want to find all works by artist with generic name. e.g. I find works only by that artist. But if I want to make other tags like artist:miyabi engl it shows ALL artist with miyabi in name. Which is a lot of.
Even if you use "artist:miyabi" engl in search it still gives all miybi's artitst.
Is there any way to avoid it?
I don't know why but seeing body modification turns me the fuck on. It even can be somewhat vanilla and I'll become rock solid.
I don't know what it is but seeing cervix/nipple/urethra penetration makes me rock solid.
Shiina Kazuki probably does it the best and his works are vanilla in a sense but John K. Peta is great for mindless sex. Here are some good ones
I'm fucking diamonds right now but I can't fap til my new onahole gets in. I hope other anons can enjoy these in my stead.
>>108551720
The forums are for e-hentai in general, not sad panda.
>>108551669
Hey Joe, I'm not sure if you've read the posts just above yours but is there some kind of "cooldown" before new accounts can gain access to sadpanda?
>>108551720
You only have to make 100~ posts to be included into "sikrit club". Just spam random shit into spam threads for a hour or two and that's all.
Don't see a problem there
>>108552158
It's only 20. And that was hard enough for me with that fucking drivel that goes on there.
>>108552158
There are two obvious problems.
1) You have to suffer the disgusting shithole that is the forum
2) You have to deal with that shit in the first place
>>108551965
Nope. Unless Tenboro implements RegEx on the engine someday...
>>108552103
<
>>108552291
>>108552279
What kind of pussies are you? Can't stand just 20~ minutes of spamming?
You don't need to read anything, just find thread with 10k reply and spam random bullshit there
>>108551829
"You still clicked on it, man. Keep your tentacles away from my little sister, lol"
>>108552406
I don't like to shitpost. Especially not not anonymously.
>>108551024
You sent it to your normalfags acquaintances, or coworkers, didn't you?
>>108552406
It's an issue for me that you have to do that shit.
>>108552390
I never used the search engine much, but that is fucking retarded.
How can you fuck up search that bad?
>>108552527
>>108552557
Well, enjoy not being in secret club and missing 10% of doujins then
>>108552608
But I am in it. As pointed out by >>108552279's past tense.
>>108552608
forgot pic
>>108552608
You can get there without ever posting anything in the forums.
>>108552608
Attitude like yours is why this problem exists in the first place.
>b-b-b-but blogging about your life on a forum is perfectly normal
That's exactly what's wrong with it.
>>108552390
>>108552698
Yeap, but without forum posts your account must be 4 year+ old to be allowed into secret club
>>108552700
Who the fuck demands you to blog about your life? Just spam "lol spam" 20 times and you are in secret club
>>108552911
>Just spam "lol spam" 20 times and you are in secret club
Also banned.
>>108552911
And get my account banned? No thanks.
Also if it's that retarded a requirement, why is it there in the first place? I blame the horsefucker admin, and why you tolerate his bullshit is beyond me.
>Mfw /ss/ guro
>>108553004
As an additional line of defense against normalfags who could happen to find site?
I don't see why you make such a drama from 20 spam posts.
There is also a hentaiverse chat with spam threads. You can spam your game stats there. You get account in game the moment you create account on g.e. anyway
Does a mod have to create a new "Artist" tag for a name to go into the Artist namespace?
it keeps happening
>>108553585
That the new Comic-Han?
>>108553390
Yes. You can suggest them here
>>108553689
looks like it
>>108553585
Sex Sweepers chapter 9 is finally out!
Wonder how long the translation will take without LLP there to translate it.
I kind of know that there isn't, but is there a specific tag for that kind of pose
where the girl puts her hands behind her head exposing her armpits while
bending her legs open and low? if not, can anyone remember some manga
with this pose going on?
We should gather to shitpost together in those horsefucker forums.
>>108553267
But I hate the shitty game.
>>108554002
>>108554002
It happens a shitton in Futanarun. Though obviously it's futanari.
I looking for the artist with the worst art ever.
ALL his girls have literally same face. When there is more than 2 girls it's impossible to tell them apart. And if they at least looked cute. Girls looks like aliens or shit. Super extended sharp noses, almost invisible eyes and shit. Dunno why, but there are also many his works in english.
So the story was like. Some normal school. MC lives with his gf, sisters, mother. Suddenly ugly fat guy with powers transfer to their school. He fuck all girls in there, fuck MC's gf, sisters, mother. In the end he leave mindbroken sluts and transfer to a new school.
The story was in english and it was full book.
I think artist name starts with H, something like hiro I think. Or maybe not
>>108554145
Yes that's what i am talking about, i knew that it's too subtle to have a tag on its own, oh well.
>>108554211
Having some brain problems, m8?
>There are people who dont are part of the triple sekrit club
>>108554327
>There are people who dont are part of the triple sekrit club
There people english speak are
Anyone have anything thats in the secret club so I can check my status? I've been shitposting on the forums for a bit
>>108554327
If it was a secret part things it would redirect to main page.
It just page with mistyped number
>>108554420
You have to wait till the dawn of the new day.
>>108554317
Nah, memory problem
>Mfw I'm in the sekrit sekrit club and have only made two posts on the forums in the five years I've had my account
Requesting footjob doujinshi. It's kind of hard to find translated ones with a decent amount of focus on footjobs instead of just one shitty page. Typically I also aim for good anatomy. Any givers? Here are some whom I probably already fapped to all of said artists:
>>108554618
>in the five years I've had my account
That's the reason. If your account is 4 year+ you will be in secret club even without a single post
>>108554737
No idea why you think it's 4.
>>108553585
I wonder if they'd release chapters early for translators.
>>108554737
3 year old account here, still part of the sekrit club.
>>108554920
Because 4 is death. When you become dead for normalfags you are accepted into secret club
Does the reverse image search in exlinks not work for anyone else anymore? I always get 0 results even for pictures I know are from exhentai.
anyone hav some cute yaoi doujins
idc if shota or regular yaoi, i just want it to be really cute
>>108554997
There are different levels of secret club.
For example, people in secret club could see 360k galleries and people in the secret secret club could see 400k galleries in the thead yesterday. People not in the secret clubs at all could only see like 250k.
>>108555146
The reverse image search for b&w images is not actually a reverse image search, it's just a hash lookup. You can change a single pixel in the image and it will always fail.
As for color images, it does seem to have gotten shittier lately
>>108555337
Either one always gets 0 results.
I am talking about the exsauce thing in the userscript though, not the search in the site itself.
>>108555380
exsauce uses sadpanda's search engine
>>108555437
Yes, but the website search will find the image while the script will not.
>>108555336
That is bullishit. There is 380-90k~ of galleries. 440k if you search expunged.
>>108554920
How much galleries there right now? w/o expunged
>>108555380
I doubt that's an issue with exsauce. That should just upload the exact same image.
This found something on the site.
>>108555487
Its not bullshit. Half the thread yesterday was people posting their personal results.
>>108555477
That's normal, but it should do that only for color images
>>108555487
>That is bullishit. There is 380-90k~ of galleries. 440k if you search expunged.
The search people did was with expunged. It was somewhere between 400k and 440k. It's believable that it now went up to 440k.
>>108555516
>Found: 0
Well shit, it is borked.
>>108555487
Uhhh.... 320,804?
Why is Maximum Joe the worst?
>>108555516
This picture didn't get found by the script OR the search.
>>108555612
>Showing 1-50 of 320,795
We meet again, phantom 9 galleries.
>>108555516
I'm getting no results for this. Goddamn it, anyone knows anything?
>>108555652;monotone&fs_from=05_005.jpg&fs_similar=1
When I download it from exhentai it works, see link above. When I download it from 4chan (which was the same version uploaded), it doesn't.
Fucking 4chan's fucking up images.
>>108555727
>>108555652
>>108555602
I think it was a bait.
>>108555704
Mine is exactly 320,795 too, with 9 mod power.
>>108555727
Nvm, found it.
>>108555727
>>108555602
All the results on the first page of Google Image Search have the title.
Step it the fuck up, senpai.
>>>/d/5495654
This is a color image.
If I search it with exlinks, I get 0 results.
if I search it on the site, I get a couple of galleries.
>>108555768
320,797 with 7 mod power.
>>108555704
>>108555768
You're both on sadpanda, not g.e so there's a delay.
>>108555750
It wasn't. I downloaded, and that worked on exhentai.
>>108555816
It's because the site uses a proper reverse image search for color images.
Exlinks/exsauce on the other hand calculates the image hash and uses it to look for matches, so the site can't do its reverse image search thing
>>108555861
I guess it really is 4chan then.
>>108555859
You said the same thing a few weeks ago, and it was exactly 9 galleries that time too
You can't fool me, rusemaster
>>108555946
I am extremely sure that I used to be able to reverse-search color images with exlinks, too.
>>108555946
Holy fuck anon. I just installed exsauce and this shit is incredibly useful. Thanks m8.
>>108556000
You can't do a reverse image search from a sha1 hash.
You can modify the script so it uploads the image instead of using its hash, but that's about it.
>>108554211
Anyone?
>>108556079
I hope this ends in NTR.
>>108556065
I just searched this >>108556079 and I STILL get 0 results.
>>108556136
It ends in pegging and piss-drinking.
>>108556171
It seems that 4chan's altering the image so the hash is different. A hash search only works with exactly the same image.
>>108556211
Better than NTR
>>108556171
That's because the image has been modified:
3c1fccc1aa76e2c63b7910f21bb290d385f4cc9a *1402259835180.jpg
9022b99687afe5a5750edcbd4cadcafbc407fd0b *img049.jpg
I've tried to upload the original image and it complains that's it's a duplicate, so it's a probably a 4chan problem
Educated guess: mootykins made some changes to the upload mechanism and now it's modifying images somehow, which results in sadpanda's search engine being useless as fuck
>>108556439
Why is it modifying images
What is he doing to our images
Guys this is spooky what if there's a conspiracy going on
>>108556482
Post this on /x/
>>108556482
Someone should send him a mail.
>>108556482
It's fucking disgusting is what. I don't want him to change my images.
>>108556482
I'm assuming it's because people keep embedding files in the images.
>>108556719
Reminds me I haven't seen a sound thread in ages. Has moot beaten them for good now?
>>108556482
YOU HAD BEEN WARNED
WHY DIDN'T YOU LISTEN
NOW IT'S OVER
THIS COULD ALL HAVE BEEN PREVENTED
IT'S ALL OVER
IT'S HAPPENING
>>108556762
Wait hold on let me check.
>>108556762
I have no idea. But I was reading this thread earlier, and apparently people are having some problems
>>>/g/42355178
>>108556821
Nope, still works.
Maybe mods just delete them quicker now.
>>108556821
>>108556893
Yours is broken.
>>108549620
>whitelist of refcontrol
?
>>108556932
Everything is broken for me
>>108556958
Refcontrol options -> add site. The list of allowed site's a whitelist.
>>108556482
It's stripping all metadata from the images now, guess one too many retards forgot to remove exif on their cock photos.
>>108557370
Really? That would be pretty gay.
It doesn't seem to be in effect on /p/ where it would really have a bad effect.
>>108556482
Why is moot so fucking shit.
>>108557752
Because he's a normalfaggot jew.
Ok so I shitposted on the forums, how do I know if I'm in the sekrit club?
>>108557924
Usually you have to wait the next dawn of the day.
On average how many posts do you need to get into the sekrit club?
>>108554729
If you don't mind femdom then try one of these.
>>108558161
around 75-100 depending on your level in hentaiverse.
So when are they going to move Comiket outside of Tokyo so there can still be doujins without lightsaber dick?
>>108558268
Ah fuck. What boards are the easiest to get away with this shit as to not get banned.
>>108558161
20.
>>108558034
Wow, this doujin is part of secret club?
I pity the anons who can't enjoy such joys
Any femdom where it is a futa getting dommed? Only know of one off the top of my head.
>>108558321
Any heavily moderated thread. Make sure to only post the phrase "Shitpost" over and over again.
>>108558347
I'm upset that
>>108558210
>
is now apart of the sekrit club.
>>108558384
Thanks friend :^)
>>108558338
Do you happen to have the horsefucker admin's name and address? Just curious.
IDS HABIDDING
NEW F/SN BY MTSP AT C86
ALSO POSSIBLY THE CONCLUSION OF GREATEST LOVE STORY EVER TOLD
>>108558034
That doujin is retarded.
Guy went to some shit hole 3rd country, got drunk, woke up with some local girl who said that he fucked her and married her?
95% that she is a slut who slept with thousands of local niggers, got pregnant from one of them and decided to try moving to better place by fucking a wealthy guy from wealthy county.
That retard believed her and took her with him
>>108558404
>>[Ex][Teri Terio] My Sweet Neighbor (COMIC Kairakuten 2012-09) [English] [The Lusty Lady Project]
>is now apart of the sekrit club.
It's a shame really.
>>108558689
>>>/pol/ is this way my friend. It seems you are lost. Here logic don't apply the same way it apply in your world.
And this is the reason the 2D world is much better than yours.
Yours,
Anon
>>108548999
>Is it me or does searching on sadpanda only work half of the time?
>>108555998
>You said the same thing a few weeks ago, and it was exactly 9 galleries that time too
>You can't fool me, rusemaster
The problem is that Maximum Joe (vigilante staffer at e-hentai) sometimes answers in lawyer fashion (as some other users have described him in the past). I don't know if he is a lawyer type; I am using their description. But the ultra-precise answers can be misinterpreted on 4chan. Joe, we are not e-hentai forums where the keenest edge separates various meanings and makes the difference between "yes or no" or "true and false"..
Your question is answered precisely in lawyer fashion as "Searching works all the time" even if no results are returned. Joe means the search works because it accepted your input and didn't reject it. The processing is then affected by your status in the e-hentai heirachy (secret flags, power, status, base level, whatever secret effects are applicable), the search terms you used, whether or not secret_club**3 is on for that gallery, etcetera. Joe will now say I am wrong and I am wearing tinfoil conspiracy hat, but I am not those other guys he likes to attack with his patented ad hominem phrases. I'm just a user answer the question and also trying to improve or organize my own incomplete understanding by forcing myself to organize my thoughts into words I can type and read.
>>108556719
>I'm assuming it's because people keep embedding files in the images.
This is most likely. I've looked at the guts of some images and seen messages, URLs, or gibberish encoded binary that is not part of the image. It may be that someone uses 4chan to transmit controls to their bot fleet by embedding data into images. So it would be good if moot stripped that bot fleet control data out.
>>108558840
>I don't know if he is a lawyer type
As in, he doesn't have neither a soul nor a conscience?
>>108558545
babby's first ntr artist
>>108558840
I see Showing 1-25 of 320,800 with 16 power
>>108559074
>MTSP is too mainstream and famous now, therefore I will mock anyone who likes his stuff so everyone can see how much of a unique and special snowflake I am and how acquired my taste in chinese cartoon porn is
Anon please, we're all on the same boat.
Is exlinks broken for anyone else? I'm not getting any of the features.
>>108537849
>made an account
>Also has the firefox plug in
>Gets invalid login whenever I try to log onto the sad panda
why
>>108559074
My babyfirst is "When you let go of my hand"
It's been like 6 years since I read it but I still mad
>>108558513
No.
>>108559304
Someone should bug Daiz.
>>108559326
lol plugin
>>108559406
>lol plugin
how else to make it past the panda then?
>>108559463
Think of it as an IQ test you failed with flying colours.
Anyone happen to know the sister brother bakery doujin? It was translated to english and the dude came on the pies which his mother ate. (dude had mother complex)
>>108559463
you just need to add 2 cookies after logging into your forum account
>>108556439
>it's modifying images somehow, which results in sadpanda's search engine being useless as fuck
Your statement made two assertions: one is that the images are modified (very careless way of stating things) and second is that the e-hentai search is useless with these images.
Firstly:
The viewable visual part of the image you see is not being modified. What is happening is that excess data embedded or hidden into the image is being stripped out.
Secondly:
There are 2 popular types of searches people use on 4chan for e-hentai. There's actually 5 approaches, but you're not a coder (if you were you would not have said what you said) so 3 of them are prolly not being used by you. So, of two easy approaches, one is the tool you click on 4chan threads to search for that image at e-hentai. That uses the low overhead (Tenboro approved) hash code matching. While efficient it often fails with files containing embedded data as I just tested and noted that I didn't get matches with a modded image. You can always use the file search option on the exhentai.org front page and that will match similar looking files regardless of embedded or hidden data being stripped out or not.
At least we don't have a return to those old days where users are urged to download this image, rename it as *.js and add it to your browser (or rename as *.exe and run it) to watch moot shit bricks.
>>108559549
Then I'm off to search for some cookies
>>108559536
IQ test can be tricky
>>108559549
This works, provided your account isn't new.
But if you're not using a browser or a device that supports cookie editing and don't have an account made before sadpanda was made from several years ago you're out of luck.
Why is there the panda there in the first place?. I know the reason I tend to see thrown around the most is "advertisers don't like loli" but there are plenty of sites like Gelbooru and Hentai Foundry that have ads and they allow it.
>>108559703
>You can always use the file search option on the exhentai.org front page and that will match similar looking files regardless of embedded or hidden data being stripped out or not.
Except you can't use the similarity search on black and white images,
>Note: The uploaded file was detected as monotone. Only exact file matches are displayed.
which is why changing the hash makes the engine useless for that kind of images.
>>108559739
>don't have an account made before sadpanda was made from several years ago
How the fuck are you so wron-
>Why is there the panda there in the first place?
Nevermind, just a newfag trying to sound smarter than other newfags.
>>108559703
>The viewable visual part of the image you see is not being modified. What is happening is that excess data embedded or hidden into the image is being stripped out.
So the image is being modified.
And you can't use the file search with any monotonous image that's downloaded from 4chan. Regardless if you use the addon, or the site itself.
>>108559851
>How the fuck are you so wron-
If you're an Americlap. From what I gather Yuropoors can get past it simply by logging in on e-hentai.
>Nevermind, just a newfag trying to sound smarter than other newfags.
You didn't answer the question, one, and two I'm not nwe. The reason I see provided most often doesn't make sense.
>>108559978
I'm an American and I can log in just by logging into e-hentai and playing with cookies a bit.
>>108559978
Your region doesn't matter for the panda (barring ISP interference).
The reason was flat out stated back when it was made:
>>108559739
I made my account last year, you're just dumb.
>>108560044
>and playing with cookies a bit.
That's what I said. I'm an Americlap and that's what I have to resort to too.
I was saying that from what I gathered, if you DIDN'T have your account since before sadpanda was created and if you're not European, simply logging in on e-hentai won't get you past the panda; you have to edit cookies.
I feel really stupid, but anyway, can someone tell me how can i check out my mod power or thatever is the shit i need to acess the sekrit club?
>>108560131
I was saying "advertisers having a problem with it" seems like bull because there are plenty of other sites with loli and shota that have advertisements.
>>108560157
By "new" I meant "within the past few months". Go make a new account and try to get past the panda. Even with editing cookies, it won't work.
>>108560131
>sadpanda was created more than 4 years ago
Where has all my time gone
>>108560264
>By "new" I meant "within the past few months".
Nice back pedaling, what you actually said here >>108559739 was:
>and don't have an account made before sadpanda was made from several years ago you're out of luck
You're just talking out of your ass.
>>108560194
Mod Power is in your My Home area:
>>108560264
Some advertisers. Some.
>>108559549
Having played with the cookies I still have no luck login in. I keep getting "invalid log in" or it just returns me to the log in page
Looking for some good stuff with thick thighs and good corruption. Usually it's like one-page mindbreak and that really strips the satisfaction of them getting corrupted. A nice, slow decline would be nice.
>>108560512
How much mod power does posting on the forums get you? I have never made a single post and wondering how easy it is.
>>108560569
Wrong thread, this is all about meta bullshit instead of posting good porn.
>>108560194
You're not really missing much. A lot of sekrit club stuff can be found via google or just accessed through the torrent tracker provided you know the name of what you're looking for.
As an example, try looking up Power Play by Yamatogawa. You won't be able to find the English Decensored gallery if you don't have Sekrit Club access, but if you search in torrents:
Bam.
>>108560601
>>108560601
Good is relative anon-kun. For example, I'm sure some fag hasn't jacked off to this 20 times yet.
>>108560594
>>108560594
0.03 per one day of activity on forum.
>>108560747
Bah. Not worth it.
>>108560643
I can access the descensored version. Am I in the club?
>>108560512
My browser goes full "This webpage has a redirect loop" when i try to acess My Home
>>108560807
Well, I started posting at the beginning of this year.
Not much point in raising MP above 12 though, but I like big numbers.
>>108561016
Wait, where can I check that?
>>108561131
>>108560131
>(barring ISP interference).
What ISP's interfere?
>>108561016
There a good guide on how to do hentaiverse with the current version? I played a while ago when twohanded was good and supposedly its shit now and I don't know what to do.
>>108561131
check >>108560512
>>108561188
Your internet provider being a douche.
>>108560429
I was referring to two different things; I did make a mistake, I should have used the word "or".
Either you have an account made before sadpanda was made or cookie edit with an account made before the last few months.
>>108561191
>>108561176
Thanks.
Can someone give an example of a gallery that you cant access with out enough MP?
>>108561188
People in South Korea can't see shit.
>>108561191
>>108561294
You're still wrong, I've never had to edit my cookies and I'm post-2010.
>>108561406
>You're still wrong, I've never had to edit my cookies and I'm post-2010.
Are you an Americlap?
>>108560885
Can you see ?
>>108561406
>>108561191
Any build recommendations then? dual wield? Mage? Etc?
>>108561606
Yes.
My mod power is only 6. And how can you even tell which galleries are restricted? I dont really get any of this club carry on.
>>108561484
Canadian. Again, region doesn't affect sadpanda access.
>>108561622
Whatever you like really.
>>108561754
So I was wrong, it wasn't strictly before the split but a while after.
So now I conclude that it's just Americlaps who can't get past the panda JUST by logging in.
We need more lolidom/uncut dicks.
>>108561970
I doubt anybody hasn't seen this yet in these threads, but I just read this and came buckets.
>>108561970
Lolidom?
Next to the one you posted, this is my favorite. It's an odd kind of cozy. Especially the second half.
>>108561685
If you're in, you can't.
If I recall correctly, these are in the club
>>108561970
look here>>108558210
for one of 'em
>>108562182
Okay, I can access them too...pretty sure I'm being trolled. This whole thread, jesus.
>>108562368
Nah there is
(was ?)a secret club which you had access if you made ~20 posts on the forum. Actually there is more than one secret club, but the 20 post one is the more recent. They put COMIC Kairakuten and another one in it because of a C&D letter.
>>108562368
Pretty sure mod power is irrelevant to this stuff. Or at least anything above 5's good.
>>108562497
>
Actually there is more than one secret club
The region blocked one?
>>108562497
i have 20 posts in the forum and can't read any of those. I'd check my Mod Power if i could acess the My Page link, which i can't because i get a redirect loop in both Chrome and Firefox. Already tried cleaning cookies, but didn't work...
>>108562592
When did you made the post ?
>>108562497
Hmm. My accounts pretty old, maybe that has something to do with it? While I can access the others, Kairakuten is definitely not showing up though.
>>108562643
Oh, i made them all ~1 hour ago, that may justify it i guess
don't mind me i'm too sleepy to think
>>108562702
Look for Kairakute, the search thing is not related to any secret club.
>>108562722
Yep, you need to have announce you it's the dawn of a new day, or wait like 24 hours I don't remember exactly.
>>108562801
Okay, thanks anon.
>>108543109
oh gosh
i didn't know i enjoyed this type of thing
>>108561970
Is that the one where she says the head is flaring out more than usual?
>>108562497
>the 20 post one is the more recent
That's been around for years.
This is meme50's magnum opus, innit?
>>108563826
No, it's not.
post yfw u foundoutta bout exhentai, /a/
pic was mfw
>>108561188
>(barring ISP interference).
>What ISP's interfere?
Various countries have their own "Great Firewall of Censorship" which they require ISP's to use. Some just limit it to loli and outlawed sites while others consider all porn to be on the list. South Korea puts all known porn sites on their great firewall list.
Pictured is a message when you try to access an illegal site using a korean ISP. If you feel the site is in error, you can contact the korean police agency of course. They can then add a comment to your identity account saying you oppose official gov't policy (technically true) as well as desire illegal pornography (technically true). This is why if you don't already have censorship, you need to oppose it because getting censorship also allows the authorities a new way to add negative info to your record.
At the end of 2014, the Conservative Party's law will take effect in Great Britain. If you want porn, you have to formally "opt in" or else it is blocked. This may stop British [email protected] or torrent users.
>>108564443
>yfw u foundoutta bout exhentai
>>108564481
And that's a bad thing?
Hopefully etnwind faggot is british
>>108563658
I didn't either until I read Addiction. Hell I didn't even really like loli period before then.
>>108564389
Then which one was it?! ANSWERS, DAMMIT!
>>108564132
>Full censorship
>Not his stuff with vomit
Automatically disagree.
>mfw the doujinshi i want translated will never be translated because it's guro, and i'm too poor to buy a commission
>>108564635
>>Full censorship
>>108564443
>language: english (348) translated (297)
>parody: otoyomegatari (311)
>character: amira hergal (103) karluk ayhan (103)
>group: hi-per pinch (257)
>artist: clover (288)
>male: shotacon (225)
>female: femdom (110)
>>108564971
why is femdom so amazing?
>>108564703
Apparently because muh Tokyo Olympics, which is a silly reason to worsen censorship because most of the rest of the world doesn't censor their porn period.
>>108565123
Well, most of the world doesn't have underage characters in their porn. Even if it's drawn
>tfw you burned through pretty much every doujin and H-manga that prominently features scat
Are there any good (meaning a good artysle and not excessively censored excrement) game CGs or artist CGs with it besides these and their artists?
I don't know what happened but the exlinks/exsauce button disappeared and it seems only for this thread. What happened?
So, when will sad panda stop being the slowest piece of shit?
>>108564481
HentaiVerse players in Great Britain or whose data packets pass thru British ISP will have to Opt In so that they can continue to play their game or view cosplay nudity.
Opting In means you will have your account and real name in the computer in a "short list" of users who desire access to porn. Having a short list would make online monitoring easier too. So security through obscurity is much harder if you are on the short list.
The British law amends the list of restricted items. So not only is loli forbidden, but images depicting rape will also be included. The law also requires search engines to not return searches for certain items. Technically, that means e-hentai search would not return results for shota, loli, rape, bestiality, snuff after the British law takes effect. Both URL describe the effects:
Okay this might seem weird but does anyone know what font this is? I know I've seen it a lot in doujins and manga translations in general.
>>108565643
Reload the page.
>>108565206
I'm sure several euro nations do. And technically plenty in NA, they jsut keep it digital.
>21 forum posts
>Its a dawn of a new day
>
>This gallery has been removed, and is unavailable.
>You will be redirected to the front page momentarily.
Kill me.
>>108566254
I did.
For some reason, it appears on posts that appear after an auto-update. If I refresh after that, it disappears.
>>108566227
The might be referring to the pokemon tournament thing
I love this guy's traps. So fucking good.
>>108566326
noob
>>108565984
>Britbongs
Couldn't they just get around that by proxies though?
>>108566326
It takes longer for some people. I had to wait three or four days before I could get in to the sekrit club but some get in after the first dawn of the new day.
It's not really consistent.
>>108566403
If you say so
>>108566227
>>108566376
It's good I got it thanks.
>>108565984
are you serious
and i was ashamed to be american, lmao
>britian
>>108566442
Well I don't have any plans on fapping til my new onahole gets in so I can wait I suppose
>>108560131
>Your region doesn't matter for the panda
Explain Power Play.
>>108566561
That's not panda related.
Give me the whitest vanilla doujins you can find /a/. I'm in need of hardcore vanilla
>>108562182
Yeah, I can confirm. Can't access those. Exlinks shows me what they are, but if I try to visit the actual link, I'm being redirected. Fucking tenboro.
Someone give me something to fap to, I'm bored of all my current fetishes.
>>108567242
>>108567242
What are you bored of?
>>108567242
>>108567334
tentacles, traps, tomboys, inflation, impregnation, parasite, mind break, tickling, urethra insertion, eggs, and urination
>>108567458
oh yeah also enemas
>>108567508
>>108567458
>>108567242
A couple of my favorites
>>108567189
Vanilla sex between couple who are in established relationships:
Also this, which doesn't fall into the above category but is still the purest porn I have ever seen:
>>108567458
>>108567458
Here's some scat.
I know a few have mind break, inflation, and urination but eh.
>>108567582
Havn't ready any of these yet, but do you have any with people with children or are married or about to get married?
>>108567639
>>108567639
Are the children getting dicked?
>>108567782
No, thats lolicon and not my fetish.
>>108567717
one of my favorite doujins
>>108567639
Some of the ones I linked have married couples. Also this, which I was hesitant to put in the list because the sex isn't strictly vanilla:
None of them have children, though. I honestly can't think of a single original comic that involves vanilla sex between a married couple with kids.
Also, vanilla legit impregnation:
>>108567573
I-I'm not that l-lewd am I anon..?
>>108567903
Thanks anon you're doing god's work.
>>108567957
Everyone is lewd on /a/
Does anyone have some feet doujins without footjobs or without them as the focus?
I mean like foot licking and foot worship, preferably where the girl is doing them.
Recommend some good ones with tsundere girls?
this one is my favorite but as you can see it's not even tagged tsundere, so I want to see what I'm missing
>>108567625
Never been a huge fan of scat though I appreciate the thought. Got anything else interesting?
4chanx refuses to update this thread, but every other thread works fine. This isn't the only time it's happened to a Ex thread. Any way to fix it?
>>108568445
This thread and this thread only refuses to show the exlinks source button for me. Is there something special with sadpanda threads that I'm not getting?
>>108568501
Mine shows the button, but sometimes I have to refresh regardless of execution order. It ALWAYS gives 0 results, though. And I'm 1 club away from max club, but no one has ever confirmed getting into that once it was locked.
test
>>108568675
We're back
So, I'm looking for this one femdom manga/doujin. Features two teenagers(probably would count as shotacon). They get convinced to go over some lady's house with her friend. Eventually they both end up taking it up the ass with their strapons, and slowly mindbreaking to be their slaves.
The best part about it, is that it used "ass-pussy" or "boy-pussy" in the only good way. While one lady was fucking the guy, she told him to stop saying asshole and instead say asspussy. Humiliating him in the best way.
I want to say one of the women were teachers, but I can't recall.
If anyone could help me find this, it would be much appreciated.
>>108556079
Love Girls for M. I keep coming back to this one.
And here's a Kill la Kill femdom with Mako and Ira that I keep coming back to
And some Dragon Quest femdom thing I keep coming back to
^Seriously this one's amazing
>>108568365
Gender Benders can be fun
>>108558210
Alright thanks. Femdom is always welcomed. Just not when people wrongly tag galleries when they get dicks stepped on.
I need a secret link stat.
>mfw just now learning about the sekrit club
Fucking kill me. I just want to fap, not dick around on the forums or whatever.
How much mod power do you need for the sekrit club, and what's the fastest way to get it? I'm at
3right now.
Give me some slut or ordinary loli fucking some innocent shota.
>>108569729
You should begin by lurking and quit being newfaggy.
S-sorry to ask for a recommendation, but does anyone know any good panty job and or sumata links? in return have my favorite sumata doujin
also, preferably no rape
>>108569729
I'm at level 0 lol, and I can access everything.
Google is your friend!
>>108569984
The actual sekrit club, anon. I can get past the panda just fine.
>>108569729
Also, posting and lurking the e hentai forums won't do anything. All you have to do is make your account and wait. There's some kind of time delay between making an account and gaining x access.
About a month after I made my account is when I noticed I had access. Could take less time idk.
>>108567625
>[Ex]Saotome Laboratory - Steam Cheese X Strawberry Banana [French]
>only translated in french
why
english translators pls step up
>equipment durability
I'm glad I quit pandaverse.
>>108553084
Oh cool, /ss/!
Wait, bondage? Kinky.
Forceful nipple piercing? Eh, kinda extreme
oh no
oh man
I can't be doing with this
I can't be doing with this at all
>>108571270
>Mfw I've fapped to it 3 times now
So what exactly is the sekrit club? Seeing certain "banned" tags or artists? I have been a member of sadpanda for awhile now, and I have posted a little bit so I'm wondering if I'm apart of the secret club or not, and of course what it entails.
>>108571747
There are links to some of the galleries in this thread, so you can check for yourself.
>>108572050
Ah okay, like this one? >>108554327 Says keep trying, so I'm assuming I haven't hit that level yet.
So what do I need to do? Get a certain post count?
>>108572135
No, that's just an incorrect url. Try these: >>108562182
>>108572298
I can access them all. How do you tell what's available to all and what's only available to other users?
>>108572339
I don't know what you mean by "only available to other users" but there are some galleries that show up as gone to people with pleb-level accounts. They show up as being removed for those people. I don't know of a way to tell if a gallery is hidden, other than to have someone with a pleb account post about it in these threads.
The only other galleries that are any issue is a handful of releases like Power Play or the first couple volumes of Ring x Mama. Those had official English releases by Project H, so they're region locked for America. No amount of mod power, pandaverse levels, forum post count or anything is going to give you access to those if you're on an American IP address. Proxy is the only way.
Anyone got some femdom humiliation?
>>108547892
I busted out laughing pretty hard right in the middle of fapping. I love that feeling. Now to find something else to finish with.
Is there a tag for something like "rape recovery"? For example, girl gets raped/abused, good guy finds her, rescues her (note it says rescue, not rescue and rape immediately), helps her get on her feet again, start living together, fall in love together and end up fucking like rabbits in the end. Specific manga/doujin instead of tags would work as well.
>>108572823
I like NTR and even I think that's disgusting
Don't read a lot of NTR normally but I liked these.
>>108572563
This guy is a massive pussy
>>108573197
tfw that will never be me
>>108572920
No it's not anon, don't judge because each of us has his own fetish.
>>108573251
Not all of us are guys, anon
Please use "his or her"
>>108573295
fuck off
his includes her
>>108573295
There are no girls on the internet, anon.
I like how that even after reading over 2000 manga/doujins I still find new things in these threads.
Anyone have anything like this?
Preferably with internal urination as well?
>>108572500
>>108572920
But that's a pure love story with bad beginning and good ending.
>>108573415
>milk party
What why is that there?
>>108573310
No it doesn't
How to save images from a secured pdf file without decrypting it
I bought it and want to upload good quality pages, anyone know of a way?
>>108573499
Although, the original post is like 3 weeks old, and that drake: power play got removed.
>>108573556
You upload it and let someone who knows what they're doing do it.
>>108573615
It's there, but I had to unfilter Western to see it.
>>108573664
Anon you're breaking my heart
>>108573721
Oh yeah, duh. We we're comparing view totals which is why I even searched that. I thought it was weird it would be deleted when I redid it to show why Milk was there.
>>108573556
printscr
>>108573556
What exactly are you trying to do and why? What is the purpose.
>>108569765
Please respond.
>>108573721
y u do dis anon
I feel dirty for getting hard at this
>>108573415
I've given up on these galleries. The Project H ones are the only ones I've not been able to see since they were changed a few months ago. I remember there was an American anon who said he could see them, but he had also donated. I don't know if that makes the difference, or if there are some parts of America that are not blocked.
>>108573885
Powerplay predates the C&D stuff, and access to them isn't related unless Powerplay requires the other ones to be available as well, but I'd need a proxy to test, and it honestly doesn't matter me to despite all the other autistic things I've discovered about Ex.
If you need anything that's block but you have a link I'll see if I can reup it.
>>108573835
Upload it to ex for da gp
>>108573817
It doesn't look as good tho
>>108574068
Oh. It helps to know what work it is, and what type of encryption. Why don't you want it decrypted?
I won't help with that selfish reason, though. Just that info is useful and curiosity.
>>108574005
Nah, I've had it since it got translated, and the torrent links are still accessible, even if the gallery isn't. It was changed before the C&D stuff, I know - that's why I used "months" plural. It was visible up until a few months ago.
>>108574005
Power Play's gallery is blocked, but not its torrents. You can still download it just fine: >>108560643
>>108574218
Or you could just
buy it like everyone else
>>108574253
I'm sure that would go over well in the states.
>>108574291
...wasn't that licensed in US in the first place?
>>108537849
Eh, I can't log in with my new account...
Did the folks at exhentai changed the system or something?
>>108574331
Yeah. No newfags allowed
>>108574365
...and yet you are.
>>108574365
>implying I'm a newfag
Yeah, nah. E-Hentai's password recovery a shit so I had to create a new one.
>>108574407
>E-Hentai's password recovery a shit so I had to create a new one.
If you hadn't been using the plugin you'd remember your password and there'd be no need for you to use the recovery.. Just saying, newfriend
>>108574218
Sure, I guess that method works.
>>108574456
>implying I use the plugin
Just stop, mate.
Oh and I agree that I should of remembered my password. Though that still doesn't change the fact that their password recovery system is utter garbage.
>New game update
>Armor and weapons now need repairing
>Enemies are harder
Only good thing is that happy pills can now be bought, price is 2k which is quite a lot.
After some years without messing with it I just took a look at my scanlator bookmarks and it's impressive how many groups died. Yoroshii, UMAD, Soba-scans, LoliLoli Hunters, Hayama Kotono, Uncesored Hentai World, BiriBiri, Anonymous Scanner, Doujin Ayane, Lusty Lady. I can only imagine how many others were gone while I wasn't looking.
It's a fucking mystery how we lost all this people yet CGrascal is still at large.
>>108574589
>CGrascal is still at large
That's because FAKKU is still alive.
>>108574589
>biribiri and lust lady died
huh
>not alternatively fapping to Power Play in portuguese
>>108574589
BiriBiri was alive after the recent C&D and Soba only died because people pissed him off too much. LL died to the C&D.
>>108574589
Biribiri is still alive, technically. As for the rest, scanlators have always been here today gone tomorrow, they have a lot shorter runs than subgroups at anyrate.
>>108574556
Whatever you say then
>>108574657
>LL died to the C&D.
No I remember them seeing operating under a another name right after their disappearance. In fact, it was a funny conspicuous name. Something along the lines of OpCovertBewbs. Might have changed the name though.
>>108537849
>hot kissing that isn't close eyed, tiny mouthed babby's first kiss
great in all flavors, rape, ntr, or vanilla.
recently I have really liked aggressive females poaching innocent males who get the tables turned on them and get turned into slobbering mindbroken cumdumpsters.
That and female edging/orgasm denial. I don't prefer NTR as a scenario, it just seems to attract the artists that cater to my preferences.
Guess I'll leave these here:
Vanilla-kinda
NTR-ish-notreally
I don't really keep the more hardcore NTR stuff off the top of my mind, I just read it if the art catches my eye and kinda forget it.
>>108574589
Just took a look at my own and apparently DesuDesu is being enslaved by some Japanese company. Karoshi soon.
On the bright side old uncle SaHa is still alive and kicking. By now he is probably the oldest active porn translator out there.
>>108574936
I can remember downloading SaHa releases on MU. Damn they've been around forever.
>that fucking disparity between color/cover pages and the actual book itself
Too many times have I fallen for this trick. I wonder if Ishikei does the coloring himself? His art looks so half-baked without it.
>>108548400
internal monologues are so hit or miss. This one is pretty damn good though.
NTR is like a crapshoot for me cuz of how much of a turnoff some very specific but overused internal monologue lines are. Literally furious after-image fapping mode to 0% erect in under 3 seconds if I see one.
>>108575032
I'm the same way about NTR, it's super hot when it hits the right notes but just becomes irritating if the author falls back on annoying copouts/cliches.
>>108575114
That's not to say vanilla isn't the same though. Especially bad vanilla art holy shit straight outta fanfiction.net with that same neutral-pleasure eyes closed slightly parted mouth face. Literally as bland as real life women what the fuck.
>>108575238
I'm getting to the point that if there's no leg locking and heart pupils I don't see the point in reading vanilla. For vanilla scenarios I really love "house wife plans a romantic evening" type scenarios, if you know what I'm talking about. The kind of thing that usually starts with naked apron.
>>108574589
Fortunately there are loads of other groups taking their place.
It's the great thing about scanlating, it never really dies.
>>108575410
Vanilla usually requires nymphos of at least this level because males in all genres are just dick transporters and provide almost nothing (with a few exceptions).
On the note of leglocking and heart pupils, subtle indications that she's having trouble maintaining composure because of the pleasure really turns me to 120%. Curled toes, pushing/clutching the sheets, bridge arch, arm/leg lock, kissing, etc. Or at least vary the ahegaos.
>>108575704
>Curled toes, pushing/clutching the sheets
>>108575785
>small breasts, tomboy, blushing, leglock
>>108575514
Did any new groups get birthed this year?
>>108548061
>
oh my god all that delicious foreskin tugging on page 26 and 27, got anything more like that?
>>108576367
Oh, christ, my autism
Can't someone just download the hidden galleries and reupload them so that they're no longer hidden? When they get hidden again, just reupload. Do this ad infinitum until tenboro pulls his head out of his ass.
>>108577039
There are millions of other sites to get the same doujin off from. Go to Fufufuu/Pururin if it rustles your jimmies too much.
>>108577179
I don't even really read the stuff that's hidden. It's more about pissing in horsefucker's cereals.
>>108577039
>reuploading a gallery takes A LOT longer than hiding it
>you'll end up banned after a few galleries
>you can use a proxy or change your IP, but it will only help in slowing you down even more
>you won't be hurting the site, as images with the same hash are only stored once
Just get into the sekrit club and stop bitching
>>108577209
>I don't even really read the stuff that's hidden
>>108577286
No, really. I'm a lolicon and so far I haven't seen any loli hidden
can we talk about h-games for a second? is there such a thing as a 3d model sex thing? even 2d i dont care. i have no idea what or where to even search. the closest thing i found was polygon love
>>108577707
There's an h-game thread on /vg/ that might help you.
Try not to be so vague, though.
>>108577816
i completely forgot /vg/ was even a thing. Im being vague because im not going to be picky.
thanks man
>>108577707
>polygon love
Something like Artifical Girl/Academy?
>
>lolicon (10)
What?
>>108577317
Henreader is published in X-eros.
>>108580351
Removed that.
So what are your favorite/the best you've seen with creampies?
Nakadashi is probably my most-searched-for tag on the panda.
>>108583254
I don't necessarily like that, but I like these and it features nakadashi decently I think.
>>108583603
Those are pretty good, yeah. Thanks for the share.
Post some sexy toddlers.
>>108541168
I'd still like a link.
>>108585161
I remember that it's got Hinterland in the name. If you can't find it from there you don't deserve it.
>>108585302
Yeah, no problem, thanks.
>>108585358
Glad to help.
I'm looking for something with an older girl getting her boyfriend to fuck her loli sister, or a similar setup. Bonus points if the younger girl doesn't want to and/or the boyfriend is reluctant.
I think I've read more than one thing like that already, but it was a long time ago and I don't remember it.
If no one knows anything like that, simply a harem where one of the girls is much younger than the others and the taboo aspect is played up would be cool too.
I think the contrast between the older girls and the loli makes it much more arousing than just a run of the mill lolicon manga where fucking kids is normal.
>>108584118
Hey guys, looking for some help with the name a tank I downloaded which I've completely forgotten about.
- Guy from another world comes to Earth and he meets a girl who he starts dating
- I recall him helping fix up other couples' relationships
- Turns out he's a prince or something and returns to this world, the girl who fell in love with him somehow follows him there
- I believe they marry in the end and the she (main girl) has red hair
Hopefully someone can give me a hand, greatly appreciate it.
I need help, guise.
I can't remember the name of a loli doujin about a guy who meets a couple of little girls in a mall food court, and then said girls knock him down and fuck him behind an alley. I could have sworn I had it saved on my HD, but I guess not. Someone here probably knows what I'm talking about.
How on earth do credits and level work on e-hentai? They've never done anything before but they've been going up on their own the past few days.
>>108588531
>>108588704
Hey Joe, the picture thread in the forums was closed, probably because of lolin and stuff.
Will this have further consequences, like review or something?
I didn't post forbidden material, but I'm afraid that I'll be punished simply because some mod doesn't pay attention or something.
>>108590109
Very unlikely.
>>108584118
Only toddler one I've ever enjoyed.
>>108575785
Why do the best things have no tags?
Up you go
>>108586239
/a/ please, don't tell me it's another fetish no one else has.
>futanari out of fucking nowhere
This is why we can't have nice things.
>>108570297
I just read it with Google Translate in another window, but seriously it's a crime that it hasn't been translated into English yet.
>>108584118
>Toddlercon
This makes me feel very uncomfortable but diamonds at the same time.
I know that it's not real and while normally I wouldn't give it a second thought it still feels really wrong.
>>108597069
I don't think a h-manga has ever made me feel uncomfortable since I first read this on
/b/ 7 or so years ago.
So I'm looking for things involving split personalities, or women getting overcome with lust. Like they become a different person, and have very little memory of anything that happens during it including any sexyness that might happen.
>>108597534
corruption?
>>108597586
I think so. But not permanent. Like a mental switch is flipped.
>>108597624
Mind control?
I'm looking for an old story, I think it was on Hotmilk or something. It's about a guy taking his friend to a seemingly normal shop lose his virginity. The owner (I think she was wearing jeans) takes him to the back, and is pretty gentle and proffessional about taking his first time. For a price, of course.
Does anyone remember it?
Any body into cum on food doujins ?
What are your favorites ?
>>108597863
Not quite.
You know dragonball's Lunch character that switched between sweet and violent when she sneezed? That, but in a doujin.
Those!
No one fucking uploaded the latest Musashi Daichi tank yet
>>108537849
How about we do this with a twist?
One guy makes an account and posts the id/password here.
Others add good stuff in favorites, since its capped at 500, so everyone can participate and we have quality content.
Try and group by folders too.
>>108600514
can you send Hath to other users?
Is 800k gp considered rich
Because I just looked at the exchange and hath is so fucking expensive
>Not fapping to Sony IPs in anticipation for their conference
What's your excuse?
>>108601755
I totally forgot e3 was this week
How was todays?
>>108602414
Platinum got moneyhated again and this time their game look less and less like anime
>>108601755
sony has no games
>>108602414
Xbox One exclusives, halo, call of piss, new IPs(inside stood out ), new fable game, witcher 3 gameplay, evolve, new tomb raider, LOTR game.
probably missed some stuff but thats what stood out to me.
>>108602816
>LOTR game
Huh. Must have missed that.
>>108602933
Nothing we haven't heard before if you've watched the trailers/interviews. Still hype for it though
Man, it's bad to let your dick completely take over when fappi | https://4archive.org/board/a/thread/108537849/sad-panda-thread | CC-MAIN-2018-30 | refinedweb | 11,765 | 82.14 |
User talk:Joe9320/Archive 3
From Uncyclopedia, the content-free encyclopedia
edit RAAAAAAAAPE
Nice meeting you! —Paizuri MUN ♦ Talkpage ♦ My Contributions ♦ 08:48, 8 March 2010 (UTC)
edit Goa Tse Clan question
Question not application--if someone signs up, do they get credit for work they've already done, or do they have to start from scratch? And is it all right if they also work for a different conspiracy (or even four or five different conspiracies)? Not that I'm a part of any conspiracies, of course. I'm not talking about me anyway. WHY???PuppyOnTheRadio 22:06, March 8, 2010 (UTC)
edit Pokemon thingy
That game is up for VFD. If I were you and wanted to keep it I'd ask an admin to move it to your namespace. • Puppy's talk page • 00:40, June 5, 2009Wednesday, 21:13, Mar 10:34, March 17, 2010 (UTC)
edit Your edits on IC
I appreciate the fact you've been a part of Imperial Colonization for a long time, and have worked on more colonizations than almost anyone else.
However, I do want to make some comments about your edits.
On Batman, your edits are here. You have Bruce Wayne doing a dance and acting silly. But the article as outlined there is dark, with a little of the feel of Poe and Lovecraft. Also in the article Bruce Wayne is heavily sedated and completely restrained--but you have him dancing, waving his arms, etc. Your edits were completely off track, and were therefore reverted.
On Creationism, the only edit by you that I found was one, which was reverted as it was the opposite of the guidelines for the article.
So in both the articles I oversaw as head of IC, your edits were reverted as not fitting the article.
I'm going to ignore Transformers as, frankly, I'm not sure where that was supposed to go anyway. Also I wasn't in charge of IC then anyway.
I wasn't in charge of God either, but will comment. The consensus was to do the article about God the Gambler. But you addedthis about God making a breakfast cereal, which doesn't seem to connect to the concept. To be fair, you also added links, which were useful. But again, I'm using that only as an example as I wasn't even in IC then--my concern is with Creationism and Batman.
In the future, please carefully read the concept of an article and read what's been written already. I went ahead and gave you credit on Batman even though, frankly, as far as I can see none of your edits were used. But for future articles, please work hard to stay on topic. If none of your edits on our next colonization fit the article, you will not be given credit. If it continues, I will move you off the active membership list.
If you'd like to be a part of setting the direction for an article, you can do so now at Uncyclopedia talk:Imperial Colonization/Discordianism. Thanks for listening, and I hope this will inspire you to be a productive member of IC. WHY???PuppyOnTheRadio 19:25, March 23,:08, March 24, 2010 (UTC)
edit Promotion to Rear Admiral
Whereas you have helped with 10 Imperial Colonizations that successfully subdued the wild natives, therefore be your elevation proclaimed. To the Glory of Her Majesty!:52, April 18, 2010 (UTC)
edit:35, April 22, Mecca Vice will skip your home
edit FYI
I have Read your submission and have recorded my first impressions. (I used helium balloons to make my voice more hilarious for the recordings.) Soon I will review the history and other stuff & junk to finalize a score for you and the other contestants. That is May 2010 ~ 06:22 (UTC)
edit You thought I forgot?
Thanks! :48, 1 July 2010
edit How do you know me?
Judging by this you seem to know me from somewhere...no? Sincerly,GEORGIEGIBBONS 20:56, July 4, 2010 (UTC)
- Actually, don't worry. I found out what it really was. I hope <insert name here> has fun here :). GEORGIEGIBBONS 11:46, July 5, 2010 (UTC)
edit The template that I'll never change
edit These thanks templates will get shorter soon, I promise
TV Tropes is a feature! So I guess, even though I disowned it, I should thank you for your vote on VFH. Thanks!
Sir MacMania GUN—[21:08 29 Jul 2010]
edit Draft
Your turn, Joe. Go here —Unführer Guildy Ritter von Guildensternenstein 02:25, August 4, 2010 (UTC)
edit K, So Here's the Deal
You're either going to make your pick, or let us autopick for you based upon the Yahoo! predraft ratings. What you're not going to do is waste mine and other people's time. So decide. —Unführer Guildy Ritter von Guildensternenstein 13:45, August 4, 2010 (UTC)
- Actually, I autopicked for you--you have Ray Rice, who, Yahoo!, is the highest rated player remaining at the position to checked off on that nifty chart of mine. So yeah. —Unführer Guildy Ritter von Guildensternenstein 14:29, August 4, 2010 (UTC)
edit Thanks!
I am eternally grateful! :33, 10 August 2010
edit ありがとうございます
Thanks for the vote!
Sir MacMania GUN—[00:00 18 Aug 2010]
edit Russo-Japanese Thanks
edit I made the league
It's on Yahoo!. Here are some important things to know:
- League ID: 512953
- Custom League URL:
- Password: guildy
—Unführer Guildy Ritter von Guildensternenstein 21:35, August 19, 2010 (UTC)
edit We saw the sign that said "No Salesmen or Agents" but we came in anyway
Thanks for the vote!
Sir MacMania GUN—[15:07 24 Aug 2010]
edit I noticed you have yet to make your team on Yahoo!
Please do so as soon as you are able. Here are some important things to know:
- League ID: 512953
- Password: guildy
- Where to go: [1]
- Custom League URL:
—Unführer Guildy Ritter von Guildensternenstein 15:29, August 24, 2010 (UTC)
- Make a team, dammit! —Unführer Guildy Ritter von Guildensternenstein 20:16, August 25, 2010 (UTC)
edit Avast me hearties!
edit UFFL 2010 Kickoff
The draft is over, the NFL regular season begins Thursday September 9th, and everyone is geared up and ready to play some fantasy football(!).
This season promises to thrill and intrigue, and as the Uncyclopedia Fantasy Football League has grown from just eight all the way to 14 teams, each one vying for a shot at the championship, except maybe Neox's team. With all this excitement, however, comes questions. Will Rush and Kick FTW, the UFFL's first team based in Britain, be able to compete with the league's American teams? Will Cheddar's rebuilt Doritorians be able to play at the same high level as last year now that their roster is down from 50% Eagles players to just 30%? Will evil Nazi overlord and reigning league Champion Guildensternenstein be able to defend his league championship now that Top-3 players at the quarterback, running back, wide receiver and tight end positions didn't fall into his lap this year? Only brutal, primal, visceral, cerebral combat on the fields of Yahoo!'s fantasy football league servers can determine these questions.
That all being said, everyone should take note of two things:
- this is a link to the league--go here to do stuff, like select a starting roster (which, believe it or not, is important).
- this is the forum where we'll talk about the league and post banal sports banter (which, believe it or not, is even more important).
Good luck, gentleman. —Unführer Guildy Ritter von Guildensternenstein 16:05, September 4, 2010 (UTC)
edit) __ 18:03, September 4, 2010 (UTC)
edit Your Efforts Are Appreciated!
--10:59, September 7, 2010 (UTC)
edit You're my first opponent for the UFFL
Prepare to die viciously.
Jenny? 19:26,7September,2010
edit Starting Lineup
You've got to go to Yahoo! and adjust your starting lineup, dammit. —Unführer Guildy Ritter von Guildensternenstein 14:29, September 8,:53, September 10, 2010 (UTC)
edit Trade
I proposed a trade to you in fantasy football. —Unführer Guildy Ritter von Guildensternenstein 12:06, September 17, 2010 (UTC)
edit Spammy spammy spam spam spam
edit Jack Dempsey thanks you
edit I...
Noticed you and the Goa Tse Clan haven't really been updating the UnCyC store. So I was wondering if you, as head of the Goa Tse Clan, would be willing to transfer ownership/co-ownership of UnCyC to either me or the Grue Army. At least at a minimum we have plenty of surplus war meterial to sell off, and this seems to be the way to do it. --High Gen. Meganew (Stuff I've Done) (Chat With Me) (Get an Award!) ENLIST MUN 14:37, October 21, 2010 (UTC)
edit A box.
Don't open it. It's on your patio. It contains something you may or may not appreciate.
On an entirely unrelated note, thanks for your vote for Wrists on VFH. I swear this is entirely unrelated... Terry? ~01027 - 16:57 Ball!".
- Thank)}" > | 21:28, November 16, 2010 (UTC)
edit Ta
Thank you for voting my 40th feature this has enabled me to receive free electro-convulsive aversion therapy.--Sog1970 21:47, November 14, 2010 (UTC)
edit Party features page
That was hilarious. I hope you don't mind the additions I made. You don't have a feature, ay? What is your best page, let's see if we can remedy this error. Aleister 21:52 16 11
- p.s. Damn, I've never looked at your user page. It's beautiful! Wow. And you've written a boatload of stuff!
edit Punji Stick
Much thanks for your vote. Now you have reduced the odds of stepping on a punji stick by 0:26, Nov 20
edit Participation Template
Thanks for participating in this past season of UFFL fantasy football. Here is a template for said participation:
All of the other awards/results are posted here. Thanks for playing. —Unführer Guildy Ritter von Guildensternenstein 18:25, December 30, 2010 (UTC)
edit Hi there..
Joe, you'll be one of our tie breaker judges, if for whatever reason the judges cannot fulfill a final verdict you will judge the articles in the category and you will give a result:)--Sycamore (Talk) 10:14, February 1, 2011 (UTC)) | http://uncyclopedia.wikia.com/wiki/User_talk:Joe9320/Archive_3 | CC-MAIN-2016-26 | refinedweb | 1,742 | 71.65 |
in reply to
Don't waste your time (Was: Registering CPAN module namespace)
in thread Registering CPAN module namespace
Not very well monitored? What's your standard for that? Almost everything is taken care of the same day. I take offense at you spreading FUD about this. I look at the list every day that I have net access, which is almost every day. Adam and Steffen take care of quite a bit of work, and Johan immediately takes care of all new Id requests.
It's extremely well monitored. You are saying that we are slacking, and you do mean offense. Saying anything about it has nothing to do with the point you are making and you could have left it out. But you have some reason to take a swipe at us.
So, what didn't we do for you that you think we should have done? What grudge do you have? Are you still mad about a two week delay in response for Tree::Simple from 2004? That was four years ago. Since then you've written to modules rarely and in in case received a prompt reply.
Update: Indeed, modules@perl.org is for dealing with PAUSE, fixing broken distros, and transferring module permissions. Any sort of other discussion is best taken elsewhere. That address isn't a mailing list, it's just a mail alias for all of the admins. If someone wants to discuss modules, they probably better off in module-authors@perl.org, or even right here on Perlmonks.
Sorry. Yes, you are 100% correct, the "Can I have a PAUSE ID" and "There is a problem with my PAUSE ID, please help" issues are handled right away, and you guys do an awesome job at that. And from skimming over the last 6 months or so of the list archives it seems that you in particular do quite a bit of responding to module registration requests and issues, so again, I apologize for imply that there is no one doing that, because clearly I am wrong. My choice of words was poor, and I apologize for that.
What I really meant is that modules@perl.org (despite what the name implies) is not a good forum for discussing module ideas and module naming help requests because it is pretty much only monitored by a small group of people and is not a "community hangout" (on the flip side, the archives have very few bike-shed-color suggestions, so maybe this is a good thing (hmm my foot is tasting better and better each time I put it in my mouth)).
But yeah, your point is correct, I could have made my point without saying that (or the clarified version too actually).
Wow, good memory, even I forgot that. It was not a grudge thing at all, I am simply trying to point out that registration was at one time very useful for CPAN, but now with search.cpan.org being the primary gateway, seems to be less so.
Yes
No
A crypto-what?
Results (169 votes),
past polls | http://www.perlmonks.org/?node_id=684477 | CC-MAIN-2014-10 | refinedweb | 516 | 81.12 |
*
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
|
Flagged Topics
|
Hot Topics
|
Zero Replies
Register / Login
JavaRanch
»
Java Forums
»
Java
»
Beginning Java
Author
super class question
Glenn Jayasuriya
Greenhorn
Joined: May 15, 2012
Posts: 4
posted
Jun 27, 2012 02:23:07
0
Hello, I'm learning about super class.
I am having some problems.
Basically I am asked to determine whether an object of a super class array is of type of subclass.
However i can't use instanceof or getClass.
So i was thinking of using booleans.
So i made a boolean in the subclass that i want and set that to true.
Now i'm trying to pass this new boolean to the superclass however i get this error message: cannot reference grad before supertype constructor has been called
I changed the super class parameters to include the new boolean. However i still get this message.
Please help
Thanks
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 4363
8
I like...
posted
Jun 27, 2012 03:13:22
0
You're probably going to have to show us the code.
However, the obvious question is why can't you use
instanceof
? Because that's what it's for.
Glenn Jayasuriya
Greenhorn
Joined: May 15, 2012
Posts: 4
posted
Jun 27, 2012 06:39:34
0
I know instanceOf is what it's for but i was told not to use it.
Here is my code:
import java.util.ArrayList; public class Lab6 { public static void main(String[] args) { ArrayList<Student> students; students = createStudents(); printStudents(students); printDeansList(students); printGradStudents(students); System.out.println("\nEnd of processing."); } public static ArrayList<Student> createStudents() { ArrayList<Student> students; students = new ArrayList<Student>(); students.add(new UndergradStudent(8032, "Casper", 2.78, 2)); students.add(new GraduateStudent(3044, "Sheena", 3.92, "Natural Language Processing")); students.add(new UndergradStudent(6170, "Yolanda", 4.26, 3)); students.add(new GraduateStudent(1755, "Geordi", 3.58, "Human-Computer Interaction")); return students; } public static void printStudents(ArrayList<Student> students) { Student student; System.out.println("\nList of all students:\n"); for (int i = 0; i < students.size(); i++) { student = students.get(i); System.out.println(i + 1 + ": " + student); } } public static void printDeansList(ArrayList<Student> students) { Student student; System.out.println("\nDean's honour list:\n"); for (int i = 0; i < students.size(); i++) { student = students.get(i); if (student.deansHonourList()) { System.out.println(student); } } } public static void printGradStudents(ArrayList<Student> students) { Student student; boolean GradStudent = false; System.out.println("\n\nList of graduate students:\n"); for (int i = 0; i < students.size(); i++) { student = students.get(i); //GradStudent = GradStudent.isGradStudent(); if (GradStudent) { System.out.println(student); } } } } class UndergradStudent extends Student{ private int year; public UndergradStudent(int number, String name, double gpa, int year) { super(number, name, gpa); this.year = year; } // deanHonourList was moved to student class public String toString() { return "Undergraduate: " + super.toString() + ") year: " + year; } } class GraduateStudent extends Student{ private String thesis; public GraduateStudent(int number, String name, double gpa, String thesis) { super(number, name, gpa); this.thesis = thesis; } public boolean deansHonourList() { boolean result = false; if (getGPA() >= 3.75) result = true; return result; } public String toString() { return "Graduate: " + super.toString() + ") thesis: " + thesis; } } class Student{ private int number; private String name; protected double gpa; public Student(int number, String name, double gpa) { this.number = number; this.name = name; this.gpa = gpa; } public double getGPA() { return gpa; } public String toString() { return number + " " + name + " (" + gpa; } public boolean deansHonourList() { boolean result = false; if (getGPA() >= 3.50) result = true; return result; } }
basically when i use the printGradStudent() method it should print out only the grad students. However to do this it must be able to differentiate which is a grad student and which is a undergrad student.
The method is not completed yet b/c i had to change it or it wouldn't compile.
I was thiniking of justing making a boolean variable in printGradStudent() and send that to super class (Student) in order to determine if the object is of type GraduateStudent
Thanks
I agree. Here's the link:
subject: super class question
Similar Threads
polymorphism question
question from Dan's exam - ClassCastException
Creating an instance of a sub-class runs parent and child constructors?
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/585306/java/java/super-class | CC-MAIN-2014-35 | refinedweb | 714 | 51.14 |
Official blink(1) control library
Project Description
Official Python library for blink(1) USB RGB LED notification devices
About this library
This is a rewrite of the original Python library. It includes the following modifications:
- 100% test coverage on all library components
- Python 3.x compatible
- Automatic installation via Python Package Index.
- Higher level control over the blink(1).
- Single implementation with cython-hidapi (instead of PyUSB), intended to be installed with admin access or virtualenv.
This library lives at
Originally written by @salimfadhley, at. Moved to this repository and rewritten for cython-hidapi by @todbot.
Installation
Use the pip utility to fetch the latest release of this package and any additional components required in a single step:
pip3 install blink1
Developer installation
Having checked out the blink1-python library, cd to it and run the setup script:
git clone cd blink1-python python3 setup.py develop python3 ./blink1_demo/demo1.py
You can now use the blink1 package on your system. To uninstall the development version:
python3 setup.py develop --uninstall
OS-specific notes
While blink1-python is not OS-specific, the cython-hidapi library it uses does have platform-specific requirements.
Linux:
You will need to install extra packages, like:
sudo apt-get install python-dev libusb-1.0-0-dev libudev-dev
Mac OS X:
You will need Xcode installed with command-line tools.
Windows:
You will need “Microsoft Visual C++ Compiler for Python 2.7”
Use
The simplest way to use this library is via a context manager.
import time from blink1.blink1 import blink1 with blink1() as b1: b1.fade_to_color(100, 'navy') time.sleep(10)
When the blink1() block exits the light is automatically switched off. It is also possible to access the exact same set of functions without the context manager:
import time from blink1.blink1 import Blink1 b1 = Blink1() b1.fade_to_rgb(1000, 64, 64, 64) time.sleep(3) b1.fade_to_rgb(1000, 255, 255, 255)
Unlike the context manager, this demo will leave the blink(1) open at the end of execution. To close it, use the b1.close() method.
To list all connected blink(1) devices:
from blink1.blink1 import Blink1 blink1_serials = Blink1.list() print("blink(1) devices found:", ','.join(blink1_serials))
To open a particular blink(1) device by serial number, pass in its serial number as a Unicode string:
from blink1.blink1 import blink1 blink1 = Blink1(serial_number=u'20002345') blink1.fade_to_rgb(1000, 255,0,255) blink1.close()
Colors
There are a number of ways to specify colors in this library:
b1.fade_to_color(1000, '#ffffff') # Hexdecimal RGB as a string b1.fade_to_color(1000, 'green') # Named color - any color name understood by css3 b1.fade_to_color(1000, (22,33,44) # RGB as a tuple. Luminance values are 0 <= lum <= 255
Attempting to select a color outside the plausible range will generate an InvalidColor exception.
Gamma correction
The context manager supports a ‘’gamma’’ argument which allows you to supply a per-channel gamma correction value.
from blink1.blink1 import blink1 with blink1(gamma=(2, 2, 2)) as b1: b1.fade_to_color(100, 'pink'), 'white')
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/blink1/ | CC-MAIN-2018-17 | refinedweb | 531 | 51.34 |
The standard way to represent an ordered set of numbers is with a binary tree. This offers a good mix of performance properties as the number of elements gets large. In particular it offers O(log(n)) operations insertion/deletion, O(log(n)) operations to find an element. Finding the ith element of the set takes more time, O(n) operations for random access compared to a vector, which has O(1) complexity for that task.
In C++ std::set implements an ordered set as a binary tree, hiding all the ugly details for you. But std::set is not always the right structure to use. Unless you are doing lots of inserts and removals in large sets, binary trees can be inefficient because they have to do things like pointer referencing, and the data is not stored in a continuous block leading to cache misses. This is why some have declared that you shouldn’t use set.
An alternative is to use a sorted std::vector as the set data structure. This improves the performance of random access to O(1), and worsens the performance of insertion/deletion to O(n). There is a handy drop in replacement for std::set in boost called flat_set. You can mostly take any code using set and switch it to flat_set with no changes to the logic.
Recently I was in a situation where I had performance critical code using many small sets (typically between 0 and 20 elements). This code does lots of insertions and deletions, so one would initially think that flat_set is not a good option with its O(n) complexity, but remember that complexity is an asymptotic statement as n grows, and I was relatively certain that my n was small. So which should be used? The only way to find out was to do some simulations.
For each n I generated a set<int> and flat_set<int> with equally spaced integers from 0 to 100,000,000, then I inserted and removed 500,000 random integers in the same range and recorded the timings. The compiler optimization was set to high ( -O3 ).
size flat_set std::set 2 0.02791 0.070053 4 0.031647 0.07919 8 0.038431 0.08474 16 0.0528 0.091744 32 0.0697 0.104424 64 0.085957 0.129225 128 0.1176 0.129537 256 0.15825 0.138755 512 0.253153 0.148642 1024 0.401831 0.156223 2048 0.718302 0.166177 4096 1.35207 0.176593 8192 2.5926 0.19331
Times are in seconds here, so for small sets (2-16 elements) flat_set is twice as fast, and beats std::set all the way up though 128 elements. By 4096 elements we are paying the asymptotic cost however and flat_set is >10x slower. flat_set is vector backed, so we know that it will be much faster at other operations like random access, iteration and find because it is in a contiguous block of memory. The surprising thing is that it is even faster at insertions and deletions provided the set size is modest.
If you are an R user, you can use flat_set very easily now with the new BH package. Simply add it as a linkingTo in your package and Bob is your uncle. Below is the code that I used for the simulations (it uses Rcpp but that can easily be taken out).
#include <boost/container/flat_set.hpp> #include <set> #include <ctime> #include <Rcpp.h> GetRNGstate(); std::clock_t start; double d1,d2; boost::container::flat_set<int> fs; std::set<int> ss; int n = 500000; int max = 100000000; for(int i = 1;i<14;i++){ int s = round(pow(2.0,i)); d1=0.0; d2=0.0; fs.clear(); fs.reserve(s*2); ss.clear(); for(int j=0;j<s;j++){ int val = round(((j+1)/(double)s)*max);//floor(Rf_runif(0.0,max)); fs.insert(val); ss.insert(val); } start = std::clock(); for(int j=0;j<n;j++){ int rand = floor(Rf_runif(0.0,max)); bool ins = fs.insert(rand).second; if(ins) fs.erase(rand); } d1 += ( std::clock() - start ) / (double) CLOCKS_PER_SEC; start = std::clock(); for(int j=0;j<n;j++){ int rand = floor(Rf_runif(0.0,max)); bool ins = ss.insert(rand).second; if(ins) ss.erase(rand); } d2 += ( std::clock() - start ) / (double) CLOCKS_PER_SEC; std::cout << s << ", " << d1 << ", " << d2 << "," << std::endl; } PutRNG... | http://www.r-bloggers.com/insert-and-remove-performance-of-boosts-flat_set-v-s-stdset/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+RBloggers+%28R+bloggers%29 | CC-MAIN-2015-35 | refinedweb | 733 | 67.25 |
In this chapter, we will cover the following recipes:
Installing web2py on Windows (from source code)
Installing web2py on Ubuntu
Setting up a production deployment on Ubuntu
Running web2py with Apache,
mod_proxy, and
mod_rewrite
Running web2py with
Lighttpd
Running web2py with Cherokee
Running web2py with Nginx and uWSGI
Running web2py on shared hosts using CGI
Running web2py on shared hosts with
mod_proxy
Running web2py from a user-defined folder
Installing web2py as a service in Ubuntu
Running web2py with IIS as proxy
Running web2py with ISAPI
In this chapter, we discuss how to download, set up, and install web2py in different systems and with different web servers.
Note
All of them require that you download the latest web2py source from the website:, unzip it under
/home/www-data/web2py on Unix and Linux systems, and on
c:/web2py on Windows systems. In various places, we will assume that the public IP address of the host machine is
192.168.1.1; replace this with your own IP address or host name. We will also assume web2py starts on port
8000, but there is nothing special about this number; change it if you need to.
Although there is a binary distribution for Windows environments (packaging executables and standard libraries), web2py is open source, and can be used with a normal Python installation.
This method allows working with the latest releases of web2py, and customizing the python modules to be used.
First of all, you must install Python. Download your preferred 2.x version (not 3.x) from:.
Although newer versions include more enhancements and bug fixes, previous versions have more stability and third-party library coverage. Python 2.5.4 has a good balance within features and proven stability history, with good binary libraries support. Python 2.7.2 is the latest production release for this platform at the time of this writing, so we will use it for the examples.
After downloading your preferred Windows Python installer (that is python-2.7.2.msi), double-click to install it. The default values are fine for most cases, so press Next until it finishes the installation.
You will need Python Win32 extensions to use the web2py taskbar or Windows service. You can install pywin32 from:.
Prior to using web2py, you may also need some dependencies to connect to databases. SQLite and MySQL drivers are included in web2py. If you plan to use another RDBMS, you will need to install its driver.
For PostgreSQL
,
you can install the psycopg2 binary package (for Python 2.7, you should use
psycopg2-2.3.1.win32-py2.7-pg9.0.1-release.exe): (notice that web2py requires psycopg2 and not psycopg).
For MS SQLServer or DB2, you need pyodbc :.
At this point, you can use web2py with your preferred database.
Download the source package from web2py official website:, and unzip it.
As web2py doesn't requires installation, you can unzip it in any folder. Using
c:\web2pyis convenient, to keep pathnames short.
To start it, double-click
web2py.py. You can also start it from the console:
cd c:\web2py c:\python27\python.exe web2py.py
Here you can add command-line parameters (
-ato set an admin password,
-pto specify an alternate port, and so on). You can see all the startup options with:
C:\web2py>c:\python27\python.exe web2py.py --help
web2py is written in Python, a portable, interpreted and dynamic language that doesn't require compilation or complicated installation to run. It uses a virtual machine (such as Java and .Net), and it can transparently byte-compile your source code on the fly when you run your scripts.
For novice users' convenience, there is web2py Windows binary distribution available at the official site, which is precompiled to a bytecode, packaged in a zip file with all the required libraries (
dll/
pyd), and is present with an executable entry-point file (
web2py.exe), but there is no noticeable difference running web2py from source.
Running web2py from the source package in Windows has many advantages, a few of which are listed as follows:
You can more easily use third-party libraries, such as Python Imaging (look at Python package index, where you can install more than ten thousand modules!).
You can import web2py functionality (for example, the Database Abstraction Layer (DAL)) from other Python programs.
You can keep web2py updated with the latest changes, help to test it, and submit patches.
You can browse the web2py source code, tweak it for your custom need, and so on.
This recipe covers how to install web2py in a development environment using the Ubuntu desktop. Installation in a production system will be covered in the next recipe.
We assume that you know how to use a console and install applications using the console. We will use the latest Ubuntu desktop, at this writing: Ubuntu Desktop 10.10.
cd /home mkdir www-dev cd www-dev wget (get web2py)
When the download is complete, unzip it:
unzip -x web2py_src.zip
Optionally install the
tklibrary for Python, if you want the GUI.
sudo apt-get install python-tk
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at. If you purchased this book elsewhere, you can visit, and register to have the files e-mailed directly to you. The code files are also uploaded at the following repository:.
All the code is released under the BSD license () unless otherwise stated in the source file.
To start web2py, access the web2py directory and run web2py.
cd web2py python web2py.py
After installation, each time you run it, web2py will ask you to choose a password. This password is your administrative password. If the password is left blank, the administrative interface will be disabled.
Enter
127.0.0.1:8000/in your browser to check if everything is working OK.
You can use some other options. For example, you can specify the port with the option
-p port and IP address with the option
-i 127.0.0.1. It's useful to specify the password, so you don't have to enter it every time you start web2py; use option
-a password. If you want help on other options, run web2py with the
-h or
âhelp option.
For example:
python web2py.py -i 127.0.0.1 -p 8000 -a mypassword --nogui
This recipe describes how to install web2py in a production environment using the Ubuntu server. This is the recommended method to deploy web2py in production.
We assume that you know how to use a console and install applications using a repository and commands. We will use the latest Ubuntu server at the time of writing: Ubuntu Server 10.04 LTS.
In this recipe we will learn how to:
Install all modules needed to run web2py on Ubuntu
Install web2py in
/home/www-data/
Create a self-signed SSL certificate
Set up web2py with
mod_wsgi
Overwrite
/etc/apache2/sites-available/default
Restart Apache
First, we need to be sure that the system is up-to-date. Upgrade the system with these commands:
sudo apt-get update sudo apt-get upgrade
Let's start by installing
postgreSQL:
sudo apt-get install postgresql
We need to unzip and open
ssh-server, if it's not installed already.
sudo apt-get install unzip sudo apt-get install openssh-server
Install Apache 2 and
mod-wsgi:
sudo apt-get install apache2 sudo apt-get install libapache2-mod-wsgi
Optionally, if you plan to manipulate images, we can install the Python Imaging Library (PIL):
sudo apt-get install python-imaging
Now we need to install web2py. We'll create
www-datain /
home, and extract the web2py source there.
cd /home sudo mkdir www-data cd www-data
Get the web2py source from the web2py site:
sudo wget sudo unzip web2py_src.zip sudo chown -R www-data:www-data web2py
Enable the Apache SSL and EXPIRES modules:
sudo a2enmod expires sudo a2enmod ssl
Create a self-signed certificate:
You should obtain your SSL certificates from a trusted Certificate Authority, such as
verisign.com, but for testing purposes you can generate your own self-signed certificates. You can read more about it at:.
Create the
SSLfolder, and put the SSL certificates inside it:
sudo openssl req -new -x509 -nodes -sha1 -days 365 -key \ /etc/apache2/ssl/self_signed.key > \ /etc/apache2/ssl/self_signed.cert sudo openssl x509 -noout -fingerprint -text < \ /etc/apache2/ssl/self_signed.cert > \ /etc/apache2/ssl/self_signed.info
If you have problem with permissions, use
sudo -i.
Edit the default Apache configuration with your editor.
sudo nano /etc/apache2/sites-available/default
Add the following code to the configuration:
NameVirtualHost *:80 NameVirtualHost *:443 <VirtualHost *:80> WSGIDaemonProcess web2py user=www-data group=www-data Order Allow,Deny Allow from all </Directory> <Location /admin> Deny from all </Location> <LocationMatch ^/([^/]+)/appadmin> Deny from all </LocationMatch> ExpiresActive On ExpiresDefault "access plus 1 hour" Order Allow,Deny Allow from all </Directory> CustomLog /var/log/apache2/access.log common ErrorLog /var/log/apache2/error.log </VirtualHost>
Restart the Apache server:
sudo /etc/init.d/apache2 restart cd /home/www-data/web2py sudo -u www-data python -c "from gluon.widget import console; \console();" sudo -u www-data python -c "from gluon.main \import save_password; \save_password(raw_input('admin password: '),443)"
Enter your browser to check if everything is working OK, replacing
192.168.1.1with your public IP address.
Apache httpd is the most popular HTTP server, and having Apache httpd on a large installation is a must, just like panettone on Christmas day in Italy. Like the panettone, Apache comes in many flavors and with different fillings. You have to find the one you like.
In this recipe, we configure Apache with
mod_proxy, and refine it through
mod_rewrite rules. This is a simple, but robust solution. It can be used to increase web2py scalability, throughput, security, and flexibility. These rules should satisfy both the connoisseur and
the beginner.
This recipe will show you how to make a web2py installation on a host appear as part of a website, even when hosted somewhere else. We will also show how Apache can be used to improve the performance of your web2py application, without touching web2py.
You should have the following:
web2py installed and running on
localhostwith the built-in Rocket webserver (port 8000)
Apache HTTP server (
httpd) version 2.2.x or later
mod_proxyand
mod_rewrite(included in the standard Apache distribution)
On Ubuntu or other Debian-based servers, you can install Apache with:
apt-get install apache
On CentOS or other Fedora-based Linux distributions, you can install Apache with:
yum install httpd
For most other systems you can download Apache from the website, and install it yourself with the provided instructions.
Now that we have Apache HTTP server (from now on we will refer to it simply as Apache) and web2py both running locally, we must configure it.
Apache is configured by placing directives in plain text configuration files. The main configuration file is usually called
httpd.conf
. The default location of this file is set at compile time, but may be overridden with the
-f command line flag.
httpd.conf may include other configuration files. Additional directives may be placed in any of these configuration files.
The configuration files may be located in
/etc/apache2, in
/etc/apache, or in
/etc/httpd, depending on the details of the OS and the Apache version.
Before editing any of the files, make sure that the required modules are enabled from the command-line shell (
bash), type:
a2enmod proxy a2enmod rewrite
With
mod_proxyand
mod_rewriteenabled, we are now ready to set up a simple rewrite rule to proxy forward HTTP requests received by Apache to any other HTTP server we wish. Apache supports multiple
VirtualHosts, that is, it has the ability to handle different virtual host names and ports within a single Apache instance. The default
VirtualHostconfiguration is in a file called
/etc/<apache>/sites-available/default, where
<apache>is
apache,
apache2, or
httpd.
In this file each
VirtualHostis defined by creating an entry as follows:
<VirtualHost *:80> ... </VirtualHost>
You can read the in-depth
VirtualHostdocumentation at.
To use
RewriteRules, we need to activate the Rewrite Engine inside the
VirtualHost:
<VirtualHost *:80> RewriteEngine on ... </VirtualHost>
Then we can configure the rewrite rule:
<VirtualHost *:80> RewriteEngine on # make sure we handle the case with no / at the end of URL RewriteRule ^/web2py$ /web2py/ [R,L] # when matching a path starting with /web2py/ do use a reverse # proxy RewriteRule ^/web2py/(.*) [P,L] ... </VirtualHost>
The second rule tells Apache to do a reverse proxy connection to, passing all the path components of the URL called by the user, except for the first, web2py. The syntax used for rules is based on regular expressions (
regex), where the first expression is compared to the incoming URL (the one requested by the user).
If there is a match, the second expression is used to build a new URL. The flags inside
[and]determine how the resulting URL is to be handled. The previous example matches any incoming request on the default
VirtualHostwith a path that begins with
/web2py, and generates a new URL prepending the remainder of the matched path; the part of the incoming URL that matches the expression
.*replaces
$1in the second expression.
The flag
Ptells Apache to use its proxy to retrieve the content pointed by the URL, before passing it back to the requesting browser.
Suppose that the Apache Server responds at the domain; then if the user's browser requests, it will receive a response with the contents from the scaffolding application of web2py. Thats is, it would be as if the browser had requested.
There is a catch: web2py could send an HTTP redirect, for instance to point the user's browser to the default page. The problem is that the redirect is relative to web2py's application layout, the one that the Apache proxy is trying to hide, so the redirect is probably going to point the browser to the wrong location. To avoid this, we must configure Apache to intercept redirects and correct them.
<VirtualHost *:80> ... / ... </VirtualHost>
There is yet another issue. Many URLs generated by web2py are also relative to the web2py context. These include the URLs of images or CSS style sheets. We have to instruct web2py how to write the correct URL, and of course, since it is web2py, it is simple and we do not have to modify any code in our application code. We need to define a file
routes.pyin the root of web2py's installation, as follows:
routes_out=((r'^/(?P<any>.*)', r'/web2py/\g<any>'),)
Apache can, at this point, transform the received content before sending it back to the client. We have the opportunity to improve website speed in several ways. For example, we can compress all content before sending it back to the browser, if the browser accepts compressed content.
#>
It is possible in the same way, just by configuring Apache, to do other interesting tasks, such as SSL encryption, load balancing, acceleration by content caching, and many other things. You can find information for those and many other setups at.
Here is the complete configuration for the default VirtualHost as used in the following recipe:
<VirtualHost *:80> ServerName localhost # ServerAdmin: Your address, where problems with the server # should # be e-mailed. This address appears on some server-generated # pages, # such as error documents. e.g. [email protected] ServerAdmin [email protected] # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this # directory, # but symbolic links and aliases may be used to point to other # locations. # If you change this to something that isn't under /var/www then # suexec will no longer work. DocumentRoot "/var/www/localhost/htdocs" # This should be changed to whatever you set DocumentRoot to. <Directory "/var/www/localhost # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit AllowOverride All # Controls who can get stuff from this server. Order allow,deny Allow from all </Directory> ### WEB2PY EXAMPLE PROXY REWRITE RULES RewriteEngine on # make sure we handle when there is no / at the end of URL RewriteRule ^/web2py$ /web2py/ [R,L] # when matching a path starting with /web2py/ do a reverse proxy RewriteRule ^/web2py/(.*) [P,L] #> </VirtualHost>
You must restart Apache for any change to take effect. You can use the following command for the same:
apachectl restart
Lighttpd is a secure, fast, compliant, and a very flexible web-server that has been optimized for high-performance environments. It has a very low memory footprint as compared to other web servers, and takes care of the cpu-load. Its advanced feature-set (FastCGI, CGI, Auth, Output-Compression, URL-Rewriting, and many more) make Lighttpd the perfect web server software for every server that suffers load problems.
This recipe was derived from official web2py book, but while the book uses FastCGI
mod_fcgi to expose web2py functionality behind a Ligthttpd web server, here, we use SCGI instead. The SCGI protocol that we use here is similar in intent to FastCGI, but simpler and faster. It is described at the following website:
SCGI is a binary protocol for inter-process communication over IP. SCGI is tailored for the specific task of web server to CGI application communication. The CGI standard defines how a web server can delegate to an external application the dynamic generation of an HTTP response.
The problem with CGI is that, for every incoming request a new process has to be created. Process creation can take longer than response generation in some contexts. This is true in most interpreted language environments, where the time to load a new instance of the interpreter can be longer than the execution of the program itself.
FastCGI addresses this problem by using long-running processes to answer to more than one request without exiting. This is beneficial, in particular, for interpreted programs, because the interpreter does not need to be restarted each time. SCGI was developed after FastCGI experience to reduce the complexity required to convert a CGI to a FastCGI application, allowing better performance. SCGI is a standard module of Lighttpd, and is available for Apache as well.
You should have:
web2py installed and running on localhost (port
8000)
Lighttpd (download and install from)
SCGI (download and install from)
Python Paste (download and install from), or WSGITools ()
If you have
setuptools, you can install SCGI, paste, and wsgitools, as follows:
easy_install scgi easy_install paste easy_install wsgitools
You will also need a script to start an SCGI server, configured for web2py that may or may not come with web2py, depending on the version, so we have supplied one to this recipe.
Now, you have to write the script to start the SCGI server that will be listening to Lighttpd requests. Don't worry, even if it is very short and easy, we provide one ready to copy here:
#!/usr/bin/env python # -*- coding: utf-8 -*- LOGGING = False SOFTCRON = False import sys import os path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path]+[p for p in sys.path if not p==path] import gluon.main if LOGGING: application = gluon.main.appfactory( wsgiapp=gluon.main.wsgibase, logfilename='httpserver.log', profilerfilename=None) else: application = gluon.main.wsgibase if SOFTCRON: from gluon.settings import global_settings global_settings.web2py_crontype = 'soft' try: import paste.util.scgiserver as scgi scgi.serve_application(application, '', 4000).run()except ImportError: from wsgitools.scgi.forkpool import SCGIServer SCGIServer(application, port=4000).run()
Copy the previous script, and put it in the root of your web2py installation with the name
scgihandler.py. Start the SCGI server, and leave it running in the background:
$ nohup python ./scgihandler.py &
Now we are ready to configure
lighttpd.
We provide a simple
lighttpd.confconfiguration file here, as an example. Of course, real-world configurations can be much more complex, but the important parts will not differ much.
Append the following lines to your
lighttpd.conf:
server.modules += ( "mod_scgi" ) server.document-root="/var/www/web2py/" # for >= linux-2.6 server.event-handler = "linux-sysepoll" url.rewrite-once = ( "^(/.+?/static/.+)$" => "/applications$1", "(^|/.*)$" => "/handler_web2py.scgi$1", ) scgi.server = ( "/handler_web2py.scgi" => ) ("handler_web2py" => ( "host" => "127.0.0.1", "port" => "4000", "check-local" => "disable", # important! ) )
This configuration does the following:
Loads the SCGI module into Lighttpd
Configures the server document root to the root of web2py installation
Rewrites the URL, using
mod_rewrite, so that incoming requests to static files are served directly by Lighttpd, while all the rest are rewritten to a fake URL beginning with
/handler_web2py.scgi
Creates an SCGI server stanza: For every request beginning with
/handler_web2py.scgithe request is routed to the SCGI server running on
127.0.0.1at port
4000, skipping the check for the existence of a corresponding local file on the filesystem
Now, check that your configuration is ok:
$ lighttpd -t -f lighttpd.conf
Then start the server for testing:
$ lighttpd -D -f lighttpd.conf
You can start/stop/restart the server with the following command:
$ /etc/init.d/lighttpd start|stop|restart
You will see your web2py application go to the speed of Light(ttpd).
This recipe explains how to run web2py behind a Cherokee web server using uWSGI.
Cherokee is a webserver written in C, similar in intent to Lighttpd: fast, compact, and modular. Cherokee comes with an administrative interface that allows one to manage its configuration, which is difficult to read and modify otherwise. uWSGI is described in its website as a fast (pure C), self-healing, developer/sysadmin-friendly application container server. Cherokee has an included module to talk to uWSGI servers.
Install the package or download, compile, and install the required components. Create the following file in the installation root of web2py, and call it
uwsgi.xml:
<uwsgi> <pythonpath>/home/web2py</pythonpath> <module>wsgihandler</module> <socket>127.0.0.1:37719</socket> <master/> <processes>8</processes> <memory-report/> </uwsgi>
This configuration spawns eight processes to manage multiple requests from the HTTP server. Change it as needed, and configure
<pythonpath>to the installation root of web2py.
As the user that owns the web2py installation, start the uWSGI server:
$ uWSGI -d uwsgi.xml
Now launch the Cherokee administrative interface to create a new configuration:
$ cherokee-admin
Connect to the admin interface with the browser at the following link:.
Go to the Sources section - (A), then click on the + button - (B).
Select Remote Host on (C), then fill the text field at (D) with the IP address, and port to match the configuration in the previous
uswgi.xmlfile.
Having configured the uWGI source, it is now possible to configure a Virtual Host, and redirect requests through it. In this recipe, we choose the default Virtual Host that is used when no other Virtual Host has a better match for the incoming request.
Click on button
(C)to go to Rule Management.
Delete all rules listed on the left. Only the default rule will remain.
Configure the default rule with a uWSGI Handler. Leave the other values unchanged.
If you want Cherokee to serve static files directly from web2py folders, you can add a Regular Expression rule. Click button (A), and select Regular Expression from the drop-down menu at (B). Be aware that this configuration works only if the web2py directory is on the same file system, and is accessible to Cherokee.
Configure the Regular Expressions:
Now you can configure the Static Handler pointing to the applications subdirectory of your web2py installation:
Remember to save the configuration, and reload or restart Cherokee from the administrative interface; then you are ready to start the uWSGI server.
Change to the correct user ID that was used to install web2py; be aware that using root is not recommended.
Go into the root directory of web2py installation, where you saved the configuration file
uwsgi.xml.
Run uWSGI with the
-d <logfile>option, so that it runs in the background:
$ su - <web2py user> $ cd <web2py root> $ uwsgi -x uwsgi.xml -d /tmp/uwsgi.log
Enjoy the speed!
You should have the following:
web2py (installed but not running)
uWSGI (download and install from)
Cherokee (download and install from)
This recipe explains how to run web2py with the Nginx web server using uWSGI.
Nginx is a free, open-source, high-performance HTTP server, and reverse proxy, written by Igor Sysoev.
Nginx, unlike traditional servers, does not rely on threads to handle requests, rather, it implements an asynchronous architecture. This implies that Nginx uses a predictable amount of memory, even under heavy load, resulting in higher stability and low resource consumption. Nginx now hosts more than seven percent of all domains worldwide.
It should be stressed that even if Nginx is asynchronous, web2py is not. Therefore, web2py will use more resources, the more concurrent requests it handles concurrently. uWSGI is described on its website as a fast (pure C), self-healing, developer/sysadmin-friendly application container server. We will configure Nginx to serve dynamic web2py pages through uWSGI, and serve static pages directly, taking advantage of its low footprint capabilities.
You should have the following:
web2py (installed but not running)
uWSGI (download and install from)
Nginx (download and install from)
On Ubuntu 10.04 LTS, you can install uWSGI and Nginx using
apt-get, as follows:
apt-get update apt-get -y upgrade apt-get install python-software-properties add-apt-repository ppa:nginx/stable add-apt-repository ppa:uwsgi/release apt-get update apt-get -y install nginx-full apt-get -y install uwsgi-python
First we need to configure Nginx. Create or edit a file called
/etc/nginx/sites-available/web2py.
In the file, write the following:
server { listen 80; server_name $hostname; location ~* /(\w+)/static/ { root /home/www-data/web2py/applications/; } location / { uwsgi_pass 127.0.0.1:9001; include uwsgi_params; } } server { listen 443; server_name $hostname; ssl on; ssl_certificate /etc/nginx/ssl/web2py.crt; ssl_certificate_key /etc/nginx/ssl/web2py.key; location / { uwsgi_pass 127.0.0.1:9001; include uwsgi_params; uwsgi_param UWSGI_SCHEME $scheme; } }
As you can see, it passes all dynamical requests to
127.0.0.1:9001. We need to get uWSGI running there.
Create the following file in the installation root of web2py, and call it
web2py.xml:
<uwsgi> <socket>127.0.0.1:9001</socket> <pythonpath>/home/www-data/web2py/</pythonpath> <app mountpoint="/"> <script>wsgihandler</script> </app> </uwsgi>
This script assumes that web2py is installed as usual at
/home/www-data/web2py/.
Now disable the default configuration, and enable the new one:
rm /etc/nginx/sites-enabled/default rm /etc/nginx/sites-available/default ln -s /etc/nginx/sites-available/web2py /etc/nginx/sites-enabled/\web2py ln -s /etc/uwsgi-python/apps-available/web2py.xml /etc/uwsgi-\python/apps-enabled/web2py.xml
In order to use HTTPS, you may need to create a self-signed certificate:
mkdir /etc/nginx/ssl cd /etc/nginx/ssl openssl genrsa -out web2py.key 1024 openssl req -batch -new -key web2py.key -out web2py.csr openssl x509 -req -days 1780 -in web2py.csr -signkey web2py.key \-out web2py.crt
You will also need to enable web2py admin:
cd /var/web2py sudo -u www-data python -c "from gluon.main import save_password;\save_password('$PW', 443)"
Once you are done, restart both uWSGI and Nginx:
/etc/init.d/uwsgi-python restart /etc/init.d/nginx restart
web2py comes with a script that will perform this setup for you automatically:
scrips/setup-web2py-nginx-uwsgi-ubuntu.sh
This recipe explains how to configure web2py to run on a shared host with login (but not root) access.
With login or FTP access to a shared host, the user isn't able to configure the web server, and must live within the host's configured constraints. This recipe assumes a typical Unix-based or Linux-based shared host running Apache.
Two deployment methods are possible, depending on how the system is configured. If Apache's
mod_proxy is available, and the host permits long-running processes, running web2py's built-in server as an Apache proxy is straightforward and efficient. If
mod_proxy is not available, or the host prohibits long-running processes, we're limited to the CGI interface, which is simple to configure and almost universally available, but is also slow, since the Python interpreter must run and load web2py for each request.
We'll start with CGI deployment, the simpler case.
We'll assume that the root of your website is
/usr/www/users/username, and that
/usr/www/users/username/cgi-bin is your CGI binaries directory. If your details differ, obtain the actual values from your provider, and modify these instructions accordingly.
For security reasons, here, we also assume your host supports running CGI scripts as the local user (
cgiwrap). This procedure may vary from host to host, if it's available at all; check with your provider.
Download the web2py source to your
cgi-bin directory. For example:
cd cgi-bin wget unzip web2py_src.zip rm web2py_src.zip
Alternatively, unzip the web2py source locally, and upload it to the host through FTP.
In your web root directory, create the file
.htaccess, if necessary, and add the following lines (changing paths as required):
SuexecUserGroup <yourusername> <yourgroup> RewriteEngine on RewriteBase /usr/www/users/username RewriteRule ^(welcome|examples|admin)(/.*)?$ \ /cgi-bin/cgiwrap/username/web2py/cgihandler.py
Change its permissions with the following:
chown 644 .htaccess
Now access, or (depending on your provider).
If you get access errors at this point, examine the most recent file in
web2py/applications/welcome/errors/, using the
tailcommand. This format isn't especially friendly, but it can provide useful clues. If the
errorsdirectory is empty, you may need to double-check that the
errorsdirectory is writable by the web server.
Using
mod_proxy has two major advantages over CGI deployment discussed in the previous recipe: web2py runs continuously, so performance is considerably better, and it runs as your local user, which improves security. Because from web2py's perspective it appears to be running on localhost, the admin application can run, but if you don't have SSL operation available, you may want to disable admin for security reasons. SSL setup is discussed in the Setting up a production deployment on Ubuntu recipe.
Here we assume that you have already downloaded and unzipped web2py somewhere in your home folder. We also assume that your web hosting provider has mod_proxy enabled, supports long running processes, allows you to open a port (8000 in the example but you can change if this port is occupied by another user).
In your base web directory, create a file
.htaccess, if necessary, and add these lines:
RewriteEngine on RewriteBase /usr/www/users/username RewriteRule ^((welcome|examples|admin)(/.*)?)$ \ [P]
Download and unzip web2py as described previously for CGI operation, except that web2py need not be installed in your
cgi-bindirectory, or even in your web documents tree. For this recipe, we'll assume that you install it in your login home directory
Start web2py running on localhost and port
8000with the following command:
nohup python web2py.py -a password -p 8000 -N
The
passwordis the one time admin password that you choose. The
-Nis optional and it disables
web2pycron to save memory. (Notice that this last step cannot be accomplished trhough FTP, so login access is required.)
This recipe explains how to relocate the web2py
applications folder.
With web2py, each application lives in a folder under the
applications/ folder, which in turn is located in the web2py
base or
root folder (the folder that also contains
gluon/, the web2py core code).
When web2py is deployed using its built-in web server, the
applications/ folder can be relocated to some other location in your file system. When
applications/ is relocated, certain other files are relocated as well, including
logging.conf,
routes.py, and
parameters_port.py. Additionally, a
site-packages in the same folder as the relocated
applications/, is inserted into
sys.path (this
site-packages directory need not exist).
When web2py is run from the command line, the folder relocation is specified with the
-f option, which should specify the parent folder of the relocated
applications/ folder, for example:
python web2py.py -i 127.0.0.1 -p 8000 -f /path/to/apps
When web2py is run as a Windows service (
web2py.exe -W), the relocation can be specified in a file
options.py in the web2py main folder. Change the default folder:
os.getcwd()
to specify the parent folder of the relocated
applications/ folder. Here is an example of the
options.py file:
import socket import os ip = '0.0.0.0' port = 80 interfaces=[('0.0.0.0',80), ('0.0.0.0',443,'ssl_key.pem','ssl_certificate.pem')] password = '<recycle>' # <recycle> means use the previous password pid_filename = 'httpserver.pid' log_filename = 'httpserver.log' profiler_filename = None #ssl_certificate = 'ssl_cert.pem' # certificate file #ssl_private_key = 'ssl_key.pem' # private key file #numthreads = 50 # ## deprecated; remove minthreads = None maxthreads = None server_name = socket.gethostname() request_queue_size = 5 timeout = 30 shutdown_timeout = 5 folder = "/path/to/apps" # <<<<<<<< edit this line extcron = None nocron = None
Applications relocation is not available when web2py is deployed with an external web server.
First, create a web2py unprivileged user:
sudo adduser web2py
For security, disable the web2py user password to prevent remote logins:
sudo passwd -l web2py
Download the source package from web2py's official website, uncompress it in a suitable directory (for example
/opt/web2py), and set the access permissions appropriately:
wget sudo unzip -x web2py_src.zip -d /opt sudo chown -Rv web2py. /opt/web2py
Create an
initscript in
/etc/inid.d/web2py(you can use the one in
web2py/scripts/as a starting point):
sudo cp /opt/web2py/scripts/web2py.ubuntu.sh /etc/init.d/web2py
Edit the
initscript:
sudo nano /etc/init.d/web2py
Set the basic configuration parameters:
PIDDIR=/opt/$NAME DAEMON_DIR=/opt/$NAME APPLOG_FILE=$DAEMON_DIR/web2py.log DAEMON_ARGS="web2py.py -p 8001 -i 127.0.0.1 -c server.crt -kserver.key -a<recycle> --nogui --pid_filename=$PIDFILE -l \$APPLOG_FILE"
Change
127.0.0.1and
8001to your desired IP and port. You can use
0.0.0.0as a wildcard IP that match all the interfaces.
Create a self-signed certificate, if you plan on using admin remotely:
sudo openssl genrsa -out /opt/web2py/server.key 1024 sudo openssl req -new -key /opt/web2py/server.key -out /opt/\web2py/server.csr sudo openssl x509 -req -days 365 -in /opt/web2py/server.csr \-signkey /opt/web2py/server.key -out /opt/web2py/server.crt
If you use
importsin
web2py.py:
sys.stdout = sys.stderr = open("/opt/web2py/web2py.err","wa", 0)
Finally, start your web2py service:
sudo /etc/init.d/web2py start
To install it permanently (so it starts and stop automatically with the rest of the operating system services), issue the following command:
sudo update-rc.d web2py defaults
If all works correctly, you'll be able to open your web2py admin:
For simple sites and intranets, you may need a simple installation method that keeps web2py running. This recipe shows how to start web2py in a simple way without further dependencies (no Apache webserver!).
You can see what is happening using
bash to debug the
init script:
sudo bash -x /etc/init.d/web2py start
Also, you can change
start-stop-daemon options to be more verbose, and use the web2py user to prevent interference with other Python daemons:
start-stop-daemon --start \ ${DAEMON_USER:+--chuid $DAEMON_USER} --chdir $DAEMON_DIR \ --background --user $DAEMON_USER --verbose --exec $DAEMON \ --$DAEMON_ARGS || return 2
Remember to set up a password to be able to use the administrative interface. This can be done by executing the following command (change
mypass to your desired password):
sudo -u web2py python /opt/web2py/web2py.py -p 8001 -a mypasswd
IIS is the primary web server for the Windows OS. It can run multiple concurrent domains and several application pools. When you deploy web2py on IIS, you want to set up a new site, and have a separate application pool for its root application. In this way, you have separate logs and ability to start/stop the application pool, independently on the others. Here we explain how.
This is the first of three recipes in which we repeat the process using different configurations. In this first recipe, we set up IIS to act as a proxy for the web2py Rocket web server.
This configuration is desirable when IIS default site is already in production with enabled ASP.NET, ASP, or PHP applications, and at the same time, your web2py sites may be under-development and may require frequent restarting (for example, due to changes in
routes.py).
In this recipe, we assume that you have IIS version 7 or later, already installed. We do not discuss the steps to install IIS7, since it is a commercial product and they are well documented somewhere else.
You also need to have web2py unzipped in a local folder. Start web2py on port
8081.
python web2py -p 8081 -i 127.0.0.1 -a 'password'
Note that when running web2py as a proxy, you should be careful about unintentionally exposing admin without encryption.
Finally, you need to be able to use a IIS Proxy. For this, you will need Application Request Routing (ARR) 2.5. ARR can be downloaded and installed from Microsoft Web Platform Installer available here:
After you download the web platform installer for ARR, open the application and browse to Products on the left-hand side of the screen, as shown in the following screenshot:
Next, click on Add - Application Request Routing 2.5, and then click on Install. This will take you to a new screen, as shown in the following screenshot; click on I Accept:
Web Platform installer will automatically select and install all the dependencies required for Application Request Routing 2.5 to work. Click on Finish, and this will bring you to the Download and Installation screen.
Once you receive the successful message, you can close Microsoft web platform application.
Now open the IIS Manager, and create a new website as directed.
First, right-click on Sites on the top-left in the IIS Manager, and select New Website. This will take you to the following screen. Fill in the details as shown here:
Make sure you select the right IP on which your site will run.
Once the site is created, double-click the URL Rewrite as shown in the following screenshot:
Once in URL Rewrite module, click on Add Rule on the top-right-hand side, as shown in the next screenshot.
Select the Reverse Proxy template under Inbound and Outbound Rules.
Fill out the details as shown here:
Since the Server IP field is the most important, it must contain the IP and port where web2py is running:
127.0.0.1:8081. Also, make sure that SSL Offloading is checked. In the outbound rules for the TO field, write the domain name assigned to the website. When done, click OK.
At this point, everything on your web2py installation should be working, except for the admin interface. Web2py requires that we use HTTPS when a request for the admin interface is coming for a non-localhost server. In our example, localhost for web2py is
127.0.0.1:8081, while IIS is currently operational on
127.0.0.1:80.
To enable the admin, you will need a certificate. Create a certificate and add it to your server certificates in IIS 7, then repeat the previous steps to bind
443to the web2py website we created previously.
Now, visit:, and you will be able to browse the web2py admin web interface. Enter the password for your web2py admin interface, and proceed normally.
Here, we present a production quality configuration, which uses a dedicated application pool run natively in IIS using the ISAPI handler. It is similar to a typical Linux/Apache configuration, but is a Windows native.
As before you will need IIS installed.
You should have web2py already downloaded and unzipped. If you have it already running on port 8081 (or other port) on localhost, you can leave it there, since it should not interfere with this installation. We will assume web2py is installed into
C:\path\to\web2py.
You can place it anywhere else you like.
Then you need to download and install
isapi-wsgi. This is explained below.
First of all, you need to download
isapi-wsgifrom:.
It is a mature WSGI adapter for IIS, based on pywin32. Most of this recipe is based on the documentation and the examples about
isapi-wsgi.
You can install
isapi-wsgiusing the win32 installer:.
You can also install it simply downloading the Python file somewhere into
"c:\Python\Lib\site-packages".
isapi_wsgiruns on IIS 5.1, 6.0, and 7.0. But IIS 7.x must have IIS 6.0 Management Compatability installed.
You may want to try running the following test to see that it was installed properly:
cd C:\Python\Lib\site-packages C:\Python\Lib\site-packages> python isapi_wsgi.py install Configured Virtual Directory: isapi-wsgi-test Extension installed Installation complete.
Now go to.
If you get a
500 errorthat says
this is not a valid Win32 application, then something is wrong and this is discussed here:.
If you see a normal
Helloresponse, then the installation was successful, and you can remove the test:
C:\Python\Lib\site-packages> python isapi_wsgi.py remove
We are not yet ready to configure the web2py handler. You need to enable the 32-bits mode.
We are now ready to configure the web2py handler. Add your web2py installation to the
PYTHONPATH:
set PYTHONPATH=%PYTHONPATH%;C:\path\to\web2py
If it does not exist already, create the file
isapiwsgihandler.pyin the
C:\path\to\web2pyfolder, which contains the following:
import os import sys import isapi_wsgi # The entry point for the ISAPI extension. def __ExtensionFactory__(): path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path]+[p for p in sys.path if not p==path] import gluon.main application = gluon.main.wsgibase return isapi_wsgi.ISAPISimpleHandler(application) # ISAPI installation: if __name__=='__main__': from isapi.install import ISAPIParameters from isapi.install import ScriptMapParams from isapi.install import VirtualDirParameters from isapi.install import HandleCommandLine params = ISAPIParameters() sm = [ScriptMapParams(Extension="*", Flags=0)] vd = VirtualDirParameters(Name="appname",Description = "Web2py in Python",ScriptMaps = sm, ScriptMapUpdate = "replace") params.VirtualDirs = [vd] HandleCommandLine(params)
Recent versions of web2py may already contain this file, or even a better version.
The first part is the handler, and the second part will allow an automatic installation from the command line:
cd c:\path\to\web2py python isapiwsgihandler.py install --server=sitename
By default, this installs the extension for virtual directory
appnameunder
Default Web Site.
Check the current mode for Web Applications (32 bits or 64 bits):
cd C:\Inetpub\AdminScripts cscript.exe adsutil.vbs get W3SVC/AppPools/Enable32BitAppOnWin64 cscript %systemdrive%\inetpub\AdminScripts\adsutil.vbs get w3svc/\AppPools/Enable32bitAppOnWin64
If answer is
The parameter "Enable32BitAppOnWin64" is not set at this node or
Enable32BitAppOnWin64 : (BOOLEAN) False, then you must switch from 64 bits to 32 bits mode for the Web Server. ISAPI does not wok on IIS in 64 bits mode. You can switch with the command:
cscript %systemdrive%\inetpub\AdminScripts\adsutil.vbs set w3svc/\AppPools/Enable32bitAppOnWin64 1
Then restart application pool, as follows:
IIsExt /AddFile %systemroot%\syswow64\inetsrv\httpext.dll 1 ^WEBDAV32 1 "WebDAV (32-bit)"
Or set up a separate pool, as follows:
system.webServer/applicationPool/[email protected] | https://www.packtpub.com/product/web2py-application-development-cookbook/9781849515467 | CC-MAIN-2020-50 | refinedweb | 7,214 | 56.15 |
0
This is my custom module:
class Player(object): def __init__(self, name, score = 0): self.name = name self.score = score def __str__(self): rep = self.name + ":\t" + str(self.score) return rep def ask_yes_no(self, question): response = None while response not in ("y", "n"): response = input(question).lower() return response def ask_number(self, question, low, high): response = None while response not in range (low, high): response = int(input(question)) return response
The program:
import games, random print "Welcome to the world's simplest game!\n" again = None while again != "n": players = [] num = games.ask_number(question = "How many players? (2-5): ", low = 2, high = 5) for i in range(num): name = raw_input("Player name: ") score = random.randrange(100) +1 player = games.Player(name, score) players.append(player) print "\nHere are the game results: " for player in players: print(player) again = games.ask_yes_no("\nDo you want to play again? (y/n): ") raw_input("Press enter to exit.")
This is the error I get when I run the program:
AttributeError: 'module' object has no attribute 'ask_number'
Please help me. Thanks! | https://www.daniweb.com/programming/software-development/threads/381119/attributeerror-my-custom-module-doesn-t-have-an-attribute | CC-MAIN-2017-43 | refinedweb | 177 | 62.24 |
User talk:Lyx
Contents
- 1 USA Tipps
- 2 Cleaning up the wiki
- 3 Wiki-Admin
- 4 about abusefilter extention
- 5 I dont think this ban was deserved
- 6 Wiki edit disputes
- 7 Deleted my user page
- 8 Wo kann man Spammer melden?
- 9 Löschung von Proposed features/House numbers/Karlsruhe Schema
- 10 Xxzme again
- 11 Feedback and change request in upload file message
- 12 Cmuelle8
- 13 False positive with "phone spam 2" filter
- 14 Statistics about Blocked accounts
- 15 Löschantrag für DE:GPS_Units_for_Loan
- 16 Request to delete some pages
- 17 Verdy_p
- 18 Verdy_p Again
- 19 Spam filter false positive
- 20 Admin wanted
- 21 The "childcare" tag on Map Features page
- 22 Category:Labelled for deletion
- 23 Packstation move
- 24 Admin's opinion requested
- 25 Editwar with User:Rtfm
- 26 Verdy p
- 27 Wiki abuse for testing purposes by user Zrcook9494
- 28 Automatic double redirect resolution
- 29 Editwar with User:Adamant1 on deletion of abandoned tagging proposals
- 30 Edit deletion request
- 31 Deletion policy
- 32 warning/block request
- 33 Neuer Admin?
- 34 Renovation of Main Page
- 35 legal threats
USA Tipps
Noch mal vielen Dank für deine Seite, ich finde die ist echt gelungen! Hab jetzt glaube ich ganz guten Durchblick und einige Fragen haben sich geklärt :) --!i!
16:58, 9 November 2012 (UTC)
Cleaning up the wiki
Please take part in this discussion :) --★ → Airon 90 12:58, 12 November 2012 (UTC)
Wiki-Admin
Hallo. Im Forum wird grade diskutiert wie das mit dem Finden neuer Admins läuft. Da du ja Admin bist, könntest du erzählen wie das bei dir ablief? Wir konnten leider keine Doku zu dem Prozess finden. Danke im voraus, --Andi 21:35, 17 March 2013 (UTC)
about abusefilter extention
You can auto-block userpage spam :. But nned to install abusefilter extention. Crochet.david (talk) 08:50, 11 August 2013 (UTC)
I dont think this ban was deserved
This is was first edit and most likely this person was unaware of Commercial OSM Software and Services. There no need to ban people because they are not aware of every single page at our wiki. Xxzme (talk) 16:00, 18 January 2015 (UTC)
- I respectfully disagree: Almost every spammer makes only one single edit, so a ban for a first edit is the normal case for spam blocks. The banned user here made an addition to the page that consisted mostly of a link to a company webpage that had no relation to openstreetmap, mapping or geo information at all. The obvious goal was to achieve a higher search engine ranking by being linked from a high ranking site. Of course this wouldn't work anyway because all external links on the wiki are wrapped with a rel=nofollow attribute. --Lyx (talk) 18:27, 18 January 2015 (UTC)
Wiki edit disputes
Xxzme
Hi Lyx, wiki editing on pages where Xxzme is appearing too is really no fun. He insists on his opinion (which is departing from the established page states) without going into compromises and quickly steps down into ranting, cursing and false commenting about me. Page histories get messy by this.
Xxzme's edits often require cleanup/correction afterwards. Sometimes because he "deduplicated" pages while not moving/merging some content. Or just breaking template inclusion.
I hate too loose my time and good mood by this user. And, no, I do not want to talk with Xxzme again, for good reason. And I am not alone, you may know it.
Please, could you use your admin powers to stop Xxzme? --Aseerel4c26 (talk) 17:28, 18 February 2015 (UTC)
- I would like to support Aseerel4c26's observations with my own, as I have had issues with Xxzme in the past myself on multiple occasions. Xxzme is quick to start edit wars, likes to drastically change the function of established wiki pages, and follows his own idea of how the wiki should be organized, without taking feedback from others into account. I have talked to him in the past, both on his user talk page and elsewhere, but I haven't really found him responsive to criticism.
- Now I will admit that I did not always react correctly to him, some of my responses (e.g. this revert) were unnecessarily hostile. But in the end, it's not just an issue between him and myself (or Aseerel4c26), but imo a systematic issue with Xxzme's approach to collaboration in a community. I hope you take that into account when assessing the situation. --Tordanik 11:09, 25 February 2015 (UTC)
Hi! I think that in the work of the user User:Xxzme more harm than good. Look at the talk page in his profile User_talk:Xxzme. With this, you will not find any discussion before he starts edit. Moreover, in their public discussions in their native language in his profile there is swearing. All of this is not normal and no adds a friendly atmosphere to attract new members, I think.--s-s-s (talk) 14:28, 7 May 2015 (UTC)
Aseerel4c26 continue uncooperative actions while hiding evidence of his vandalism/ignoring talk pages everywhere at wiki
Examples of his vandalism:
- he misunderstood changes and instead of discussing them simply reverts any of my edits [1] without explanation or discussion at talk page
- he keeps reverting my edits about Potlatch 1 without any discussion or explanation. I removed P1 because there dedicated page for outdated software
- reverting my efforts of removing outdated content from wiki while lying about me "silently delete other people's work"...
- Aseerel4c26 uncooperative actions reverting any evidence of previous disputes
- He reverts even my simplest edits without any discussion. In fact, he tried to hide my messages to him
- He reverts my edits without discussion while I was placing labels to mark outdated content. Happily there people who can give better solution than full revert without any discussion. And as always, talk page was completely ignored by Aseerel4c26.
In general, you can easily track for frequent he uses "revert" and "undo" instead of cooperating / discussions at talk pages
My list is not full, please also review his edit history. Xxzme (talk) 17:58, 18 February 2015 (UTC)
Dear Aseerel4c26, Dear Xxzme,
I am sorry to hear that you apparently did not manage to find common ground. I see that both of you make many changes to the Wiki, and as far as I can see you both generally try to make the Wiki a better, more useful tool for mappers. I will have a closer look at the details that you provided and try to find a way out of this situation. Unfortunately I will be traveling until Sunday and not have time to get a full view of the situation before that, so please give me time until next Wednesday to come up with results. I would appreciate if both of you limit yourself to noncontroversial edits until then. I will also invite comments from a few other users. --Lyx (talk) 21:47, 18 February 2015 (UTC)
- Yes as you say, both Aseerel4c26 and Xxzme are very active on the wiki and trying to make the wiki better. So it's a shame to be banning either of them. I think both these people have a tendency to come across rude to others on occasions, due to english language expressions and conversational mannerisms which can be difficult for non-native speakers. We have to make allowances for that.
- Now they're both clashing with eachother. If that wasn't happening then there would be no need for a ban. I think both of them have demonstrated good faith attempts to discuss the matters at hand. In particular I note that Xxzme has a good habit of moving discussions to the talk page, rather than always discussing while reverting. However there's no civil discussion happening now, and this state of edit warring is not acceptable. A ban is needed.
- I suggest we ban Xxzme. That's because in these cases where there is an edit war happening, it seems to me that he is generally pushing a less useful wiki edit. More importantly it seems to me he is more rude. He's obviously been very rude with Aseerel4c26, but in general he seems less able to cooperate peacefully with others in the community.
- A wiki ban doesn't need to be permanent but Xxzme needs to realise that this will happen.
- -- Harry Wood (talk) 11:05, 19 February 2015 (UTC)
Decision
I have now looked at the edit history in more detail, and several people have sent comments here on the wiki, by email or in person. Thanks to all the users that offered advice. Looking at the edits of Xxzme, most of these edits appear to be useful and improve the wiki. Sometimes he makes mistakes, but that happens to everyone and should not be a reason for a ban. However, Xxzme has often reacted rude and aggressive when someone disagreed with one of his edits. This frequently leads to others loosing any hope of a civil discussion and quickly degenerates into an edit war. There is a danger that we drive other editors away if this continues.
I have decided to issue a temporary ban of User Xxzme for 1 month. I hope that he decides to still work on the Wiki after this timeout, and that he will be working in a more cooperative way then.
Deleted my user page
And labelled it as spam. I don't remember what was on it, probably some innocuous links.
Why did you delete it? --Hubne (talk) 02:21, 30 May 2015 (UTC)
- The page contained only bi-lingual spam in Chinese and English. Deleting the page was a mistake, I had not noticed that the spammer had replaced the content of an existing page instead of creating a new one. I apologize for that. I have restored the previous versions of your user page. --Lyx (talk) 08:28, 30 May 2015 (UTC)
- Thanks for apologising and correcting the deletion :) Please tell me this was a rare oversight and that you generally check for pre-existing content before deleting these pages. I am going to put a watch on my user page right after this edit, perhaps that would have been a wise precaution for me to take in the first place. Hubne (talk) 00:14, 4 June 2015 (UTC)
- I also hope this was a rare oversight. At least I can't recall any others right now, except one that I noticed and reverted immediately after it happened. Usually, after noticing a spammer I start with checking the spammers edit history. There, newly created pages are marked different from changes and I treat them differently. Of course, I'm only human so I do make mistakes eventually. --Lyx (talk) 11:24, 4 June 2015 (UTC)
Wo kann man Spammer melden?
Hallo Lyx, auf der BlockList habe ich gesehen, dass du wohl die nötigen Rechte hast, um Spammer in einen highway=* + noexit=yes + oneway=yes laufen zu lassen. Könntest du dir bei Gelegenheit bitte mal User:Poker88 vorknöpfen, der hat die Diskussionsseite von Lübeck/Fahrradstadtplan zweimal um nicht themenverwandte Inhalte erweitert... Danke! – Zusatzfrage: wie/wo melde ich Spammer möglichst effektiv? --zarl (talk) 07:55, 8 July 2015 (UTC)
- Hallo Zarl, wenn es eine vom Spammer neu angelegte Seite ist, einfach den Inhalt mit einem delete|spam Makro ersetzen, ansonsten die Änderung des Spammers rückgängig machen und in den Änderungskommentar das Wort 'Spam' mit unterbringen. Ich gehe die Änderungsliste im Wiki regelmässig durch, andere Admins wahrscheinlich auch. --Lyx (talk) 11:11, 8 July 2015 (UTC)
Löschung von Proposed features/House numbers/Karlsruhe Schema
Ich habe letztes Jahr die Löschung von Proposed features/House numbers/Karlsruhe Schema beantragt, um die Verschiebung des Originalinhalts der Seite rückgängig machen zu können. Der User, der die Seite seinerzeit verschoben hatte, hat übrigens nichts dagegen - insofern ist die Löschung doch eigentlich eine Routinearbeit? Ich wäre dankbar, wenn du dir das mal vornehmen könntest. Je länger der aktuelle Zustand bestehen bleibt, desto schwerer wird eine Korrektur. --Tordanik 12:04, 15 July 2015 (UTC)
- Hi, danke für den Hinweis. Ich bin mir noch nicht ganz klar, welche Folgen eine Löschung für die zahlreichen Seiten hat, die hierhin verweisen. Ich vermute, die Links zeigen dann erstmal ins Leere? Dann sollten wir einen Zeitpunkt abmachen, damit danach gleich die Rückverschiebung der ursprünglichen Seite (und die Korrektur der darauf zeigenden links) anlaufen kann. --Lyx (talk) 17:33, 15 July 2015 (UTC)
- Die Aktion so zu koordinieren, dass die Rückverschiebung und Korrekturen gleich nach der Löschung erfolgen, ist natürlich sinnvoll. Ich hätte heute noch bis zum frühen Nachmittag Zeit dafür (schaue auch regelmäßig ins Wiki), ansonsten wieder ab Montag. --Tordanik 07:31, 16 July 2015 (UTC)
- Ergänzung, nur dass es keine Missverständnisse gibt: Die Diskussionsseite bitte nicht löschen. --Tordanik 07:33, 16 July 2015 (UTC)
- Montag um 18 Uhr würde mir gut passen, klappt das bei Dir? --Lyx (talk) 10:44, 16 July 2015 (UTC)
- Ok, das sollte klappen. Bis Montag also. --Tordanik 11:40, 16 July 2015 (UTC)
Xxzme again
Sorry to raise this again, but Xxzme is causing problems again. Today's issue is (moving the Nominatim instructions so that any links to them will see only a blank page). According to my count currently there have been 156 changes today. Most add no value, but all will require translators and the people who actually maintain the content to check - a huge waste of time for all involved.
Previous recent problems have included personal abuse (see ).
Can Xxzme please be banned again, permanently this time?
- Indeed - thanks. --SomeoneElse (talk) 20:23, 17 September 2015 (UTC)
Feedback and change request in upload file message
Hi, now for another and a better reason ;-))
Cmuelle8
Hallo Lyx,
kannst du mal bitte Cmuelle8 vorübergehend sperren (ähnlich den DWG-Kurzzeitsperren) oder ihm als Wiki-Admin klar machen, dass seine Editwars nicht erwünscht ist und er eine Diskussion nicht verweigern soll? Er führt seit einigen Wochen mit mehreren Benutzern einen Editwar auf DE:Relation:multipolygon und Relation:multipolygon. Siehe dazu die Diskussion im OSM-Forum und eine etwas ältere (ebenda).
Reneman liest zwar im Forum mit, hat aber in dem Thread gepostet und kann als "nicht ganz unbefangen" angesehen werden. --Nakaner (talk) 18:54, 10 February 2016 (UTC)
- Hallo Michael, danke für dein bedachtes Vorgehen :) Grundsätzlich sollte einer Usersperre eine Diskussion direkt mit dem betroffenen User voraus gegangen sein. Es gibt zwar hier einen Anfang aber keine "Verwarnung". Ich habe als Zwischenlösung die deutsche Version DE:Relation:multipolygon für einen Tag gesperrt. In der Hoffnung, dass dieser Zeitraum ausreicht um abzukühlen und Diskussionen mehr Raum zu geben... Gruß René aus Mainz --Reneman (talk) 19:31, 10 February 2016 (UTC)
False positive with "phone spam 2" filter
I'm trying to edit Multiple_values and get blocked by a spam filter. I've done enough edits before that it shouldn't be a karma issue. There's no phone number or external link in my edits. I managed to pass half the page through, but when I try to pass the next paragraph, even after removing all digits from it, I get blocked by "phone spam 2" again. --Vincent De Phily (talk) 08:59, 24 February 2016 (UTC)
- I made some adjustments to that filter this morning. Looks like it was sufficient for your edits to go through now. --Lyx (talk) 22:17, 24 February 2016 (UTC)
- Indeed, thanks. --Vincent De Phily (talk) 22:23, 24 February 2016 (UTC)
Statistics about Blocked accounts
Is there a way to get statistics about the reasons accounts were blocked? or even better ... to get the list of all blocked accounts, without having to scan the list by by block of 50 account as requested on (there is an option for 500 but it does not work, and I suspect there are a LOT of blocked accounts)?
- There is no statistic that I am aware of. For the users blocked by me, as far as I remember there was one user blocked after a lengthy discussion for disruptive behaviour, two or three users blocked by mistake (and quickly unblocked again) and all the other blocks have been for spam or vandalism. --Lyx (talk) 19:11, 14 June 2016 (UTC)
Once an account is blocked, is it removed from OSM users accounts statistics? --jfd553 (talk) 18:29, 14 June 2016 (UTC)
- The Wiki has its own account system that is not related to OSM user accounts (except that many users choose to use the same account name on both).--Lyx (talk) 19:11, 14 June 2016 (UTC)
I understand that the blocked accounts I was referring to are related to the Wiki, not the map. Is there a similar list of blocked accounts for mappers? --jfd553 (talk) 19:29, 14 June 2016 (UTC)
- I don't know of a public list, there might be one for the admins. You would have to ask one of the OSM admins; the Wiki administration has nothing to do with OSM user administration. --Lyx (talk) 19:47, 14 June 2016 (UTC)
- You could try .--Andrew (talk) 19:56, 14 June 2016 (UTC)
Löschantrag für DE:GPS_Units_for_Loan
Hallo Wolfgang,
kannst du bitte die Seite löschen?
Der GPS-Verleih für Deutschland wurde heute eingestellt, auf der deutschen OSM-Seite habe ich bereits die Referenzen entfernt bzw. durch einen entsprechenden Kommentar ersetzt. Da hier im Wiki die deutsche Seite nur einen Eintrag enthält, kann IMO die Seite gelöscht werden. Für eventuelle Rückfragen stehe ich gerne zur Verfügung. Gislars (talk) 17:36, 13 August 2016 (UTC)
Request to delete some pages
Hi. Sorry if I'm disturbing you. It's just a little request to finish a lengthy process I'm making (probably around 1000-1500 pages, categories and templates moved manually in the last 2 weeks).
I've almost finished the move/fusion of "Pt-br:" (brasilian portuguese) pages to "Pt:" (portuguese) but I need the following 8 remaining pages to be deleted so I can move "Pt-br:" pages to "Pt:" to preserve edit history (I could copy-paste but that wouldn't preserve the edit history). I've requested the deletion of them a week ago but the delete request waiting list is a bit long. These deletion requests are uncontroversial since are only redirects and other 2 are in english and edits only by me, this can be verified in each history page:
Pages with redirect edits only:
- Pt:Anonymous edits
- Pt:Key:tracktype
- Pt:OpenStreetMap in the media
- Pt:Tag:amenity=marketplace
- Pt:Tag:amenity=parking
- Pt:Tag:natural=wetland
Other:
- Pt:Getting Involved (in English - not translated)
- Pt:Elements (2 edits by me: 1 exact text copy of Pt-br:Elementos and the other edit is some little changes in words made by me)
Thanks in advance. Zermes (talk) 10:10, 3 October 2016 (UTC)
- I have deleted the pages as requested; as they were flagged for deletion for two weeks now I assume everyone is ok with it. However, as far as I remember quite a few members of the Brazilian community think that pt_PT and pt_BR are sufficiently different to keep these separate versions. So maybe a copy instead of a move might be advised. If you haven't done so yet, please discuss with the community in Portugal and Brazil. --Lyx (talk) 20:17, 5 October 2016 (UTC)
Thank you. About the differences between pt-pt and pt-br they are not so much as some people, those against, say. That matter was discussed a lot 2 years ago on page Category talk:User pt. The result was: 15 users in favor, 1 neutral, and 2 against (you can check this easily). Only 2 users from Portugal were against (by the way I'm from Portugal, but I didn't participated in that discussion), everyone from Brazil and 4 from Portugal were Ok about the "fusion". The majority were in favor. One of those 2 against even said "I'm against the joining because there is differentiation between British English e English America (en e en-gb) so we should differentiate Portuguese from Brazilian". What? Of course this is not true in OSM wiki.
The discussion stoped because some thought only those from Portugal should have a chance and only them should vote in the matter. If the majority from Portugal voted again for the fusion (in 6, 4 voted for the fusion), I think one of them against would say: since the majority are from the capital of Portugal, the others from other regions should have a chance to vote isolated too. That wouldn't stop there... And we could say what about Angola users, Mozambique users, East Timor users? They don't have voice here?
This situation happens in Portuguese Wikipedia, sometimes someone want to split in two (pt-br and pt-pt), but that goes against the rules for creating another project language (must be a distinct language, not a regional dialect or a different written form of the same language). See - this one is the 5th proposal to split! In that page I gave my arguments against the split although I didn't needed since the proposal to split goes against the Wiki-Meta rules and those arguments can be applied here. European Portuguese and Brazilian Portuguese are not languages, they are variations of the same language: Portuguese, with minor differences, like those (more or less) minor differences between British and American English.
Here in OSM wiki, since that discussion in page Category talk:User pt, some people has been tagging for the fusion, like here since 2014, no one say nothing same here and here and moving some pages [2] [3] [4] [5] (and others of course) and no regular editor here (in fact, no one) said something against those proposals, at least from what I know.
I even added in Pt:Main Page in January this wiki/page was for all Portuguese speaking countries: Angola, Brasil, Cabo Verde, Guiné-Bissau, Macau, Moçambique, Portugal, São Tomé e Príncipe, Timor-Leste and places like Goa, Damão e Diu. This page will be the last one I will make the fusion.
After moving more than 1000 pages since 2 weeks ago (21 September), non stop everyday, I only had one user asking what I was doing and where it was decided. I've pointed the same page where the discussion took place 2 years ago and he said Ok and was happy about that. By the way, he talked to me in "Brazilian Portuguese" and I responded to him in "European Portuguese" and we understood our selfs very well. I think this says everything, we don't talk different languages. Anyway I take full responsibility for my actions of course. I've read those pages, every argument and I thought since the majority vote in favor, and the arguments in favor are strong and practical, I will do the necessary work. Many times in the past, I didn't created a "Pt:" version of a tag/key page if there was already an existing one in "Pt-br:". Why? Because I knew someday someone would do the hard work to join them. Deleting one/or simply redirecting would be a disrespect for the editors of one of the pages. For me it was more hard and time consuming to join 10-20 tiny pages (I'm still doing it now in Pt:Map Features sub-pages, but these ones are longer and I'm updating them based on the English version) than moving manually more than 1000 pages.
Sorry for the long text. Any way, thank you again, for you advice and concern too. Zermes (talk) 00:08, 6 October 2016 (UTC)
Verdy_p
Hallo Wolfgang,
could you please help Verdy_p to take a break of a few days? Since our last conversation in real life he has continued his changes and moved lots of pages. I hope that during his break he understands why he was blocked. --Nakaner (talk) 22:34, 6 December 2016 (UTC)
Verdy_p Again
Hallo Wolfgang,
ich glaube, die letzte Sperre von Verdy_p war für die Katz. Neulich hat er die Leute auf der Mailingliste Ulmer-Alb verärgert. Mir ist egal, was und ob du machst, aber ich wollte dich nur informiert haben. Am sonstigen Editierverhalten scheint sich nicht allzu viel verbessert zu haben. Die meisten Änderungen sind immer noch unkommentiert. Er ist mir nur seltener durch mein Sichtfeld gelaufen. --Nakaner (talk) 09:26, 19 February 2017 (UTC)
Spam filter false positive
Hi, I presume you are a sysop. If so, can you please whitelist, or remove from any blacklist 'geolocation.ws'. I am simply trying to edit an existing page, but am prevented from saving due triggering your spam filter. I hasten to state I did not add said blocked text - it seems to be transcluded from an existing template.
Thanks. Teutonic Tamer (talk) 01:56, 30 June 2017 (UTC)
- Hi, that string is not listed in any of my spam filters, and the abuse filter log did not record any blocked edit attempts by you, so you are probably hitting a different filter. Can you show the exact message that you get when trying to save your edit? That would help me to identify the filter that is causing the problem. --Lyx (talk) 05:45, 30 June 2017 (UTC)
Admin wanted scheint etwas festgefahren. Da hilft nur noch ein Admin. Danke! Mmd (talk) 16:19, 21 July 2017 (UTC)
- Danke für das Locken der DIDOK Seite. --Datendelphin (talk) 18:27, 24 July 2017 (UTC)
The "childcare" tag on Map Features page. techlady
- There appears to have been a misunderstanding. As far as I can see you edited the "Map Features" page directly; that will not work. I suggest you revert your changes on that page. Instead you need to edit the Template:Map_Features:amenity which opens if you click on "This table is a wiki template with a default description in English. Editable here." on the bottom of the amenity section. On that template you have the documentation on what the fields in that template do, and below the documentation there is the actual template that you need to edit. Please make use of the "preview" function when editing this template and only save your changes when your finished, because changes to that template will trigger the re-rendering of more than a hundred pages on the Wiki. --Lyx (talk) 22:51, 6 September 2017 (UTC)
- Note: easiest way to add childcare to the "Education" block in the amenity template will be to open the template as described above while logged in, then scroll down until you find the "Education" block header and the click on the source edit link next to it. That way you will only open the table for the "Education" block. Then copy an existing row definition (which starts with a line beginning with |- and ends immediately before the next such line). Move this copy to the position in the table where you want to insert the new row and adapt the individual lines, so when you copied e.g. the "college" block then "college" becomes "childcare" in your copy. Look at e.g. the music_school definition to see an example without an icon or photo. --Lyx (talk) 23:07, 6 September 2017 (UTC)
Lyx, thanks again. I'll proceed carefully. I was not sure whether to put it under Education, but it seems the best of the options. Lyx, At this point I can find no rendering icon for this tag. Do you know what is accepted practice? I know of a free image source with icons. I could search there. Also, do they have to be SVG icons? I bought three nonattribution icons for $1 each. I'd like to share them with you for your opinion, but don't have your email. I'll also try to contact other people who worked on the tag. I'm still not sure how to get the icon hosted. Where do I upload it?
Lyx, Thanks again for your help, but I've had to put the addition of "amenity=childcare" to the Map Features page on hold while I deal with the icon issue. I have learned the technical specs, but am still checking the licenses of the icons I have suggested. It may take a while to work out all that.
Category:Labelled for deletion
Can you look at Category:Labelled for deletion? There are 500+ entries, some since 2016 (I am unable to do this as I have no sysop rights) Mateusz Konieczny (talk) 14:41, 2 January 2018 (UTC)
- Can you consider looking at this category? Backlog is smaller but there are still hundreds of pages stuck there Mateusz Konieczny (talk) 08:26, 30 January 2018 (UTC)
- @Lyx: Danke, fleißig, fleißig! :-) --Aseerel4c26 (talk) 22:43, 3 February 2018 (UTC)
- Thanks for processing it, now it is almost empty! Mateusz Konieczny (talk) 08:14, 25 February 2018 (UTC)
- Can you look at it again? It filled with 300+ entries. BTW, do you have any idea who and how may be nominated for sysop? It seems that you are the sole person with both sysop rights and using them Mateusz Konieczny (talk) 14:13, 8 April 2018 (UTC)
- Several users are currently checking if all the wiki pages for the towns in Germany are really necessary. Most of them are stubs or have not been edited for 3 to 8 years. In addition, user User:Raubraupe proposed many pages for deletion which are not linked from any other page and/or almost empty (disussed at OSM-Samstag in Bonn two weeks ago). --Nakaner (talk) 17:21, 8 April 2018 (UTC)
- Sorry for bothering you again but Category:Labelled for deletion got filled again Mateusz Konieczny (talk) 08:59, 24 June 2018 (UTC)
- I noticed that, but many of the delete requests look somewhat dubious to me, e.g. the delete request for IT:Tag:power=tower. I think there is some more time needed for wiki users to notice, review and maybe revert these delete requests. --Lyx (talk) 09:23, 24 June 2018 (UTC)
- Power tower one was cause by deletion request at Template:Kosmos rule that got included on all pages that included this template, mostly power related. I will look at and remove instances of this template about a software as such software-specific templates should not appear anyway. It should get rid of some spurious requests. Mateusz Konieczny (talk) 09:36, 24 June 2018 (UTC)
- There are also many cases like - user page with rendering rules of some program. Adamant1 claims that this program is dead and marked such pages for deletion. I think that as long as user pages are OSM related and are not created on massive scale it is not OK to delete or edit them. What you think is preferable - deleting them or reverting Adamant1 edits? Mateusz Konieczny (talk) 09:45, 24 June 2018 (UTC)
- Thanks for clearing up the links in the Tag pages. Regarding user pages: I will not delete them for now to give the users themselves more time to revert the delete request on their pages or start a discussion with Adamant1. I'm not happy with these delete requests and think a discussion beforehand would have been the right thing to do; on the other hand if no users challenge these requests the pages will be deleted eventually (just not now). --Lyx (talk) 14:20, 24 June 2018 (UTC)
- Lyx, I reverted all the deletion tags I had added to user pages that I could find. I apologize for doing that. I was not aware it wasn't a problem at the time. As it isn't stated anywhere that it shouldn't be done. Although I still should of known better anyway. Luckily Mateusz Konieczny brought it to my attention though. --Adamant1 (talk) 07:15, 31 July 2018 (UTC)
> This category is full again. Could you maybe resolve the straightforward cases (no links, no discussions, previous deletion proposals)? Then I can look at the others and possibly remove their deletion requests. I just reviewed the deletion proposals and added some pages to the category. --Tigerfell
(Let's talk) 10:15, 1 December 2018 (UTC)
- I'm a bit short on free time the last couple of weeks, so I can't promise to clean it all up. But I'll give it a try. --Lyx (talk) 21:29, 1 December 2018 (UTC)
- Great, thank you! --Tigerfell
(Let's talk) 10:40, 2 December 2018 (UTC)
Hey, could you please delete File:Knut IMG 8095.jpg? I know that there are links and templates pointing to it, but there is a file in Wikimedia Commons that is the exact same image with the same name [6]. As far as I understand, every time you write
[[File:Knut IMG 8095.jpg]], the parser checks if this file exists in this wiki and if not, it checks Wikimedia Commons. As the filenames are the same, deleting this file would effectively work without breaking links. Please correct me if I am wrong though.
By the way, thank you for revising this category again. U30303020 (talk) 18:34, 2 September 2018 (UTC)
- Well, without checking the details, I deleted the file and checked one of the pages using the image, in this case Animals. It did not work (i.e. the image was not displayed any more), so I restored the file. --Lyx (talk) 21:41, 4 September 2018 (UTC)
Thank you for trying it out. Too bad it did not work. I replaced all of links to this file with a different one. Then you can delete it as usually. U30303020 (talk) 15:20, 5 September 2018 (UTC)
Packstation move
Hi Lyx, could you please move Packstation to DE:Packstation (with talk page and overwrite the redirect). See last section on Talk:Packstation. Thanks! --aseerel4c26 (talk) 08:17, 26 February 2018 (UTC)
- Done --Lyx (talk) 21:49, 26 February 2018 (UTC)
- Danke! :) --aseerel4c26 (talk) 06:55, 27 February 2018 (UTC)
- Thanks to everybody who helped to fix this page! Mateusz Konieczny (talk) 08:45, 27 February 2018 (UTC)
- Achja, da du jetzt eh Bescheid weißt, verschiebe bei Gelegenheit bitte noch DE:Packstation/temp in den Hintergrund. Alle Beteiligten scheinen zufrieden zu sein. --aseerel4c26 (talk) 22:37, 28 February 2018 (UTC)
Admin's opinion requested
Hi Lyx,
could I get an opinion from you regarding my suggestion to revert and protect Proposed features/Public Transport. I posted it on the talk page and in the mailing list. However, nobody ever replied which could either be understood as accepting the suggestion or due to the fact that I used the wrong channels...
Thank you. U30303020 (talk) 11:41, 2 June 2018 (UTC)
- Hi, I don't think an admins opinion is in any way more important than others here. But I'll give you my opinion anyway :-) I don't think it is needed or even helpful to revert and protect that page. If you want to reference the version that was actually voted on, you could use the direct link to that version that is also linked in the information block on top of the page. --Lyx (talk) 21:48, 2 June 2018 (UTC)
Editwar with User:Rtfm
User:Rtfm has started/particpated (depends on the point of view) in multiple edit wars on
motorcycle_friendly=yes. He started a tagging proposal which had a voting with lots of sockpuppets (and lacking email to the Tagging mailing list). Although the proposal faced unanimous refusal, he create a feature page which was later moved into the
Proposed_features/ "namespace". Other users (Matheusz, Polarbear and myself) added warnings on these pages about the history of the tag. He removed them several times. He continued his editwar today.
User:Mateusz Konieczny, User:Polarbear w and myself told him in the past that his behaviour is not accepted. You can find the whole story on User_talk:Rtmf. Mailing list discussion are linked from there. Could you please take actions like reverting his last edit with an admin hat on, locking page(s) and telling him that such actions are not welcome here? --Nakaner (talk) 21:17, 16 July 2018 (UTC)
- Ops, I already reverted. Though locking this page may be a good idea Mateusz Konieczny (talk) 14:56, 17 July 2018 (UTC)
- I just found Tag:motorcycle friendly=customary and added
{{delete proposal}}. I'll buy some fresh junk food. --Nakaner (talk) 22:55, 19 July 2018 (UTC)
Verdy p
I was very surprised to see your indefinite block of User:Verdy p. Please can you explain what happened, and where this was discussed? Andy Mabbett (User:Pigsonthewing); Andy's talk; Andy's edits 10:26, 8 August 2018 (UTC)
- Where it is discussed ? -- Naveenpf (talk) 10:51, 8 August 2018 (UTC)
- User:Verdy p has been blocked after ...
- ______SNIP____ Moved to User talk:Verdy_p#Blocked
- There was big discussion here, but I'm going to move User:Lyx's explanation and the following discussion over to User talk:Verdy_p#Blocked which is a more logical and easy place to find it (particularly the explanation of the block is important)
- -- Harry Wood (talk) 10:17, 28 August 2018 (UTC)
- This is not such a good idea since it makes the discussion editable at will by verdy_p himself. -- If any further proof of verdy_p's temper was required, I point interested readers to et al. where verdy_p continues his feud with user apm_wa. --Woodpeck (talk) 13:02, 9 September 2018 (UTC)
- Hello Harry, good to see some transparency and discussion on the block. Since this is a crowdsourcing platform and majority decision has the more value. The minority has to follow. Anyway moderators of wiki should have a process to block contributors. For spammer we can right away block -- Naveenpf (talk) 02:30, 10 September 2018 (UTC)
Wiki abuse for testing purposes by user Zrcook9494 adds random NASCAR content, which has nothing to do with OSM. Kindly request to block this user and delete all of their changes. Mmd (talk) 19:11, 20 October 2018 (UTC)
Automatic double redirect resolution
Hi Lyx,
I occasionally check for double redirects. Now, a user contacted me on my talk page and suggested to resolve redirects automatically. There is a server setting that does that, but the MediaWiki handbook mentions that it may make page move vandalism worse. I do not think this is a problem here, because page moves are restricted to autoconfirmed users only. You are dealing with spam and vandalism in this wiki. What is your experience?
If that seems to be okay for you, I would request the tech team at GitHub to change the setting. --Tigerfell
(Let's talk) 08:52, 16 November 2018 (UTC)
- I can't see how this setting could be abused for spam, and other forms of vandalism are indeed kind of rare in this Wiki. On the other hand I have no idea how much work it is to clean up the double redirects here, as I have never tried it. So if it makes your life easier, feel free and go ahead. --Lyx (talk) 21:28, 17 November 2018 (UTC)
Editwar with User:Adamant1 on deletion of abandoned tagging proposals
I am having an edit war with User:Adamant1 on the deletion of old and abandoned tagging proposals (recently Proposed_features/agricultural_access). Could you please intervene and take appropriate measures?
He placed {{delete|reason}} on a lot of tagging proposals which had been created a few years ago and marked as abandoned later. I think that they should be kept for archival reasons. He thinks that they (might?) make readers use the tags proposed there. I asked him to revert his deletions in July 2018 (see the archive of his talk page, section "Blanking" second round). I am not alone, @Mateusz Konieczny, @Tordanik, @Constantino and @Polarbear w complained about similar actions by User:Adamant1. --Nakaner (talk) 09:44, 29 January 2019 (UTC)
- How exactly is adding deletion proposals to pages that you never touched "Edited warring"? Also, I never said I added the deletion proposals on the pages because I think other users will use the tags. I did it because the pages have zero content and haven't been edited since the proposals where created. Which I clearly state in the deletion proposals. Further, the pages aren't from "a few years ago." A lot of them are from 2010 or earlier and haven't been edited in as long. Finally, a lot of the pages I requested be deleted originally got deleted by Lyx himself. Despite the condescension of you and other people that had a problem with it, decided to gang up on me, and threw insults. Including Verdy_P who got told multiple times by SomeoneElse to back off me because I was in the right. I don't appreciate being miss-represented or having crap made up about my edits. If any of you had issues with deletion proposals I would have fine discussing them, but you never did. At this point your behavior is borderline harassment and I'm pretty sick of it. That goes for the rest of your gang also. --Adamant1 (talk) 10:00, 29 January 2019 (UTC)
- Nobody is "ganging up" here, or harassing anybody. It is just more people wanting to preserve old proposals for reference, than you wanting to delete them. You could just accept that and stop probing the issue every six months. Mankind is keeping archives for thousands of years, so it does not matter if the proposal was created 2010 or 2012. --Polarbear w (talk) 10:43, 29 January 2019 (UTC)
- Its "ganging up" when every time one of you has an issue with something I do you ping everyone else and attack me together. There was also that time one of you requested people on the mailing list to attack me (which is totally harassment). Otherwise, there's no reason Nakaner couldn't have just dealt with problems he has with me on his own, by contacting me on my talk page. I'm a pretty reasonable person. Instead of lying about a none existent edit war. Also, I'm not "probing the issue every six months." They are completely different pages then the ones I requested be deleted six months ago (a lot of which where deleted. Despite your rhetoric and the repeated fits by everyone). Claiming I'm doing this based on a six month old grudge that I don't have is also harassment.
- I happen to be cruising through proposals randomly and saw a few blank ones. So I thought id request they be deleted. Which I'm perfectly free to do. It had nothing to do with the previous episode except in your paranoid minds. Last time I checked anyone can request a page be deleted whenever they feel like. Nakaner does it, Mateusz Konieczny does it, I'm sure you do, and I know others do. So I don't need to be harassed by any of you about it every time. I don't need your permission or to clear it with you first either. Originally I had permission from SomeoneElse to request the pages be deleted that Nakaner reverted because he clearly doesn't care about the opinions of admins unless he thinks they are going to side with him. Lastly, the age thing was only important to Nakaner as a fake excuse to throw a temper tantrum about the whole thing. The main reason I requested the pages be deleted was because they are essentially blank. That was it. Get over it. If this continues I'll just report you and Nakaner to the DWG. --Adamant1 (talk) 11:14, 29 January 2019 (UTC)
- I and many other tried to reach out to you last year and asked you to stop adding {{delete|reason}}. After some time, you stopped. At that time, I reverted a few of your edits on the pages we are talking about, Proposed_features/agricultural_access is among them. Yesterday, you reverted my revert on this page which is the beginning of an editwar. I can use my spare time for better purposes than editwarring with another user on the wiki. That's why I am escalating this issue to a sysop because earlier attempts to reach out to you seem to be unsuccessful (otherwise you would not have reverted my revert).
This is a usual behaviour in OpenStreetMap (if someone fails to recognize my point, I will ask other users for a second opinion and escalate it to an admin if they agree me and the person in question continues their "bad" behaviour. As Polarbear wrote, nobody is harassing you. We complain about your behaviour, not your person. Please be aware that the OSM community has members beyond the border of the U.S. and that other countries have different cultures of feedback. Using the English languages does not mean that I follow US feedback culture rules. Please keep that in mind and don't put too much weight in the words of non-native speakers. --Nakaner (talk) 11:01, 30 January 2019 (UTC)
- I'm sick of re-litigating this every time I make an edit you people don't like. It wasn't "many" that asked me stop. It was just you and your three buddies. Ultimately, there were more people that said it was OK and probably useful to have the pages be deleted. Including SomeoneElse, who agreed with me that they might make it harder for new users. Verdy_P also went off on me about it for the same reasons you did and got told to leave me alone three times. not to mention the pages you didn't reverted eventually got deleted. So you can go off about how I should have stopped my "bad" behavior, but you were clearly the one in the wrong. There's no reason I would never request another page be deleted just because you or Polarbearing say so. Anyone, the ones I requested to be deleted this time had nothing to do with the other ones. Its ridiculous to connect them to try and make it look I have a pattern of "bad" behavior, when its just not there. I consulted an administrator and other users, all who agreed with me, and I decided to continue based on that. Which I've already told both you and Polarbearing. Even if I hadn't though, I can request a page be deleted for whatever reason I want, whenever I want. I don't need your permission to edit things and there's still procedures for reverting someone. Which don't include "because I don't like the edit and I told them not to do it."
- Harassment isn't confined to personal attacks. Its any aggressive behavior or the use of intimidation to persuade someone not to do something. Having five people boss me around on my talk page at the same time by telling me what to do, along with requesting other people on the mailing list do the same, instead of engaging in an actual discussion about the pages is both aggressive and intimating. It has nothing to do with language or culture. Its the particular tactics choosing to use. From the beginning non of you said anything specific about any specific page. It was just "stop doing it." If you had pointed out a specific thing that was worth saving on a specific page, I would have fine with that and we could have talked about it, but you didn't. Not once. And you have continued to ignore that SomeoneElse and others said it was fine. He also told Verdy_P to leave me alone three times for him making the same arguments you guys are and all the pages you didn't revert were eventually deleted. I've said it to all of you at last twice, but you still push the issue like none of that happened and I'm just a rogue editor that won't listen to reason. That's the epitome of harassment.
- As far as the one page I reverted that you claim is "edit warring." The original reason you gave for reverting me was because of a conversation that never happened. Nothing in anything you or anyone else said in the supposed conversation related to that page. It was mentioned exactly zero times. Using a conversation that never happened as a reason to revert someone is not a valid reason for doing the revert. Like I said, it has to be based on more then "because I feel like it." So I feel like I'm in the clear there. If you have an issue with it though, feel free to message me on my talk page or on the pages discussion page about what exactly on that specific page is worth that page not being deleted. I'm perfectly willing to get rid of the banner if there's a reason to, but I'm not going to just because you vaguely, generally, like a year ago, said to not request "pages" be deleted or something. I don't think you or any of the others even looked over any of the pages in the first to see if there was anything that would make them worth saving. Otherwise, you would have just pointed out what those things were from the start and included them in your revert comments. —Preceding unsigned comment added by Adamant1 (talk • contribs) 30 January 2019
- Since non-personal statements have been requested: I think that abandoned proposals are generally worth keeping (if only to avoid people making a grand new suggestion without knowing about previous art). I can see how individual abandoned proposals that contain very little useful content might occasionally be deleted, and in these cases I would expect the person suggesting the deletion to give a clear reason. If such deletion requests were made on a case-by-case basis as someone stumbles over something useless, I would be more inclined to support the deletion than if a single person made a "gardening" effort. Generally, if you ever find yourself in a situation where you feel others are "ganging up" on you, and you feel compelled to write long essays that frequently contain the phrase "you people", it could be a sign that you should take a step back and maybe ask a third, independent party how they would judge the situation. --Woodpeck (talk) 22:08, 30 January 2019 (UTC)
- I think we need a general discussion about which outdated information we want to keep and how we want to make clear that this is outdated (so it does not confuse other readers). So, I started a forum thread about it. Please join: --Tigerfell
(Let's talk) 22:19, 30 January 2019 (UTC)
- Woodpeck, I appreciate the non-personal statement about it. I agree with your analysis. That being said, I never made a "gardening effort." Nor would I. Even if I had though, it doesn't justify the rude, disingenuous, bossy response I repeatedly got from Nakaner and the others. Also, I only used the phrase "you people" once in my last message because I was in between classes when I wrote it and I didn't have time to list off everyone's names. I refereed to them in "proper form" in plenty of other places though. Also, I already "took a step back" and asked a third independent party originally, SomeoneElse (along with multiple wiki users). Both him and they agreed with me that the pages could be cleaned up and that I wasn't doing anything wrong. As much as I did that, Nakanar and his friends could accept that they were bullying me and are in the wrong. Btw, for someone that goes off about how "fluffy bunny language policing" is a bad thing, you sure seem to do it a lot. I didn't call them "you people" out of anything except that I was in a rush at the time. Its not like they haven't said similar things themselves anyway. I don't expect you to call them out on it or the other harassment though. So don't bother.
- Tigerfell, thanks for creating the forum post. I'll be sure to participate in it. Hopefully it will lead to something more productive then the current tactics being used by Nakaner Et al. Although the whole thing was already discussed six months ago and went in my favor, I'm perfectly willing to discuss it again. Maybe Nakaner Et al. won't ignore the discussion like they did last time and will accept actually accept that some of the pages can be deleted. I'm not going to hold my breath. --Adamant1 (talk) 00:05, 31 January 2019 (UTC)
- I appreciate Tigerfell's attempt to start a broader discussion but hope the discussion will remain in one place.. or someone summarizes the results here.
- @Adamant1: I don't think anyone is bossy here. This wiki is pretty old and if there are still proposals from 15 years ago it is because there has been a broad consensus for 15 years to keep them. I need to look at some of those old proposals if I want to figure out how some feature started or why something was done (or not done) in a certain way. If you find it confusing to find stumble over proposals maybe the wiki search needs improving or you can use more sophisticated search engines. RicoZ (talk) 20:26, 31 January 2019 (UTC)
- @RicoZ, I didn't necessarily say anyone was bossy here. I said they were bossy when this originally came up and that I wasn't going to just take it this time like I did back then. Further, if you had of actually bothered to read what I said or the deletion proposals themselves, you would have noticed that the age of the proposals was a minor thing and that it was mostly about the fact that they don't have any useful, or really any, content. So the whole keep the pages to "figure out how some feature started or why something was done (or not done) in a certain way" argument your making here is a mute point. While I agree the search could be improved, it ultimately has zero to do with me "confused." Other people complained about it to and we shouldn't have to use a different search engine, because you think its fine The one here should work how its suppose to. Also, plenty of other people agree that old empty pages should be cleaned and lots where. I could make the same argument you just did about the search and say if you think the content on the proposals pages are valuable, just find it somewhere else. I'm not going to because its a weak, dismissive argument. Everyone's views should be listened to and considered, instead of blown off. Even if you don't agree with them. --Adamant1 (talk) 04:59, 1 February 2019 (UTC)
Hello everyone, sorry for being silent for a while. The amount of time I have available for OSM is unfortunately rather limited at the moment, and I would prefer to spend it in a productive way. This discussion here appears to have some aspects that are not exactly helpful, so let me remind you of a few things. You (the reader) probably care deeply about OSM, and when you see someone doing things to your beloved project that you deem wrong you might be tempted to "attack" that person that you think is harming the project. Don't do that, please. It is very likely that this other person also cares as deeply about OSM as you do, and does what she thinks is in the best interest of OSM. So, both you and the other person have the best interest of OSM in mind, you just do not agree (yet) what that best interest is. So, if someone does something you don't agree with, please tell all of us that you don't think that particular something is a good idea, and why you think so; and please ask the other person why they think it should be done, not as an accusation but to find out. Try to find common ground starting from there, and always assume that the other person is acting in good faith. The talk pages are the right place for this.
On the issue of deleting wiki pages, let me tell you how I do handle delete requests usually (other admins might do this differently). If a page has ever been touched by a single author and that author requests deletion, I'll delete it. If a page has had a deletion request for quite some time and nobody has spoken out against it being deleted, and that page is not linked from other pages, has no significant content on itself or other language versions, I'll delete it. The length of "quite some time" might be a few days for automatically generated lists to a few months or longer for personal pages. If a deletion request is disputed based on the content of that individual page, I usually wait for all parties to come to a conclusion. If a deletion request is opposed not based on the content of that particular page but based on "all deletions are evil and need to be avoided", I might ignore the opposition.
A current example would be Proposed features/Tag:natural=fungus. Basically everyone ever editing that page except the original author agrees that that page is complete utterly useless garbage. However, a deletion request was removed with the given reason "(Please, stop trying to delete nonempty proposals. Yes - abandoned proposals are inactive, it is not sufficient reason to delete them.)". Here I would have hoped that the user removing the deletion request had actually spent some time on studying that page and its history, and maybe write to the talk page why he opposes that deletion request. Maybe he could show us that this page actually has value that we had overlooked? On the practical side: I will not get around to act on deletion requests in the next couple of days, so you could use the time to try to find some agreement on how to proceed. Please continue the discussion either here or in the forum thread started by user Tigerfell (hopefully with someone writing a summary here). --Lyx (talk) 21:12, 1 February 2019 (UTC)
- Thanks for explaining your criteria for deletion. It is obvious that the decision to actually delete something (unless obvious spam) is not an easy one and requires plenty of care from the admin.
- I see the "high cost" of deletions as the main reason to delete very very cautiously. If a page is deleted it is not just content but all history, irreparably. For this reason everyone who has ever touched the page will be tempted to very carefully double check the deletion request and - if someone does many deletion request like Adamant1 did the slightest doubt over any single of the deletion requests will cause general disapproval for good reasons.
- Regarding natural=fungus it is certainly worth discussing whether it is worth to keep such proposals.. in this case it might have some worth as an obvious example of how not to do it. RicoZ (talk) 22:13, 1 February 2019 (UTC)
- Regarding natural=fungus, while the original page was nonsense I have changed my opinion on mapping fungi and replaced the proposal with one that imho makes sense. In short, at least one specimen is believed to be 2400 years old and covers an area of about 8.8 sq km. RicoZ (talk) 20:39, 2 February 2019 (UTC)
- Regarding natural=fungus and similar stupid proposals - main value lies in that once similar proposal appears again one may link existing consensus rather than explain for nth time the same thing. Hopefully some people who wanted to propose something similar used search, found it and discovered why it is a bad idea. I personally found existing tag via abandoned proposal, as my search found proposal page that used a different language not present in the normal Wiki page. Mateusz Konieczny (talk) 21:51, 6 February 2019 (UTC)
- @Mateusz Konieczny There's probably zero chance of that happening with a proposal like natural=fungus. Which you say yourself is a "stupid proposal." There has to be a point where the canard of the mythological repeated proposal unicorn doesn't justify keeping some pages around "just because." In most cases it has almost zero chance of happening. If it does though, either know one is proposing those pages be deleted in the first place, the original proposal page doesn't have any content that would be useful if its brought up again, or it will be so far in the future it might be worth revisiting again anyway.
- Its really nonsensical to say no pages should ever be deleted, just because you don't want to repeat yourself. For one, its pretty slim you will. Also, the Wiki doesn't revolve around your preferences. I.E. you could choose just to not participate in a discussion if it does ever come up again and maybe other people are fine with repeating themselves or revisiting things later if need be. I know I'm fine with doing both. Finally, and most importantly, having to repeat yourself is just life. I've repeated myself interacting with you and your buddies. I deal with it though. I'm sure you can to. Sometimes there's value in revisiting things.
- Its not like you ultimately care about pages being deleted anyway.Its weird your making such an issue out of it in the first place since you and your buddies do it all the time yourselves. Including on this discussion page. I don't remember you chiding Nakanar that much (or at all) when he said he was going to "get the snacks" and put a deletion proposal for the motorcycle_friendly article. Or is that different because he's a member of the "in group" and I'm not? I seem to remember one of you at some point saying I shouldn't edit articles because I don't have enough edits to know what I'm doing. It seemed like some really stupid circular logic at the time, but I could see the same thing being at play here. As in, I don't have deletion proposals for you to think I should be able to request pages be deleted or some similarly dumb none sense. Otherwise, why not apply the same zero tolerance approach on yourself and the your friends that you have with me? My deletion proposals only make up a small portion of the ones currently in the queue. Why aren't off reverting those and chiding the people that did them to? The same question goes to Polarbearing and especially Nakaner. --Adamant1 (talk) 08:58, 16 February 2019 (UTC)
Folks, I would really appreciate it if you could refrain from name calling. Remember, while other participants in this debate may have a communication style that you don't like, they DO care deeply about OSM. So, please feel free to discuss the merits and failures of the different approaches to edits and grooming of Wiki pages, but don't attack people for having a different opinion or even for expressing that opinion in a way that you don't like. Thanks! --Lyx (talk) 10:16, 16 February 2019 (UTC)
- Where did anyone do any name calling? I used the word "buddies." That's all I can think of on my part. I'm not sure how that's name calling. -- Adamant1
- OK, fair enough. I'll try not to name drop. I hadn't really thought about it, but I guess it is better to talk about issues then people. Although if specific people are the ones with the issues and not people in general I don't want to make it seem otherwise. Although I can understand why it would be better not to single people out. As an unrelated side note, being from a relatively backwoods part of California I've really became aware of just how crudely people here talk through communicating with users on here from other countries. It always surprises me how a pretty average, normal word here might be offensive to someone from somewhere else. So it wouldn't surprise me if I had have called someone a name just out of ignorance or language differences. Instead of actually intent to. Awhile back I got in a good argument with someone from Europe because I said "alright boss" and they took it as offensive. We call people here boss all the time though. "shrug." —Preceding unsigned comment added by Adamant1 (talk • contribs) 16 February 2019
After a month of discussing in the forum, I would conclude that some people want to keep almost all proposals at any cost and there is no progress in this point. We could continue this on talk
openstreetmap.org to reach more people and possibly get a even broader discussion (we already had problems sticking to the topic), but I do not see the benefit of it. The arguments repeat, the people ask the same questions again, there are no actual negotiations but always the same views. On the other hand, bringing this up on talk could mean that other people could act as moderators of the discussion as well. I am not really decided what to do... --Tigerfell
(Let's talk) 15:06, 28 February 2019 (UTC)
- @Lyx The policy is now ready for voting. --Tigerfell
(Let's talk) 11:30, 13 April 2019 (UTC)
Edit deletion request
I know this is a weird request, but can you delete these useless edits that I created?:
1: 2: 3: 4:
Thanks :). — EzekielT (talk) 03:47, 6 February 2019 (UTC)
- I'm afraid I don't know how I would do that, except reverting all edits since (and they wouldn't be gone from the history anyway). --Lyx (talk) 08:09, 6 February 2019 (UTC)
- Nevermind, I’ve decided to keep them after reading this hilarious piece in the tagging list about me: it appears my edit war with myself has humoured Polarbear w quite a bit :D! — EzekielT (talk) 05:27, 10 February 2019 (UTC)
Deletion policy
Dear Lyx,:05, 16 April 2019 (UTC)
warning/block request
"Piss off. I didn't ask for your opinion and I don't give two craps about it. I'm not discussing crap with you" at is not acceptable. Can you warn/block that user as an admin? Mateusz Konieczny (talk) 07:21, 27 April 2019 (UTC)
- I obviously commented at but I think it deserves also admin intervention including block Mateusz Konieczny (talk) 07:23, 27 April 2019 (UTC)
Neuer Admin?
Hallo Lyx,
ich hatte mich am 4.09. auf Talk:Wiki selbst als neuen Wiki-Administrator vorgeschlagen. Ich habe dort auch meine Pläne als Administrator vorgestellt, insbesondere das regelmäßige Durchgehen der Löschanträge. Daraufhin erhielt ich fünf positive Rückmeldungen, u. a. von zwei aktiven Administratoren. Mit dem selben Mechanismus wurde Minh Nguyen im März zum Administrator ernannt. Nachdem keine weiteren Rückmeldungen mehr kamen, habe ich alle Bürokraten angepingt und gefragt, ob sie eine Entscheidung treffen könnten. Das ist aber bis heute nicht passiert. Spricht etwas dagegen, mich zu einem Administrator zu machen oder sind alle Bürokraten mit anderen Dingen beschäftigt? --Tigerfell
(Let's talk) 10:05, 20 September 2019 (UTC)
- Hallo Tigerfell, sorry für die späte Reaktion. Ich bin momentan tatsächlich anderweitig ziemlich eingespannt. Normalerweise würde ich Dich hier an Grant Slater (firefishy) verweisen, da er hier der "Haupt-Zuständige" ist; ich weiss aber nicht wie es bei ihm mit Zeit aussieht. Ich schaffe es hoffentlich morgen und Sonntag auf die SOTM; ich werde schauen ob welche von den anderen Wikiadmins da sind und das Thema ansprechen. Ich melde mich dann anschliessend wieder hier. --Lyx (talk) 19:30, 20 September 2019 (UTC)
Okay, hat sich etwas ergeben? --Tigerfell
(Let's talk) 06:21, 24 September 2019 (UTC)
- Leider nicht, firefishy war nicht auf der SOTM. Ich schreibe ihn jetzt an und werde nachher noch auf der Wiki-Talk Seite generell was dazu schreiben, was meiner persönlichen Meinung nach Anforderung an Wiki-Admins ist oder sein sollte. --Lyx (talk) 18:57, 24 September 2019 (UTC)
Ich wollte noch bestätigen, dass ich den Beitrag gelesen habe. Ich denke, dass ich mich aus Debatten heraushalten kann. Bei allen anderen Punkten fühle ich mich nicht explizit angesprochen. Die Beschreibung entspricht auch meiner Wahrnehmung von diesem Wiki, wie man auch auf Wiki:Administrators#Role of admins in the wiki nachlesen kann (die Seite darf natürlich gerne verändert werden, hatte versucht, die bisherige, ungeschriebene Handlungsweise zu verschriftlichen). --Tigerfell
(Let's talk) 18:28, 4 October 2019 (UTC)
Renovation of Main Page
The home page hasn’t had any edits in 5 years, and I could help. Can you give me administrator rights to renovate it? Thanks!
Dragomaniaca Ping me here 16:20, 5 October 2019 (UTC)
- For something as important as the main page (I suppose thats what you mean with "home page"?) it might be a good idea to create a new version in a sandbox that everyone can look at before editing it in place? RicoZ (talk) 19:16, 5 October 2019 (UTC)
- Leave it to me, RicoZ. Lyx, can I be an administrator? Please?
Dragomaniaca Ping me here 22:38, 5 October 2019 (UTC)
- Wenn ich mir Edits wie, oder anschaue, habe ich erhebliche Zweifel, ob der User die notwendige Voraussetzungen mitbringt, überhaupt irgendwelche Edits in diesem Wiki vorzunehmen, geschweige denn Admin. Bitte User zeitnah sperren, das OSM Wiki ist kein privater Sandkasten. Mmd (talk) 07:35, 6 October 2019 (UTC)
- Auch andere Benutzer haben schon damit begonnen, kritischen Änderungen an zentralen Templates zurückzurollen: Mmd (talk) 16:50, 6 October 2019 (UTC)
- Dragomaniaca, no, you can't be an administrator. For a significant change like renovating the main page you need to get community buy in, e.g. by building a demonstration version and discussing it with the community. And you need to be more careful and check your changes to see if they break something. I noticed the message box on Talk:Main Page was broken for some hours yesterday until you fixed it again. --Lyx (talk) 07:38, 7 October 2019 (UTC)
legal threats
Wikipedia has a policy of blocking users making legal threats (see ). Is there similar tradition on the OSM Wiki? I am asking as I noticed [7] Mateusz Konieczny (talk) 03:46, 1 December 2019 (UTC)
- There is no such tradition on the OSM Wiki, probably because this hasn't been a problem that we encountered so far. Unfortunately we also don't have a well-defined dispute resolution process. Admin can help to cool down edit wars by change protecting pages for a while and hope that people are able to find some kind of agreement, even it is to agree to disagree. This could mean e.g. to mention the fact that there is a disagreement and listing both points of view on a page, so readers can form their own opinion on the matter at hand. --Lyx (talk) 08:31, 3 December 2019 (UTC)
- If there isn't a policy about it I would still advocate for RTFM being blocked for his other actions. Especially his post calling us out for being the "wiki police" who think we "ate the wisdom from a spoon" whatever that means, but the legal threats should definitely qualify for a block in my opinion if nothing else does. --Adamant1 (talk) 04:27, 1 December 2019 (UTC) | https://wiki.openstreetmap.org/wiki/User_talk:Lyx | CC-MAIN-2020-10 | refinedweb | 12,006 | 69.72 |
Like many supercomputers in the world, Grendel, the world's 175 fastest computer, forces me to install everything from compiling source code and does not allow me to mess up the beautiful /usr/local directory. I can only play around in my home directory and cannot enjoy apt-get to deploy all Python modules I need.
So, i gotta install Python 2.6, and numpy, scipy, mlpy and pyml all from source code - the default version of Python on CentOS/RedHat Enterprise Linux 5.4 is 2.4. During this progress, I have figured out how Python and its modules are placed, or more precisely the directory structure. The feeling is like when I first figured out how things under /usr/local is for.
1. Python (at least for Python 2.4 and Python 2.6)
The source code package contains a configure script as the convention. When you run the configure script, you do things like this
./configure --prefix=/home/bao/Python-2.6And then your run
makeand
make install
After
make install, where is my Python 2.6? Denote the directory specified by
--prefixas
$PYTHON. The default value of
$PYTHONis
/usr/local/. After
make install, $PYTHON contains four subdirectories,
bin,
include,
liband
share, like the structure under
/usr/local/. Python 2.6 interpreter itself is under
$PYTHON/bin/, called
python2.6and/or
python.
include,
liband
sharesever the conventional purpose on UNIX systems, which are source files/heads, compiled shared/static libraries and documentations respectively.
libcould also include Python modules installed - I will detail this point in section 2.
You need to do is to add
$PYTHON/bininto
$PATHenvironmental variable in order to start
python2.6or
pythondirectly from your shell. I would delete the
$PYTHON/bin/pythonand enter
python2.6to make sure I am calling the Python 2.6 interpreter because some programs of mine run on Python 2.4. You can use the
whichcommand to determine which exactly the Python interpreter is used, like this:
$ which python /usr/bin/python $ which python2.6 ~/apps/Python-2.6/bin/python2.6
2. Locations of Python modules if installed to
$PYTHON
Most Python module source code packages contain a
setup.pyscripts by convention.You install (including compiling) it by executing
python2.6 python install --prefix=/home/bao/Python2.6/. Notice here I used
python2.6rather than default
python(which is Python 2.4 interpreter on my system).
If you do not specify in
--prefix, the
setup.pywill install everything into
/usr/local/by default.
So where is the module installed? Well, it goes to my
$PYTHONas specified by
--prefix. More precisely, it goes to the
$PYTHON/lib. Under
$PYTHON/libthere should be one or more directory(ies) like
pythonX.Y, depending on the Python version (X.Y) you use. On mine, it is
$PYTHON/lib/python2.6. Under the
pythonX.Ydirectory, there is a folder called
site-packages, where contains installed modules. On my system:
$ ls /home/bao/apps/Python-2.6/lib/python2.6/site-packages/ numpy numpy-1.3.0-py2.6.egg-info README
By default, your Python interpreter will look for modules under this
site-packagesdirectory.
3. What if I set directory other than
$PYTHONafter
--prefix?
The
setup.pywill create the same hierarchy structure
lib/pythonX.Y/site-packagesunder the directory you specified.
4. The
$PYTHONPATHenvironmental variable and sys.path (You need to read this if you did section 3).
Let's do a small experiment first. Start your Python interpreter, import sys module and run sys.path:
$ python2.6 Python 2.6 (r26:66714, May 24 2010, 10:45:11) [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path ['', '/home/bao/apps/Python-2.6', '/home/bao/apps/Python-2.6/lib/python26.zip', '/home/bao/apps/Python-2.6/lib/python2.6', '/home/bao/apps/Python-2.6/lib/python2.6/plat-linux2', '/home/bao/apps/Python-2.6/lib/python2.6/lib-tk', '/home/bao/apps/Python-2.6/lib/python2.6/lib-old', '/home/bao/apps/Python-2.6/lib/python2.6/lib-dynload', '/home/bao/apps/Python-2.6/lib/python2.6/site-packages']
The output of sys.path is a list of default paths where Python interpreter will search modules. For
import XYZ, it will search a folder called XYZ under all those directories.
If your modules are located under any of the directories, (e.g., the paths specified in
--prefixare the same when you install Python interpreter and modules) , you don't have to do anything. As you can see, default search path will make sure installed modules be found.
O/w, you need to specify the
$PYTHONPATHenvironmental variable on your UNIX system to tell Python interpreter to search XYZ under it. Suppose you install XYZ at
/MyMoD/XYZfolder. Then your
$PYTHONPATHshould contain the string
/MyMoD. Another case is when you Python module is just one Python file, like XYZ.py, located at
/MyMoD/XYZ.py, then your
$PYTHONPATHshould also contain the string
/MyMoD.
For more details about
$PYTHONPATH, please look into | http://forrestbao.blogspot.com/2010/05/python-and-modules-path-or-directory.html | CC-MAIN-2017-13 | refinedweb | 850 | 61.73 |
Example
with st.echo(): st.write('This code will be printed')
Display codeDisplay code
Sometimes you want your Streamlit app to contain both your usual
Streamlit graphic elements and the code that generated those elements.
That's where
st.echo() comes in.
Ok so let's say you have the following file, and you want to make its app a little bit more self-explanatory by making that middle section visible in the Streamlit app:
import streamlit as st def get_user_name(): return 'John' # ------------------------------------------------ # Want people to see this part of the code... def get_punctuation(): return '!!!' greeting = "Hi there, " user_name = get_user_name() punctuation = get_punctuation() st.write(greeting, user_name, punctuation) # ...up to here # ------------------------------------------------ foo = 'bar' st.write('Done!')
The file above creates a Streamlit app containing the words "Hi there,
John", and then "Done!".
Now let's use
st.echo() to make that middle section of the code visible
in the app:
import streamlit as st def get_user_name(): return 'John' with st.echo(): # Everything inside this block will be both printed to the screen # and executed. def get_punctuation(): return '!!!' greeting = "Hi there, " value = get_user_name() punctuation = get_punctuation() st.write(greeting, value, punctuation) # And now we're back to _not_ printing to the screen foo = 'bar' st.write('Done!')
It's that simple!
Note
You can have multiple
st.echo() blocks in the same file.
Use it as often as you wish! | https://docs.streamlit.io/library/api-reference/utilities/st.echo | CC-MAIN-2022-21 | refinedweb | 227 | 69.48 |
However, the good news is that I was able to load up the official 3.0 Python tutorial (work in progress) and try it out using Crunchy. I did find out one limitation of using Crunchy to do so. Crunchy encodes the Python output using utf-8 before forwarding to the browser. So, instead of having things like b'Andr\xc3\xa9' appearing on the screen, it would be converted to André. Thus, Crunchy is not a very good platform to teach about encoding/decoding of strings. For other aspects though, it is an ideal tool (if I may say so) for going through the Python tutorial: there is no need to switch back and forth between the browser and a separate Python environment to try things out. I still hope to have the time and energy to go through the entire 3.0 tutorial (something I have never done before, for 2.x) and see if I can find any bugs or come up with useful suggestions.
All I have left to do for the next release is to write up some documentation/tutorial on the new Turtle module and on launching Crunchy under Python3.0a1. With a bit of luck, this will all be finished before the end of the year.
In addition to the code reorganization mentioned above, I did fix a few bugs and made an improvement on Crunchy's Borg interpreters. For those that aren't familiar with it, Crunchy allows to embed a number of interpreters (html input box communicating with the Python backend) within a single page. These interpreters can either be isolated one from another (meaning that a variable defined in one interpreter is only known by that interpreter) or can share a common environment (aka Borg interpreters). Normally, in a single user mode, using a single open tab in Firefox, every time a new page is displayed, the Borg interpreters are effectively reset (the old ones are garbage collected and the new ones are created from an empty slate).
Previously, if one were to have multiple users (or multiple tabs open from the same user) on the same Crunchy server, all Borg interpreters ended up sharing the exact same state. This is not very convenient if two users are trying to use the same variable names! I had planned to address this "feature" at some point after the 1.0 release but was forced into it earlier due to the 3.0a1 work. The reason is the following.
To create "Borg interpreters", I was using the Borg idiom invented by Alex Martelli. It goes as follows:
class Borg(object):
'''Borg Idiom, from the Python Cookbook, 2nd Edition, p:273
Derive a class form this; all instances of that class will share the
same state, provided that they don't override __new__; otherwise,
remember to use Borg.__new__ within the overriden class.
'''
_shared_state = {}
def __new__(cls, *a, **k):
obj = object.__new__(cls, *a, **k)
obj.__dict__ = cls._shared_state
return obj
When using this idiom in a standard program under 3.0a1/2, a deprecation warning is raised about object.__new__() not taking any argument. When I was trying to make use of this idiom in Crunchy running under 3.0a1/2, the deprecation warning was actually replaced by an exception. Rather than trying to silence this exception, I decided to take a different approach and used instead the following:.
class BorgGroups(object):
'''Inspired by the Borg Idiom, from the Python Cookbook, 2nd Edition, p:273
to deal with multiple Borg groups (one per crunchy page)
while being compatible with Python 3.0a1/2.
Derived class must use a super() call to work with this properly.
'''
_shared_states = {}
def __init__(self, group="Borg"):
if group not in self._shared_states:
self._shared_states[group] = {}
self.__dict__ = self._shared_states[group]
# The following BorgConsole class is defined such that all instances
# of an interpreter on a same html page share the same environment.
class BorgConsole(BorgGroups, SingleConsole):
'''Every BorgConsole share a common state'''
def __init__(self, locals={}, filename="Crunchy console", group="Borg"):
super(BorgConsole, self).__init__(group=group)
SingleConsole.__init__(self, locals, filename=filename)
To be fair, I must admit that I did not come up with this solution totally on my own. A while ago, I asked for something like this on comp.lang.python. (Those interested in the details should search for "Borg rebellion".) I just derived the above solution from some suggestions made at that time.
Finally, in addition to all this, I found out a bug in code.py for Python 3.0a1/2. I tried to send an email to the python-3000 mailing list about it, but it was held up, waiting for a moderator approval for a few days. So, I canceled it and filed a bug report instead (which I should have done in the first place) on the bug tracker. I still haven't seen any follow up - perhaps due to the title I gave it. The bug is actually very easy to fix - three lines of code need to be replaced by a single one. The solution is related to my only other "official" contribution to Python to date. Hopefully, by this time next year, I'll have learned enough to contribute more to Python. | https://aroberge.blogspot.com/2007/ | CC-MAIN-2018-13 | refinedweb | 877 | 62.98 |
The C# Programming Language: Types
The types of the C# language are divided into two main categories: value types and reference types. Both value types and reference types may be generic types, which take one or more type parameters. Type parameters can designate both value types and reference types.
type: value-type reference-type type-parameter
A third category of types, pointers, is available only in unsafe code. This issue is discussed further in §18.2.
Value types differ from reference types in that variables of the value types directly contain their data, whereas variables of the reference types store references to their data, the latter being known as objects. With reference types, it is possible for two variables to reference the same object, and thus possible for operations on one variable to affect the object referenced by the other variable. With value types, the variables each have their own copy of the data, so it is not possible for operations on one to affect the other.
C#’s type system is unified such that a value of any type can be treated as an object. Every type in C# directly or indirectly derives from the object class type, and object is the ultimate base class of all types. Values of reference types are treated as objects simply by viewing the values as type object. Values of value types are treated as objects by performing boxing and unboxing operations (§4.3).
4.1 Value Types
A value type is either a struct type or an enumeration type. C# provides a set of predefined struct types called the simple types. The simple types are identified through reserved words.
value-type: struct-type enum-type struct-type: type-name simple-type nullable-type simple-type: numeric-type bool numeric-type: integral-type floating-point-type decimal integral-type: sbyte byte short ushort int uint long ulong char floating-point-type: float double nullable-type: non-nullable-value-type ? non-nullable-value-type: type enum-type: type-name
Unlike a variable of a reference type, a variable of a value type can contain the value null only if the value type is a nullable type. For every non-nullable value type, there is a corresponding nullable value type denoting the same set of values plus the value null.
Assignment to a variable of a value type creates a copy of the value being assigned. This differs from assignment to a variable of a reference type, which copies the reference but not the object identified by the reference.
4.1.1 The System.ValueType Type
All value types implicitly inherit from the class System.ValueType, which in turn inherits from class object. It is not possible for any type to derive from a value type, and value types are thus implicitly sealed (§10.1.1.2).
Note that System.ValueType is not itself a value-type. Rather, it is a class-type from which all value-types are automatically derived.
4.1.2 Default Constructors
All value types implicitly declare a public parameterless instance constructor called the default constructor. The default constructor returns a zero-initialized instance known as the default value for the value type:
- For all simple-types, the default value is the value produced by a bit pattern of all zeros:
- For sbyte, byte, short, ushort, int, uint, long, and ulong, the default value is 0.
- For char, the default value is '\x0000'.
- For float, the default value is 0.0f.
- For double, the default value is 0.0d.
- For decimal, the default value is 0.0m.
- For bool, the default value is false.
- For an enum-type E, the default value is 0, converted to the type E.
- For a struct-type, the default value is the value produced by setting all value type fields to their default values and all reference type fields to null.
- For a nullable-type, the default value is an instance for which the HasValue property is false and the Value property is undefined. The default value is also known as the null value of the nullable type.
Like any other instance constructor, the default constructor of a value type is invoked using the new operator. For efficiency reasons, this requirement is not intended to actually have the implementation generate a constructor call. In the example below, variables i and j are both initialized to zero.
class A { void F() { int i = 0; int j = new int(); } }
Because every value type implicitly has a public parameterless instance constructor, it is not possible for a struct type to contain an explicit declaration of a parameterless constructor. A struct type is, however, permitted to declare parameterized instance constructors (§11.3.8).
4.1.3 Struct Types
A struct type is a value type that can declare constants, fields, methods, properties, indexers, operators, instance constructors, static constructors, and nested types. The declaration of struct types is described in §11.1.
4.1.4 Simple Types
C# provides a set of predefined struct types called the simple types. The simple types are identified through reserved words, but these reserved words are simply aliases for predefined struct types in the System namespace, as described in the table below.
Because a simple type aliases a struct type, every simple type has members. For example, int has the members declared in System.Int32 and the members inherited from System.Object, and the following statements are permitted:
int i = int.MaxValue; // System.Int32.MaxValue constant string s = i.ToString(); // System.Int32.ToString() instance method string t = 123.ToString(); // System.Int32.ToString() instance method
The simple types differ from other struct types in that they permit certain additional operations:
- Most simple types permit values to be created by writing literals (§2.4.4). For example, 123 is a literal of type int and 'a' is a literal of type char. C# makes no provision for literals of struct types in general, and nondefault values of other struct types are ultimately always created through instance constructors of those struct types.
- When the operands of an expression are all simple type constants, it is possible for the compiler to evaluate the expression at compile time. Such an expression is known as a constant-expression (§7.19). Expressions involving operators defined by other struct types are not considered to be constant expressions.
- Through const declarations, it is possible to declare constants of the simple types (§10.4). It is not possible to have constants of other struct types, but a similar effect is provided by static readonly fields.
- Conversions involving simple types can participate in evaluation of conversion operators defined by other struct types, but a user-defined conversion operator can never participate in evaluation of another user-defined operator (§6.4.3).
4.1.5 Integral Types
C# supports nine integral types: sbyte, byte, short, ushort, int, uint, long, ulong, and char. The integral types have the following sizes and ranges of values:
- The sbyte type represents signed 8-bit integers with values between –128 and 127.
- The byte type represents unsigned 8-bit integers with values between 0 and 255.
- The short type represents signed 16-bit integers with values between –32768 and 32767.
- The ushort type represents unsigned 16-bit integers with values between 0 and 65535.
- The int type represents signed 32-bit integers with values between –2147483648 and 2147483647.
- The uint type represents unsigned 32-bit integers with values between 0 and 4294967295.
- The long type represents signed 64-bit integers with values between –9223372036854775808 and 9223372036854775807.
- The ulong type represents unsigned 64-bit integers with values between 0 and 18446744073709551615.
- The char type represents unsigned 16-bit integers with values between 0 and 65535. The set of possible values for the char type corresponds to the Unicode character set. Although char has the same representation as ushort, not all operations permitted on one type are permitted on the other.
The integral-type unary and binary operators always operate with signed 32-bit precision, unsigned 32-bit precision, signed 64-bit precision, or unsigned 64-bit precision:
- For the unary + and ~ operators, the operand is converted to type T, where T is the first of int, uint, long, and ulong that can fully represent all possible values of the operand. The operation is then performed using the precision of type T, and the type of the result is T.
- For the unary – operator, the operand is converted to type T, where T is the first of int and long that can fully represent all possible values of the operand. The operation is then performed using the precision of type T, and the type of the result is T. The unary – operator cannot be applied to operands of type ulong.
- For the binary +, –, *, /, %, &, ^, |, ==, !=, >, <, >=, and <= operators, the operands are converted to type T, where T is the first of int, uint, long, and ulong that can fully represent all possible values of both operands. The operation is then performed using the precision of type T, and the type of the result is T (or bool for the relational operators). It is not permitted for one operand to be of type long and the other to be of type ulong with the binary operators.
- For the binary << and >> operators, the left operand is converted to type T, where T is the first of int, uint, long, and ulong that can fully represent all possible values of the operand. The operation is then performed using the precision of type T, and the type of the result is T.
The char type is classified as an integral type, but it differs from the other integral types in two ways:
- There are no implicit conversions from other types to the char type. In particular, even though the sbyte, byte, and ushort types have ranges of values that are fully representable using the char type, implicit conversions from sbyte, byte, or ushort to char do not exist.
- Constants of the char type must be written as character-literals or as integer-literals in combination with a cast to type char. For example, (char)10 is the same as '\x000A'.
The checked and unchecked operators and statements are used to control overflow checking for integral-type arithmetic operations and conversions (§7.6.12). In a checked context, an overflow produces a compile-time error or causes a System.OverflowException to be thrown. In an unchecked context, overflows are ignored and any high-order bits that do not fit in the destination type are discarded.
4.1.6 Floating Point Types
C# supports two floating point types: float and double. The float and double types are represented using the 32-bit single-precision and 64-bit double-precision IEEE 754 formats, which provide the following sets of values:
- Positive zero and negative zero. In most situations, positive zero and negative zero behave identically as the simple value zero, but certain operations distinguish between the two (§7.8.2).
- Positive infinity and negative infinity. Infinities are produced by such operations as dividing a non-zero number by zero. For example, 1.0 / 0.0 yields positive infinity, and –1.0 / 0.0 yields negative infinity.
- The Not-a-Number value, often abbreviated NaN. NaNs are produced by invalid floating point operations, such as dividing zero by zero.
- The finite set of non-zero values of the form s × m × 2e, where s is 1 or –1, and m and e are determined by the particular floating point type: For float, 0 < m < 224 and –149 ≤ e ≤ 104; for double, 0 < m < 253 and –1075 ≤ e ≤ 970. Denormalized floating point numbers are considered valid non-zero values.
The float type can represent values ranging from approximately 1.5 × 10–45 to 3.4 × 1038 with a precision of 7 digits.
The double type can represent values ranging from approximately 5.0 × 10–324 to 1.7 × 10308 with a precision of 15 or 16 digits.
If one of the operands of a binary operator is of a floating point type, then the other operand must be of an integral type or a floating point type, and the operation is evaluated as follows:
- If one of the operands is of an integral type, then that operand is converted to the floating point type of the other operand.
- Then, if either of the operands is of type double, the other operand is converted to double, the operation is performed using at least double range and precision, and the type of the result is double (or bool for the relational operators).
- Otherwise, the operation is performed using at least float range and precision, and the type of the result is float (or bool for the relational operators).
The floating point operators, including the assignment operators, never produce exceptions. Instead, in exceptional situations, floating point operations produce zero, infinity, or NaN, as described below:
- If the result of a floating point operation is too small for the destination format, the result of the operation becomes positive zero or negative zero.
- If the result of a floating point operation is too large for the destination format, the result of the operation becomes positive infinity or negative infinity.
- If a floating point operation is invalid, the result of the operation becomes NaN.
- If one or both operands of a floating point operation is NaN, the result of the operation becomes NaN.
Floating point operations may be performed with higher precision than the result type of the operation. For example, some hardware architectures support an “extended” or “long double” floating point type with greater range and precision than the double type, and implicitly perform all floating point operations using this higher precision type. Only at excessive cost in performance can such hardware architectures be made to perform floating point operations with less precision. Rather than require an implementation to forfeit both performance and precision, C# allows a higher precision type to be used for all floating point operations. Other than delivering more precise results, this rarely has any measurable effects. However, in expressions of the form x * y / z, where the multiplication produces a result that is outside the double range, but the subsequent division brings the temporary result back into the double range, the fact that the expression is evaluated in a higher range format may cause a finite result to be produced instead of an infinity.
4.1.7 The decimal Type
The decimal type is a 128-bit data type suitable for financial and monetary calculations. The decimal type can represent values ranging from 1.0 × 10–28 to approximately 7.9 × 1028 with 28 or 29 significant digits.
The finite set of values of type decimal are of the form (–1)s × c × 10-e, where the sign s is 0 or 1, the coefficient c is given by 0 ≤ c < 296, and the scale e is such that 0 ≤ e ≤ 28.The decimal type does not support signed zeros, infinities, or NaNs. A decimal is represented as a 96-bit integer scaled by a power of 10. For decimals with an absolute value less than 1.0m, the value is exact to the 28th decimal place, but no further. For decimals with an absolute value greater than or equal to 1.0m, the value is exact to 28 or 29 digits. Unlike with the float and double data types, decimal fractional numbers such as 0.1 can be represented exactly in the decimal representation. In the float and double representations, such numbers are often infinite fractions, making those representations more prone to round-off errors.
If one of the operands of a binary operator is of type decimal, then the other operand must be of an integral type or of type decimal. If an integral type operand is present, it is converted to decimal before the operation is performed.
The result of an operation on values of type decimal is what would result from calculating an exact result (preserving scale, as defined for each operator) and then rounding to fit the representation. Results are rounded to the nearest representable value and, when a result is equally close to two representable values, to the value that has an even number in the least significant digit position (this is known as “banker’s rounding”). A zero result always has a sign of 0 and a scale of 0.
If a decimal arithmetic operation produces a value less than or equal to 5 × 10-29 in absolute value, the result of the operation becomes zero. If a decimal arithmetic operation produces a result that is too large for the decimal format, a System.OverflowException is thrown.
The decimal type has greater precision but smaller range than the floating point types. Thus conversions from the floating point types to decimal might produce overflow exceptions, and conversions from decimal to the floating point types might cause loss of precision. For these reasons, no implicit conversions exist between the floating point types and decimal, and without explicit casts, it is not possible to mix floating point and decimal operands in the same expression.
4.1.8 The bool Type
The bool type represents boolean logical quantities. The possible values of type bool are true and false.
No standard conversions exist between bool and other types. In particular, the bool type is distinct and separate from the integral types; a bool value cannot be used in place of an integral value, and vice versa.
In the C and C++ languages, a zero integral or floating point value, or a null pointer, can be converted to the boolean value false, and a non-zero integral or floating point value, or a non-null pointer, can be converted to the boolean value true. In C#, such conversions are accomplished by explicitly comparing an integral or floating point value to zero, or by explicitly comparing an object reference to null.
4.1.9 Enumeration Types
An enumeration type is a distinct type with named constants. Every enumeration type has an underlying type, which must be byte, sbyte, short, ushort, int, uint, long, or ulong. The set of values of the enumeration type is the same as the set of values of the underlying type. Values of the enumeration type are not restricted to the values of the named constants. Enumeration types are defined through enumeration declarations (§14.1).
4.1.10 Nullable Types
A nullable type can represent all values of its underlying type plus an additional null value. A nullable type is written T?, where T is the underlying type. This syntax is shorthand for System.Nullable<T>, and the two forms can be used interchangeably.
A non-nullable value type, conversely, is any value type other than System.Nullable<T> and its shorthand T? (for any T), plus any type parameter that is constrained to be a non-nullable value type (that is, any type parameter with a struct constraint). The System.Nullable<T> type specifies the value type constraint for T (§10.1.5), which means that the underlying type of a nullable type can be any non-nullable value type. The underlying type of a nullable type cannot be a nullable type or a reference type. For example, int?? and string? are invalid types.
An instance of a nullable type T? has two public read-only properties:
- A HasValue property of type bool
- A Value property of type T
An instance for which HasValue is true is said to be non-null. A non-null instance contains a known value and Value returns that value.
An instance for which HasValue is false is said to be null. A null instance has an undefined value. Attempting to read the Value of a null instance causes a System.InvalidOperationException to be thrown. The process of accessing the Value property of a nullable instance is referred to as unwrapping.
In addition to the default constructor, every nullable type T? has a public constructor that takes a single argument of type T. Given a value x of type T, a constructor invocation of the form
new T?(x)
creates a non-null instance of T? for which the Value property is x. The process of creating a non-null instance of a nullable type for a given value is referred to as wrapping.
Implicit conversions are available from the null literal to T? (§6.1.5) and from T to T? (§6.1.4). | http://www.informit.com/articles/article.aspx?p=1648574&seqNum=5 | CC-MAIN-2017-09 | refinedweb | 3,409 | 54.22 |
Getting started with inline SVG
This May, Viget worked with Dick's Sporting Goods to launch Women's Fitness, an interactive look at women’s fitness apparel and accessories. One of it's most interesting features is the grid of hexagonal product tiles shown in each scene. To draw the hexagons, I chose to use SVG polygon elements.
I've had experience using SVG files as image sources and in icon fonts, but this work was my first opportunity to really dig into it's most powerful use case, inline in HTML. Inline SVG simply refers to SVG markup that is included in the markup for a webpage.
<div><svg><!-- WHERE THE MAGIC HAPPENS. --></svg></div>
Based on this experience, here are a few simple things I learned about SVG.
1. Browser support is pretty good
2. SVG can be styled with CSS
Many SVG attributes, like fill and stroke, can be styled right in your CSS.
See the Pen eLbCy by Chris Manning (@cwmanning) on CodePen.
3. SVG doesn't support CSS z-index
Setting the z-index in CSS has asbolutely no effect on the stacking order of svg. The only thing that does is the position of the node in the document. In the example below, the orange circle comes after the blue circle in the document, so it is stacked on top.
See the Pen qdgtk by Chris Manning (@cwmanning) on CodePen.
4. SVG can be created and manipulated with JavaScript
Creation
Creating namespaced elements (or attributes, more on that later) requires a slightly different approach than HTML:
// HTML document.createElement('div'); // SVG document.createElementNS('', 'svg');
If you're having problems interacting with or updating elements, double check that you're using
createElementNS with the proper namespace. More on SVG namespaces.
With Backbone.js
In a Backbone application like Women's Fitness, to use
svg or another namespaced element as the view's
el, you can explictly override this line in
Backbone.View._ensureElement:
// var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
I made a Backbone View for SVG and copied the
_ensureElement function, replacing the line above with this:
// this.nameSpace = ''; this.tagName = 'svg'; var $el = $(window.document.createElementNS(_.result(this, 'nameSpace'), _.result(this, 'tagName'))).attr(attrs);
Setting Attributes
- Some SVG attributes are namespaced, like the href of an image or anchor:
xlink:href. To set or modify these, use setAttributeNS.
// typical node.setAttribute('width', '150'); // namespaced node.setAttributeNS('', 'xlink:href', '');
- Tip: attributes set with jQuery are always converted to lowercase! Watch out for issues like this gem:
// jQuery sets 'patternUnits' as 'patternunits' this.$el.attr('patternUnits', 'userSpaceOnUse'); // Works as expected this.el.setAttribute('patternUnits', 'userSpaceOnUse');
- Another tip: jQuery's
addClassdoesn't work on SVG elements. And element.classList isn't supported on SVG elements in Internet Explorer. But you can stil update the class with
$.attr('class', value)or
setAttribute('class', value).
5. SVG can be animated
CSS
As mentioned in #2, SVG elements can be styled with CSS. The following example uses CSS animations to transform rotatation and SVG attributes like stroke and fill. In my experience so far, browser support is not as consistent as SMIL or JavaScript.
Browser support: Chrome, Firefox, Safari. Internet Explorer does not support CSS transitions, transforms, and animations on SVG elements. In this particular example, the rotation is broken in Firefox because CSS transform-origin is not supported on SVG elements:.
See the Pen jtrLF by Chris Manning (@cwmanning) on CodePen.
SMIL
SVG allows animation with SMIL (Synchronized Multimedia Integration Language, pronounced "smile"), which supports the changing of attributes with SVG elements like animate, animateTransform, and animateMotion. See and for more. The following example is animated without any CSS or JavaScript.
Browser support: Chrome, Firefox, Safari. Internet Explorer does not support SMIL animation of SVG elements.
See the Pen jtrLF by Chris Manning (@cwmanning) on CodePen.
JavaScript
Direct manipulation of SVG element attributes allows for the most control over animations. It's also the only method of the three that supports animation in Internet Explorer. If you are doing a lot of work, there are many libraries to speed up development time like svg.js (used in this example), Snap.svg, and d3.
See the Pen jtrLF by Chris Manning (@cwmanning) on CodePen.
TL;DR
SVG isn't limited to whatever Illustrator outputs. Using SVG in HTML is well-supported and offers many different options to style and animate content. If you're interested in learning more, check out the resources below.
Additional Resources
- Using SVG by Chris Coyier
- An SVG Primer for Today's Browsers (in-depth primer, lots of code examples and visual aids) | https://www.viget.com/articles/getting-started-with-inline-svg/ | CC-MAIN-2021-43 | refinedweb | 772 | 58.58 |
I have a string,
"004-034556", that I want to split into two strings:
string1=004 string2=034556
That means the first string will contain the characters before
'-', and the second string will contain the characters after
'-'. I also want to check if the string has
'-' in it. If not, I will throw an exception. How can I do this? -"); }
Note,
An alternative to processing the string directly would be to use a regular expression with capturing groups. This has the advantage that it makes it straightforward to imply more sophisticated constraints on the input. For example, the following splits the string into two parts, and ensures that both consist only of digits:
import java.util.regex.Pattern; import java.util.regex.Matcher; class SplitExample { private static Pattern twopart = Pattern.compile("(\d+)-(\d+)"); public static void checkString(String s) { Matcher m = twopart.matcher(s); if (m.matches()) { System.out.println(s + " matches; first part is " + m.group(1) + ", second part is " + m.group(2) + "."); } else { System.out.println(s + " does not match."); } } public static void main(String[] args) { checkString("123-4567"); checkString("foo-bar"); checkString("123-"); checkString("-4567"); checkString("123-4567-890"); } }
As the pattern is fixed in this instance, it can be compiled in advance and stored as a static member (initialised at class load time in the example). The regular expression is:
(\d+)-(\d+)
The parentheses denote the capturing groups; the string that matched that part of the regexp can be accessed by the Match.group() method, as shown. The \d matches and single decimal digit, and the + means “match one or more of the previous expression). The – has no special meaning, so just matches that character in the input. Note that you need to double-escape the backslashes when writing this as a Java string. Some other examples:
([A-Z]+)-([A-Z]+) // Each part consists of only capital letters ([^-]+)-([^-]+) // Each part consists of characters other than - ([A-Z]{2})-(\d+) // The first part is exactly two capital letters, // the second consists of digits
String[] result = yourString.split("-"); if (result.length != 2) throw new IllegalArgumentException("String not in correct format");
This will split your string into 2 parts. The first element in the array will be the part containing the stuff before the
-, and the 2nd element in the array will contain the part of your string after the
-.
If the array length is not 2, then the string was not in the format:
string-string.
split() method in the
String class.-
// This leaves the regexes issue out of question // But we must remember that each character in the Delimiter String is treated // like a single delimiter public static String[] SplitUsingTokenizer(String subject, String delimiters) { StringTokenizer strTkn = new StringTokenizer(subject, delimiters); ArrayList<String> arrLis = new ArrayList<String>(subject.length()); while(strTkn.hasMoreTokens()) arrLis.add(strTkn.nextToken()); return arrLis.toArray(new String[0]); }
String[] out = string.split("-");
should do thing you want. String class has many method to operate with string.
The requirements left room for interpretation. I recommend writing a method,
public final static String[] mySplit(final String s)
which encapsulate this function. Of course you can use String.split(..) as mentioned in the other answers for the implementation.
You should write some unit-tests for input strings and the desired results and behaviour.
Good test candidates should include:
- "0022-3333" - "-" - "5555-" - "-333" - "3344-" - "--" - "" - "553535" - "333-333-33" - "222--222" - "222--" - "--4555"
With defining the according test results, you can specify the behaviour.
For example, if
"-333" should return in
[,333] or if it is an error.
Can
"333-333-33" be separated in
[333,333-33] or [333-333,33] or is it an error? And so on.
You can try like this also
String concatenated_String="hi^Hello"; String split_string_array[]=concatenated_String.split("\^");
Assuming, that
- you don’t really need regular expressions for your split
- you happen to already use apache commons lang in your app
The easiest way is to use StringUtils#split(java.lang.String, char). That’s more convenient than the one provided by Java out of the box if you don’t need regular expressions. Like its manual says, it works like this:
A null input String returns null. StringUtils.split(null, *) = null StringUtils.split("", *) = [] StringUtils.split("a.b.c", '.') = ["a", "b", "c"] StringUtils.split("a..b.c", '.') = ["a", "b", "c"] StringUtils.split("a:b:c", '.') = ["a:b:c"] StringUtils.split("a b c", ' ') = ["a", "b", "c"]
I would recommend using commong-lang, since usually it contains a lot of stuff that’s usable. However, if you don’t need it for anything else than doing a split, then implementing yourself or escaping the regex is a better option.
Use org.apache.commons.lang.StringUtils’ split method which can split strings based on the character or string you want to split.
Method signature:
public static String[] split(String str, char separatorChar);
In your case, you want to split a string when there is a “-“.
You can simply do as follows:
String str = "004-034556"; String split[] = StringUtils.split(str,"-");
Output:
004 034556
Assume that if
- does not exists in your string, it returns the given string, and you will not get any exception.
With Java 8:
List<String> stringList = Pattern.compile("-") .splitAsStream("004-034556") .collect(Collectors.toList()); stringList.forEach(s -> System.out.println(s));
For simple use cases
String.split() should do the job. If you use guava, there is also a Splitter class which allows chaining of different string operations and supports CharMatcher:
Splitter.on('-') .trimResults() .omitEmptyStrings() .split(string);
String Split with multiple characters using Regex
public class StringSplitTest { public static void main(String args[]) { String s = " ;String; String; String; String, String; String;;String;String; String; String; ;String;String;String;String"; //String[] strs = s.split("[,\s\;]"); String[] strs = s.split("[,\;]"); System.out.println("Substrings length:"+strs.length); for (int i=0; i < strs.length; i++) { System.out.println("Str["+i+"]:"+strs[i]); } } }
Output:
Substrings length:17 Str[0]: Str[1]:String Str[2]: String Str[3]: String Str[4]: String Str[5]: String Str[6]: String Str[7]: Str[8]:String Str[9]:String Str[10]: String Str[11]: String Str[12]: Str[13]:String Str[14]:String Str[15]:String Str[16]:String
But do not expect the same output across all JDK versions. I have seen one bug which exists in some JDK versions where the first null string has been ignored. This bug is not present in the latest JDK version, but it exists in some versions between JDK 1.7 late versions and 1.8 early versions.
public class SplitTest { public static String[] split(String text, String delimiter) { java.util.List<String> parts = new java.util.ArrayList<String>(); text += delimiter; for (int i = text.indexOf(delimiter), j=0; i != -1;) { String temp = text.substring(j,i); if(temp.trim().length() != 0) { parts.add(temp); } j = i + delimiter.length(); i = text.indexOf(delimiter,j); } return parts.toArray(new String[0]); } public static void main(String[] args) { String str = "004-034556"; String delimiter = "-"; String result[] = split(str, delimiter); for(String s:result) System.out.println(s); } }
You can split a string by a line break by using the following statement:
String textStr[] = yourString.split("\r?\n");
You can split a string by a hyphen/character by using the following statement:
String textStr[] = yourString.split("-");
import java.io.*; public class BreakString { public static void main(String args[]) { String string = "004-034556-1234-2341"; String[] parts = string.split("-"); for(int i=0;i<parts.length;i++) { System.out.println(parts[i]); } } }
The fastest way, which also consumes the least resource could be:
String s = "abc-def"; int p = s.indexOf('-'); if (p >= 0) { String left = s.substring(0, p); String right = s.substring(p + 1); } else { // s does not contain '-' }
One way to do this is to run through the String in a for-each loop and use the required split character.
public class StringSplitTest { public static void main(String[] arg){ String str = "004-034556"; String split[] = str.split("-"); System.out.println("The split parts of the String are"); for(String s:split) System.out.println(s); } }
Output:
The split parts of the String are: 004 034556
Please don’t use StringTokenizer class as it is a legacy class that is retained for compatibility reasons, and its use is discouraged in new code. And we can make use of the split method as suggested by others as well.
String[] sampleTokens = "004-034556".split("-"); System.out.println(Arrays.toString(sampleTokens));
And as expected it will print:
[004, 034556]
In this answer I also want to point out one change that has taken place for
split method in Java 8. The String#split() method makes use of
Pattern.split, and now it will remove empty strings at the start of the result array. Notice this change in documentation for Java 8:
When there is a positive-width match at the beginning of the input
sequence then an empty leading substring is included at the beginning
of the resulting array. A zero-width match at the beginning however
never produces such empty leading substring.
It means for the following example:
String[] sampleTokensAgain = "004".split(""); System.out.println(Arrays.toString(sampleTokensAgain));
we will get three strings:
[0, 0, 4] and not four as was the case in Java 7 and before. Also check this similar question.
You can use the Split().
import java.io.*; public class Splitting { public static void main(String args[]) { String Str = new String("004-034556"); String[] SplittoArray = Str.split("-"); String string1= SplittoArray[0]; String string2= SplittoArray[1]; } }
Else,
You can use StringTokenizer.
import java.util.*; public class Splitting { public static void main(String[] args) { StringTokenizer Str = new StringTokenizer("004-034556"); String string1= Str.nextToken("-"); String string2= Str.nextToken("-"); } }
Hope It Helps.. 🙂
Here are two ways two achieve it
WAY 1:
As you have to split two numbers by a special character you can use regex
import java.util.regex.Matcher; import java.util.regex.Pattern; public class TrialClass { public static void main(String[] args) { Pattern p=Pattern.compile("[0-9]+"); Matcher m=p.matcher("004-034556"); while(m.find()) { System.out.println(m.group()); } } }
WAY 2:Using string split method
public class TrialClass { public static void main(String[] args) { String temp="004-034556"; String [] arrString=temp.split("-"); for(String splitString:arrString) { System.out.println(splitString); } } }
You can use simply StringTokenizer to split string in two or more parts whether their is any type of delimiters:
StringTokenizer st=new StringTokenizer("004-034556","-"); while(st.hasMoreTokens()) { System.out.println(st.nextToken()); }
split() method in the
String class on javadoc.
String data = "004-034556-1212-232-232"; int cnt = 1; for (String item : data.split("-")) { System.out.println("string "+cnt+" = "+item); cnt++; }
Here many examples for split string but I little code optimized.
String str="004-034556" String[] sTemp=str.split("-");// '-' is a delimiter string1=004 // sTemp[0]; string2=034556//sTemp[1];
String s="004-034556"; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='-') { System.out.println(s.substring(0,i)); System.out.println(s.substring(i+1)); } }
As mentioned by everyone, split() is the best option which may be used in your case. An alternative method can be using substring().
To split a string, use
String.split(regex):
String phone = "004-034556"; String[] output = phone.split("-"); System.out.println(output[0]); System.out.println(output[1]);
output:
004
034556
From the documentation:.
So basically what you can do is something like this:
String s = "123-456-789-123"; // the String to be split String[] array = s.split("-"); // split according to the hyphen and put them in an array for(String subString : array){ // cycle through the array System.out.println(subString); }
Output:
123 456 789 123
String string = "004^034556-34"; String[] parts = string.split(Pattern.quote("^"));
If you have special character then you can use Patter.quote. If you are simple have dash (-) then you shorten the code
String string = "004-34"; String[] parts = string.split("-");
If you try to add other special character in place of dash (^) then the error will generate ArrayIndexOutOfBoundsException. For that you have to use Pattern.quote
Sometimes if you want to split
string containing + then it won’t split; instead you will get a
runtime error. In that case, first
replace + to _ and then split:
this.text=text.replace("/", "_"); String temp[]=text.split("_"); | https://exceptionshub.com/how-to-split-a-string-in-java.html | CC-MAIN-2022-05 | refinedweb | 2,051 | 67.04 |
Overview
Atlassian Sourcetree is a free Git and Mercurial client for Windows.
Atlassian Sourcetree is a free Git and Mercurial client for Mac.
configparser
The ancient ConfigParser module available in the standard library 2.x has seen a major update in Python 3.2. This is a backport of those changes so that they can be used directly in Python 2.6 - 3.5.
To use the configparser backport instead of the built-in version on both Python 2 and Python 3, simply import it explicitly as a backport:
from backports import configparser
If you'd like to use the backport on Python 2 and the built-in version on Python 3, use that invocation instead:
import configparser
For detailed documentation consult the vanilla version at.
Why you'll love configparser
Whereas almost completely compatible with its older brother, configparser):
- the classic %(string-like)s syntax (called BasicInterpolation)
- a new ${buildout:like} syntax (called ExtendedInterpolation)
A few words about Unicode
configparser.
Versioning
This backport is intended to keep 100% compatibility with the vanilla release in Python 3.2+. To help maintaining a version you want and expect, a versioning scheme is used where:
- the first two numbers indicate the version of Python 3 from which the backport is done
- a backport release number is provided as the final number (zero-indexed)
For example, 3.5.2 is the third backport release of the configparser.
3.3.0r2
3.3.0r1
- compatible with 3.3.0 + fixes for #15803 and #16820
- fixes BitBucket issue #4: read() properly treats a bytestring argument as a filename
- ordereddict dependency required only for Python 2.6
- unittest2 explicit dependency dropped. If you want to test the release, add unittest2 on your own.
3.2.0r3
- proper Python 2.6 support
- explicitly stated the dependency on ordereddict
- numbered all formatting braces in strings
- explicitly says that Python 2.5 support won't happen (too much work necessary without abstract base classes, string formatters, the io library, etc.)
- some healthy advertising in the README
3.2.0r2
- a backport-specific change: for convenience and basic compatibility with the old ConfigParser, bytestrings are now accepted as section names, options and values. Those strings are still converted to Unicode for internal storage so in any case when such conversion is not possible (using the 'ascii' codec), UnicodeDecodeError is raised.
Conversion Process
This section is technical and should bother you only if you are wondering how this backport is produced. If the implementation details of this backport are not important for you, feel free to ignore the following content.
configparser is converted using python-future and free time. Because a fully automatic conversion was not doable, I took the following branching approach:
- the 3.x branch holds unchanged files synchronized from the upstream CPython repository. The synchronization is currently done by manually copying the required files and stating from which CPython changeset they come from.
- the. | https://bitbucket.org/ambv/configparser | CC-MAIN-2019-13 | refinedweb | 486 | 53.71 |
On Tuesday 05 February 2008 11:51:58 pm Kelly Miller wrote: > Ignacio Vazquez-Abrams wrote: > > > > So, something like this? Something like that, but I'd suggest a few enhancements. > %if 0%{?fedora} <= 8 > BuildRequires: kdelibs-devel >= 3.0.0, kdebase-devel >= 3.0.0 > Requires: kdebase All supported distros have kdefoo-devel > 3, no need to have that BR versioned. The only versioning I'd consider adding is kdefoo-devel < 4, to make sure someone doesn't try building against kde4 bits (like on a part f8, part rawhide system or some such thing). > %else > BuildRequires: kdelibs3-devel >= 3.0.0, kdebase3-devel >= 3.0.0 > Requires: kdebase3 > %endif Again, no need to have the BR versioned. kdefoo3-devel is definitely going to be 3.something. -- Jarod Wilson jwilson redhat com | https://listman.redhat.com/archives/fedora-devel-list/2008-February/msg00290.html | CC-MAIN-2021-39 | refinedweb | 132 | 61.43 |
Red Hat Bugzilla – Bug 51312
getpwuid() fails for uid=0 and uid=500
Last modified: 2007-04-18 12:35:39 EDT
From Bugzilla Helper:
User-Agent: Mozilla/4.76 [en] (X11; U; Linux 2.4.2-2 i686)
Description of problem:
How reproducible:
Always
Steps to Reproduce:
See attachment
Actual Results: See attachment
Expected Results: Should have received primed passwd structure
Additional info:
Created attachment 26993 [details]
debug material for bug 51312
Works just fine for me.
What's your content of nsswitch.conf, why you decided to print the
backtrace from _dl_debug_state, does it return NULL or what?
Execution of the pgm stops at the point of failure.
Here's the contents of
It's looking more like a bug in the KDevelop debugger. My function A calls a function B which in turn calls getpwuid(). If I set breakpoints on either sided
of the call to function B and do a "run to cursor" then I don't appear to have any problems. But if I step into function B and attempt to step over the call to
getpwuid() or if I step over the call to function B, then the problem occurs.
I appear to have a similar problem with the gethostbyname() api. Any chance I have some kind of corruption or authority problem that would be causing
these calls to fail while debugging?
We (Red Hat) should really try to this this before next release.
Please attach the code that fails.
Here's a small program that causes the problem when stepping over getpwuid() statement using kdevelop's debugger.
#include <pwd.h>
int main(int argc, char *argv[])
{
uid_t nUserID = getuid();
struct passwd *pPasswd = NULL;
pPasswd = (struct passwd *)getpwuid(nUserID);
return EXIT_SUCCESS;
}
I just tried it with kdbg here; I broke at main and stepped over all function
calls. It worked fine. | https://bugzilla.redhat.com/show_bug.cgi?id=51312 | CC-MAIN-2016-50 | refinedweb | 307 | 62.88 |
Summary: The key goal of
__str__ and
__repr__ is to return a string representation of a Python object. The way they represent the string object differentiates them.
str()&
__str()__return a printable/readable string representation of an object which is focused on the end-user.
repr()&
__repr()__return a string representation of an object that is a valid Python object, something you can pass to
eval()or type into the Python shell without getting an error. Its major goal is to be unambiguous.
Problem Statement: What is the difference between
__str__ and
__repr__ in Python?
Firstly, let us discuss why this is one of the most commonly asked questions on the Internet. Let us have a look at an example to understand the reason behind the confusion.
Example 1:
name = 'FINXTER' print(str(name)) print(repr(name))
Output:
FINXTER 'FINXTER'
Now you see, why this is so confusing! ? Both of them seem to print the string
FINXTER. Thus, both of them are built-in functions, and both return a string representation of an object; The only visible difference in this case is –
str() prints the string without the quotes (
FINXTER), while
repr() prints its with the quotes (
'FINXTER').
➤ Note: In case you are wondering why are we using
repr() and
str() instead of
__repr__ and
__str__ then please have a look at the note given below:
But now let us have a look at a different example;
Example 2:
from datetime import datetime d = datetime.now() print(str(d)) print(repr(d))
Output:
2020-11-04 16:38:20.048483 datetime.datetime(2020, 11, 4, 16, 38, 20, 48483)
In the second example we can clearly visualize the difference between
repr() and
str().
Let’s have a quick look at what the official documentation says about
object.__repr__(self) and
object.__str__(self):
object.__repr__(self): Called by the
repr()built-in function to compute the “official” string representation of an object.
object.__str__(self): Called by the
str()built-in function and by the print statement to compute the “informal” string representation of an object.
In other words, we can say that:
❖ The goal of __repr__ is to be unambiguous
The
__repr__() function returns the object representation of any valid python expression such as tuple, dictionary, string, etc. This means, whenever the
repr() function is invoked on the object, it will return the object itself and hence can be evaluated with the
eval() function to recreate the object itself because of its unambiguous nature. Thus,
repr(25)!=repr("25").
Let us have a look at a quick example where we can use
repr() on an expression and evaluate it with the help of
eval() function.
Note: You cannot use the
eval() function on
str() which is clearly depicted in the example below.
Example:
text1 = 'a string' text2 = eval(repr(text1)) if text1 == text2: print("eval() Works!") text3 = eval(str(text1)) if text1 == text3: print("eval() Works!")
Output:
eval() Works! Traceback (most recent call last): File "main.py", line 5, in <module> text3 = eval(str(text1)) File "<string>", line 1 a string ^ SyntaxError: unexpected EOF while parsing
❖ The goal of __str__ is to be readable
The goal of
__str__ is not to unambiguous, rather its purpose is to provide a representation that a user that is more readable to the user. Thus,
str(25)==str("25") .
Let us have a look at a very simple example which demonstrates the unambiguous nature of
repr() and the readability aspect of
str().
if str(25)==str("25"): print("Goal of __str__ : Readability") if repr(25)!=repr("25"): print("Goal of __repr__ : Unamgiuity")
Output:
Goal of __str__ : Readability Goal of __repr__ : Unamgiuity
✨ Simply put,
__repr__ is for developers while
__str__ is for customers!
Points to Remember
❖ For Containers, __str__ Uses The Contained Objects’ __repr__
To simplify things let us take the help of an example:
rank = {'Rick': 1} language = ['Python', 'Java'] error = (404, 'status_code') for item in (rank, language, error): print(f"{str(type(item)):}") print(f"repr() representation: {repr(item):}") print(f"str() representation: {str(item)}") print("\n")
Output:
<class 'dict'> repr() representation: {'Rick': 1} str() representation: {'Rick': 1} <class 'list'> repr() representation: ['Python', 'Java'] str() representation: ['Python', 'Java'] <class 'tuple'> repr() representation: (404, 'status_code') str() representation: (404, 'status_code')
In the above example, it is clear that even when we use the
str() on a container object, the str() function invokes their
__repr()__ method; hence we get the object itself as the output and there is no difference between
str() and
repr() when used with objects. This justifies that for containers
__str__ uses contained objects’
__repr__.
❖ The default implementation of __str__ and
__repr__ is useless
The default implementation of
__str__ and
__repr__ is useless and unless you ensure to specifically define and use them, most classes don’t have helpful results for either. Let’s make things clear with the help of another example:
class Finxter(object): pass print(str(Finxter())) print(repr(Finxter()))
Output:
<__main__.Finxter object at 0x7f85641d15e0> <__main__.Finxter object at 0x7f85641d15e0>
As seen above there is no difference between either method and no information beyond the classes
id.
Note: An object will behave as though
__str__=__repr__ if
__repr__ is defined, and
__str__ is not.
Now let us try and override the
__str__ and
__repr__ methods to visualize their behaviour on Coustom Objects. Please follow the example given below.
Example:
class Finxter(object): def __str__(object): return str("Freelancing") def __repr__(object): return repr("Freelancing") print(str(Finxter())) print(repr(Finxter())) print(eval(repr(Finxter())))
Output:
Freelancing 'Freelancing' Freelancing
From the above example, it is clear that
__repr__() cab be easily overridden so that
repr() works differently.
Note: If you override
, that will also be used for
__repr__
__str__
, but vice versa is not possible. Let us have a look at that in the example given below., but vice versa is not possible. Let us have a look at that in the example given below.
Example A: Overriding
__repr__ also overrides
__str__
class Finxter(object): def __repr__(object): return repr("Freelancing") print(str(Finxter())) print(repr(Finxter()))
Output:
'Freelancing' 'Freelancing'
Example B: Overriding
__str__ doesn’t affect
__repr__
class Finxter(object): def __str__(object): return str("Freelancing") print(str(Finxter())) print(repr(Finxter()))
Output:
Freelancing <__main__.Finxter object at 0x7f3b284ef5e0>
Conclusion
Let us summarize the key difference beween
__repr__ and
__str__! | https://blog.finxter.com/python-__str__-vs-__repr__/ | CC-MAIN-2022-21 | refinedweb | 1,053 | 50.67 |
What is the most ridiculous pessimization you've seen?
We all know that premature optimization is the root of all evil because it leads to unreadable/unmaintainable code. Even worse is pessimization, when someone implements an "optimization" because they think it will be faster, but it ends up being slower, as well as being buggy, unmaintainable, etc. What is the most ridiculous example of this that you've seen?
Answers
On an old project we inherited some (otherwise excellent) embedded systems programmers who had massive Z-8000 experience.
Our new environment was 32-bit Sparc Solaris.
One of the guys went and changed all ints to shorts to speed up our code, since grabbing 16 bits from RAM was quicker than grabbing 32 bits.
I had to write a demo program to show that grabbing 32-bit values on a 32-bit system was faster than grabbing 16-bit values, and explain that to grab a 16-bit value the CPU had to make a 32-bit wide memory access and then mask out or shift the bits not needed for the 16-bit value.
I think the phrase "premature optimization is the root of all evil" is way, way over used. For many projects, it has become an excuse not to take performance into account until late in a project.
This phrase is often a crutch for people to avoid work. I see this phrase used when people should really say "Gee, we really didn't think of that up front and don't have time to deal with it now".
I've seen many more "ridiculous" examples of dumb performance problems than examples of problems introduced due to "pessimization"
- Reading the same registry key thousands (or 10's of thousands) of times during program launch.
- Wasting mega bytes of memory by keeping full paths to files needlessly
- Not organizing data structures so they take up way more memory than they need
- Sizing all strings that store file names or paths to MAX_PATH
- Gratuitous polling for thing that have events, callbacks or other notification mechanisms
What I think is a better statement is this: "optimization without measuring and understanding isn't optimization at all - its just random change".
Good Performance work is time consuming - often more so that the development of the feature or component itself.
Databases are pessimization playland.
Favorites include:
- Split a table into multiples (by date range, alphabetic range, etc.) because it's "too big".
- Create an archive table for retired records, but continue to UNION it with the production table.
- Duplicate entire databases by (division/customer/product/etc.)
- Resist adding columns to an index because it makes it too big.
- Create lots of summary tables because recalculating from raw data is too slow.
- Create columns with subfields to save space.
- Denormalize into fields-as-an-array.
That's off the top of my head.
I think there is no absolute rule: some things are best optimized upfront, and some are not.
For example, I worked in a company where we received data packets from satellites. Each packet cost a lot of money, so all the data was highly optimized (ie. packed). For example, latitude/longitude was not sent as absolute values (floats), but as offsets relative to the "north-west" corner of a "current" zone. We had to unpack all the data before it could be used. But I think this is not pessimization, it is intelligent optimization to reduce communication costs.
On the other hand, our software architects decided that the unpacked data should be formatted into a very readable XML document, and stored in our database as such (as opposed to having each field stored in a corresponding column). Their idea was that "XML is the future", "disk space is cheap", and "processor is cheap", so there was no need to optimize anything. The result was that our 16-bytes packets were turned into 2kB documents stored in one column, and for even simple queries we had to load megabytes of XML documents in memory! We received over 50 packets per second, so you can imagine how horrible the performance became (BTW, the company went bankrupt).
So again, there is no absolute rule. Yes, sometimes optimization too early is a mistake. But sometimes the "cpu/disk space/memory is cheap" motto is the real root of all evil.
Oh good Lord, I think I have seen them all. More often than not it is an effort to fix performance problems by someone that is too darn lazy to troubleshoot their way down to the CAUSE of those performance problems or even researching whether there actually IS a performance problem. In many of these cases I wonder if it isn't just a case of that person wanting to try a particular technology and desperately looking for a nail that fits their shiny new hammer.
Here's a recent example:
Data architect comes to me with an elaborate proposal to vertically partition a key table in a fairly large and complex application. He wants to know what type of development effort would be necessary to adjust for the change. The conversation went like this:
Me: Why are you considering this? What is the problem you are trying to solve?
Him: Table X is too wide, we are partitioning it for performance reasons.
Me: What makes you think it is too wide?
Him: The consultant said that is way too many columns to have in one table.
Me: And this is affecting performance?
Him: Yes, users have reported intermittent slowdowns in the XYZ module of the application.
Me: How do you know the width of the table is the source of the problem?
Him: That is the key table used by the XYZ module, and it is like 200 columns. It must be the problem.
Me (Explaining): But module XYZ in particular uses most of the columns in that table, and the columns it uses are unpredictable because the user configures the app to show the data they want to display from that table. It is likely that 95% of the time we'd wind up joining all the tables back together anyway which would hurt performance.
Him: The consultant said it is too wide and we need to change it.
Me: Who is this consultant? I didn't know we hired a consultant, nor did they talk to the development team at all.
Him: Well, we haven't hired them yet. This is part of a proposal they offered, but they insisted we needed to re-architect this database.
Me: Uh huh. So the consultant who sells database re-design services thinks we need a database re-design....
The conversation went on and on like this. Afterward, I took another look at the table in question and determined that it probably could be narrowed with some simple normalization with no need for exotic partitioning strategies. This, of course turned out to be a moot point once I investigated the performance problems (previously unreported) and tracked them down to two factors:
- Missing indexes on a few key columns.
- A few rogue data analysts who were periodically locking key tables (including the "too-wide" one) by querying the production database directly with MSAccess.
Of course the architect is still pushing for a vertical partitioning of the table hanging on to the "too wide" meta-problem. He even bolstered his case by getting a proposal from another database consultant who was able to determine we needed major design changes to the database without looking at the app or running any performance analysis.
I have seen people using alphadrive-7 to totally incubate CHX-LT. This is an uncommon practice. The more common practice is to initialize the ZT transformer so that bufferication is reduced (due to greater net overload resistance) and create java style bytegraphications.
Totally pessimistic!
Nothing Earth-shattering, I admit, but I've caught people using StringBuffer to concatenate Strings outside of a loop in Java. It was something simple like turning
String msg = "Count = " + count + " of " + total + ".";
into
StringBuffer sb = new StringBuffer("Count = "); sb.append(count); sb.append(" of "); sb.append(total); sb.append("."); String msg = sb.toString();
It used to be quite common practice to use the technique in a loop, because it was measurably faster. The thing is, StringBuffer is synchronized, so there's actually extra overhead if you're only concatenating a few Strings. (Not to mention that the difference is absolutely trivial on this scale.) Two other points about this practice:
- StringBuilder is unsynchronized, so should be preferred over StringBuffer in cases where your code can't be called from multiple threads.
- Modern Java compilers will turn readable String concatenation into optimized bytecode for you when it's appropriate anyway.
I once saw a MSSQL database that used a 'Root' table. The Root table had four columns: GUID (uniqueidentifier), ID (int), LastModDate (datetime), and CreateDate (datetime). All tables in the database were Foreign Key'd to the Root table. Whenever a new row was created in any table in the db, you had to use a couple of stored procedures to insert an entry in the Root table before you could get to the actual table you cared about (rather than the database doing the job for you with a few triggers simple triggers).
This created a mess of useless overheard and headaches, required anything written on top of it to use sprocs (and eliminating my hopes of introducing LINQ to the company. It was possible but just not worth the headache), and to top it off didn't even accomplish what it was supposed to do.
The developer that chose this path defended it under the assumption that this saved tons of space because we weren't using Guids on the tables themselves (but...isn't a GUID generated in the Root table for every row we make?), improved performance somehow, and made it "easy" to audit changes to the database.
Oh, and the database diagram looked like a mutant spider from hell.
How about POBI -- pessimization obviously by intent?
Collegue of mine in the 90s was tired of getting kicked in the ass by the CEO just because the CEO spent the first day of every ERP software (a custom one) release with locating performance issues in the new functionalities. Even if the new functionalities crunched gigabytes and made the impossible possible, he always found some detail, or even seemingly major issue, to whine upon. He believed to know a lot about programming and got his kicks by kicking programmer asses.
Due to the incompetent nature of the criticism (he was a CEO, not an IT guy), my collegue never managed to get it right. If you do not have a performance problem, you cannot eliminate it...
Until for one release, he put a lot of Delay (200) function calls (it was Delphi) into the new code. It took just 20 minutes after go-live, and he was ordered to appear in the CEO's office to fetch his overdue insults in person.
Only unusual thing so far was my collegues mute when he returned, smiling, joking, going out for a BigMac or two while he normally would kick tables, flame about the CEO and the company, and spend the rest of the day turned down to death.
Naturally, my collegue now rested for one or two days at his desk, improving his aiming skills in Quake -- then on the second or third day he deleted the Delay calls, rebuilt and released an "emergency patch" of which he spread the word that he had spent 2 days and 1 night to fix the performance holes.
This was the first (and only) time that evil CEO said "great job!" to him. That's all that counts, right?
This was real POBI.
But it also is a kind of social process optimization, so it's 100% ok.
I think.
"Database Independence". This meant no stored procs, triggers, etc - not even any foreign keys.
var stringBuilder = new StringBuilder(); stringBuilder.Append(myObj.a + myObj.b + myObj.c + myObj.d); string cat = stringBuilder.ToString();
Best use of a StringBuilder I've ever seen.
Using a regex to split a string when a simple string.split suffices
Very late to this thread I know, but I saw this recently:
bool isFinished = GetIsFinished(); switch (isFinished) { case true: DoFinish(); break; case false: DoNextStep(); break; default: DoNextStep(); }
Y'know, just in case a boolean had some extra values...
Worst example I can think of is an internal database at my company containing information on all employees. It gets a nightly update from HR and has an ASP.NET web service on top. Many other apps use the web service to populate things like search/dropdown fields.
The pessimism is that the developer thought that repeated calls to the web service would be too slow to make repeated SQL queries. So what did he do? The application start event reads in the entire database and converts it all to objects in memory, stored indefinitely until the app pool is recycled. This code was so slow, it would take 15 minutes to load in less than 2000 employees. If you inadvertently recycled the app pool during the day, it could take 30 minutes or more, because each web service request would start multiple concurrent reloads. For this reason, new hires wouldn't appear in the database the first day when their account was created and therefore would not be able to access most internal apps on their first couple days, twiddling their thumbs.
The second level of pessimism is that the development manager doesn't want to touch it for fear of breaking dependent applications, but yet we continue to have sporadic company-wide outages of critical applications due to poor design of such a simple component.
No one seems to have mentioned sorting, so I will.
Several different times, I've discovered that someone had hand-crafted a bubblesort, because the situation "didn't require" a call to the "too fancy" quicksort algorithm that already existed. The developer was satisified when their handcrafted bubblesort worked well enough on the ten rows of data that they're using for testing. It didn't go over quite as well after the customer had added a couple of thousand rows.
I once had to attempt to modify code that included these gems in the Constants class
public static String COMMA_DELIMINATOR=","; public static String COMMA_SPACE_DELIMINATOR=", "; public static String COLIN_DELIMINATOR=":";
Each of these were used multiple times in the rest of the application for different purposes. COMMA_DELIMINATOR littered the code with over 200 uses in 8 different packages.
I once worked on an app that was full of code like this:
1 tuple *FindTuple( DataSet *set, int target ) { 2 tuple *found = null; 3 tuple *curr = GetFirstTupleOfSet(set); 4 while (curr) { 5 if (curr->id == target) 6 found = curr; 7 curr = GetNextTuple(curr); 8 } 9 return found; 10 }
Simply removing found, returning null at the end, and changing the sixth line to:
return curr;
Doubled the app performance.
The big all time number one which I run into time and time again in inhouse software:
Not using the features of the DBMS for "portability" reasons because "we might want to switch to another vendor later".
Read my lips. For any inhouse work: IT WILL NOT HAPPEN!
I had a co-worker who was trying to outwit our C compiler's optimizer and routine rewrote code that only he could read. One of his favorite tricks was changing a readable method like (making up some code):
int some_method(int input1, int input2) { int x; if (input1 == -1) { return 0; } if (input1 == input2) { return input1; } ... a long expression here ... return x; }
into this:
int some_method() { return (input == -1) ? 0 : (input1 == input2) ? input 1 : ... a long expression ... ... a long expression ... ... a long expression ... }
That is, the first line of a once-readable method would become "return" and all other logic would be replace by deeply nested terniary expressions. When you tried to argue about how this was unmaintainable, he would point to the fact that the assembly output of his method was three or four assembly instructions shorter. It wasn't necessarily any faster but it was always a tiny bit shorter. This was an embedded system where memory usage occasionally did matter, but there were far easier optimizations that could have been made than this that would have left the code readable.
Then, after this, for some reason he decided that ptr->structElement was too unreadable, so he started changing all of these into (*ptr).structElement on the theory that it was more readable and faster as well.
Turning readable code into unreadable code for at the most a 1% improvement, and sometimes actually slower code.
In one of my first jobs as a full-fledged developer, I took over a project for a program that was suffering scaling issues. It would work reasonably well on small data sets, but would completely crash when given large quantities of data.
As I dug in, I found that the original programmer sought to speed things up by parallelizing the analysis - launching a new thread for each additional data source. However, he'd made a mistake in that all threads required a shared resource, on which they were deadlocking. Of course, all benefits of concurrency disappeared. Moreover it crashed most systems to launch 100+ threads only to have all but one of them lock. My beefy dev machine was an exception in that it churned through a 150-source dataset in around 6 hours.
So to fix it, I removed the multi-threading components and cleaned up the I/O. With no other changes, execution time on the 150-source dataset dropped below 10 minutes on my machine, and from infinity to under half an hour on the average company machine.
I suppose I could offer this gem:
unsigned long isqrt(unsigned long value) { unsigned long tmp = 1, root = 0; #define ISQRT_INNER(shift) \ { \ if (value >= (tmp = ((root << 1) + (1 << (shift))) << (shift))) \ { \ root += 1 << shift; \ value -= tmp; \ } \ } // Find out how many bytes our value uses // so we don't do any uneeded work. if (value & 0xffff0000) { if ((value & 0xff000000) == 0) tmp = 3; else tmp = 4; } else if (value & 0x0000ff00) tmp = 2; switch (tmp) { case 4: ISQRT_INNER(15); ISQRT_INNER(14); ISQRT_INNER(13); ISQRT_INNER(12); case 3: ISQRT_INNER(11); ISQRT_INNER(10); ISQRT_INNER( 9); ISQRT_INNER( 8); case 2: ISQRT_INNER( 7); ISQRT_INNER( 6); ISQRT_INNER( 5); ISQRT_INNER( 4); case 1: ISQRT_INNER( 3); ISQRT_INNER( 2); ISQRT_INNER( 1); ISQRT_INNER( 0); } #undef ISQRT_INNER return root; }
Since the square-root was calculated at a very sensitive place, I got the task of looking into a way to make it faster. This small refactoring reduced the execution time by a third (for the combination of hardware and compiler used, YMMV):
unsigned long isqrt(unsigned long value) { unsigned long tmp = 1, root = 0; #define ISQRT_INNER(shift) \ { \ if (value >= (tmp = ((root << 1) + (1 << (shift))) << (shift))) \ { \ root += 1 << shift; \ value -= tmp; \ } \ } ISQRT_INNER (15); ISQRT_INNER (14); ISQRT_INNER (13); ISQRT_INNER (12); ISQRT_INNER (11); ISQRT_INNER (10); ISQRT_INNER ( 9); ISQRT_INNER ( 8); ISQRT_INNER ( 7); ISQRT_INNER ( 6); ISQRT_INNER ( 5); ISQRT_INNER ( 4); ISQRT_INNER ( 3); ISQRT_INNER ( 2); ISQRT_INNER ( 1); ISQRT_INNER ( 0); #undef ISQRT_INNER return root; }
Of course there are both faster AND better ways to do this, but I think it's a pretty neat example of a pessimization.
Edit: Come to think of it, the unrolled loop was actually also a neat pessimization. Digging though the version control, I can present the second stage of refactoring as well, which performed even better than the above:
unsigned long isqrt(unsigned long value) { unsigned long tmp = 1 << 30, root = 0; while (tmp != 0) { if (value >= root + tmp) { value -= root + tmp; root += tmp << 1; } root >>= 1; tmp >>= 2; } return root; }
This is exactly the same algorithm, albeit a slightly different implementation, so I suppose it qualifies.
This might be at a higher level that what you were after, but fixing it (if you're allowed) also involves a higher level of pain:
Insisting on hand rolling an Object Relationship Manager / Data Access Layer instead of using one of the established, tested, mature libraries out there (even after they've been pointed out to you).
All foreign-key constraints were removed from a database, because otherwise there would be so many errors.
This doesn't exactly fit the question, but I'll mention it anyway a cautionary tale. I was working on a distributed app that was running slowly, and flew down to DC to sit in on a meeting primarily aimed at solving the problem. The project lead started to outline a re-architecture aimed at resolving the delay. I volunteered that I had taken some measurements over the weekend that isolated the bottleneck to a single method. It turned out there was a missing record on a local lookup, causing the application to have to go to a remote server on every transaction. By adding the record back to the local store, the delay was eliminated - problem solved. Note the re-architecture wouldn't have fixed the problem.
Checking before EVERY javascript operation whether the object you are operating upon exists.
if (myObj) { //or its evil cousin, if (myObj != null) { label.text = myObj.value; // we know label exists because it has already been // checked in a big if block somewhere at the top }
My problem with this type of code is nobody seems to care what if it doesn't exist? Just do nothing? Don't give the feedback to the user?
I agree that the Object expected errors are annoying, but this is not the best solution for that.
How about YAGNI extremism. It is a form of premature pessimization. It seems like anytime you apply YAGNI, then you end up needing it, resulting in 10 times the effort to add it than if you had added it in the beginning. If you create a successful program then odds are YOU ARE GOING TO NEED IT. If you are used to creating programs whose life runs out quickly then continue to practice YAGNI because then I suppose YAGNI.
Not exactly premature optimisation - but certainly misguided - this was read on the BBC website, from an article discussing Windows 7.
Mr Curran said that the Microsoft Windows team had been poring over every aspect of the operating system to make improvements. "We were able to shave 400 milliseconds off the shutdown time by slightly trimming the WAV file shutdown music.
Now, I haven't tried Windows 7 yet, so I might be wrong, but I'm willing to bet that there are other issues in there that are more important than how long it takes to shut-down. After all, once I see the 'Shutting down Windows' message, the monitor is turned off and I'm walking away - how does that 400 milliseconds benefit me?
Someone in my department once wrote a string class. An interface like CString, but without the Windows dependence.
One "optimization" they did was to not allocate any more memory than necessary. Apparently not realizing that the reason classes like std::string do allocate excess memory is so that a sequence of += operations can run in O(n) time.
Instead, every single += call forced a reallocation, which turned repeated appends into an O(n²) Schlemiel the Painter's algorithm.
An ex-coworker of mine (a s.o.a.b., actually) was assigned to build a new module for our Java ERP that should have collected and analyzed customers' data (retail industry). He decided to split EVERY Calendar/Datetime field in its components (seconds, minutes, hours, day, month, year, day of week, bimester, trimester (!)) because "how else would I query for 'every monday'?"
No offense to anyone, but I just graded an assignment (java) that had this
import java.lang.*; | http://unixresources.net/faq/312003.shtml | CC-MAIN-2019-18 | refinedweb | 3,970 | 60.24 |
How to create data object without a file
A place to ask questions about methods in Orange and how they are used and other general support.
2 posts • Page 1 of 1
How to create data object without a file
Is there any way to create the data object NOT from Orange.data.Table() ? I think there should be some where to directly set values and attributes, but don't know how. thanks.
Re: How to create data object without a file
- Code: Select all
import Orange
domain = Orange.data.Domain([Orange.feature.Discrete("A", values=["a", "b"]), Orange.feature.Continuous("B")], None)
table = Orange.data.Table(domain, [["a", 1.0], ["b", 2.0]])
print table[0]
See the full documentation for Orange.data.Table.
2 posts • Page 1 of 1
Return to Questions & Support | http://orange.biolab.si/forum/viewtopic.php?p=5273 | CC-MAIN-2014-52 | refinedweb | 135 | 59.9 |
Introduction
In this tutorial we are going to learn how to display and use the Status Card from the ESP-DASH library. We will be using the ESP32 and the Arduino core.
In previous tutorials we have already covered dashboard cards suitable for sensor measurements (temperature, humidity and the generic card). These cards are useful when we want to display the numeric value of a measurement.
Nonetheless, we may also want to monitor the state of a given component of our system (ex: it is working / not working, the button is pressed / not pressed, etc…). For these scenarios, a status display is usually more adequate.
The Status Card supports 4 different values, each one with a different icon [1]:
- “success” – Green
- “danger” – Red
- “warning” – Yellow
- “idle” – Grey
Note that the names of the states we have listed above are basically the values we need to pass to have the different icons rendered. The actual message that is on the card can be defined by us.
As such, the “success” status, for example, doesn’t necessarily need to have a message indicating “success“. We can use something like “Working” or “Connected”, or similar, since the actual icon is quite generic and can apply for different use cases. The same goes for the other status.
In order for us to focus on how the card works, we are not going to attach any real sensor or device to the ESP32. Instead, we are going to check how to test its different values. Naturally, once we understand the basic operating mechanism, it should be easy to adapt for any particular device we want to monitor.
The tests shown below were performed on a ESP32-E FireBeetle board from DFRobot. The Arduino core version used was 2.0.0 and the Arduino IDE version was 1.8.15, working on Windows 8.1.
The code to display the status card
As usual, we will start by the library includes. These libraries will expose to us the functionality we need to connect the ESP32 to a WiFi network, setup a HTTP server and serve the real-time web dashboard.
#include <WiFi.h> #include <ESPAsyncWebServer.h> #include <ESPDash.h>
To be able to connect the ESP32 to the WiFi network, we will need to know its credentials. As such, we will define two global variables to hold the network name (SSID) and password. We will use them later in the Arduino setup.
const char* ssid = "networkName"; const char* password = "networkPassword";
Then we will create our AsyncWebServer object and our ESPDash object. The server object will be used under the hood by the ESP-DASH lib to take care of serving the web page with the dashboard and to the updates via a websocket connection.
ESPDash dashboard(&server);
We will then create a Card object and indicate in the constructor that we want to render a Status Card. The constructor receives the following parameters:
- The address of a ESPDash object.
- An enum value indicating the card type. A Status Card has a type equal to STATUS_CARD.
- The name of the card, which will be rendered in the dashboard. We will call it “Status“.
- The inicial status value of the card. The valid values are a list of strings listed here. We will start with “success“.
Card statusCard(&dashboard, STATUS_CARD, "Status", "success");
In order to display all the 4 possible status, we will define an array of strings with all the supported values. We will also define a global counter that will allow us to iterate over these values, so we are able to display them all in the dashboard.
int statusIterator = 0; char possibleStatus[4][10] = { "success", "danger", "warning", "idle" };
The Arduino setup will be pretty much what we have covered in previous tutorials: opening a serial connection, connecting the ESP32 to a WiFi network and starting the async HTTP web server. The full code is available below.
void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } Serial.println(WiFi.localIP()); server.begin(); }
We will use the Arduino main loop to iterate through all the values of our status array. To do so, we will start by incrementing the iterator by 1 and performing the modulo operation over the value 4 (the length of the status string array). This ensures a circular counter behavior that will never reach 4 (outside the array boundaries, which is indexed starting at zero) and will reset to 0 after the value 3.
statusIterator = (statusIterator+1)%4;
Then, just for readibility, we will assign the current value of the array to a variable.
char * currentStatus = possibleStatus[statusIterator];
After this we will call the update method in our Card object. This method receives two values: a message that will be printed on the card and the current status. We will pass the string with the current status in both, simply so we can match the icon with the status name later, when testing the code.
statusCard.update(currentStatus, currentStatus); dashboard.sendUpdates();
Finally we will introduce a 5 seconds delay between each iteration of the loop. The complete code for the loop is available in the snippet below.
void loop() { statusIterator = (statusIterator+1)%4; char * currentStatus = possibleStatus[statusIterator]; statusCard.update(currentStatus, currentStatus); dashboard.sendUpdates(); delay(5000); }
The complete code is available below.
#include <WiFi.h> #include <ESPAsyncWebServer.h> #include <ESPDash.h> const char* ssid = "networkName"; const char* password = "networkPassword"; AsyncWebServer server(80); ESPDash dashboard(&server); Card statusCard(&dashboard, STATUS_CARD, "Status", "success"); int statusIterator = 0; char possibleStatus[4][10] = { "success", "danger", "warning", "idle" }; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } Serial.println(WiFi.localIP()); server.begin(); } void loop() { statusIterator = (statusIterator+1)%4; char * currentStatus = possibleStatus[statusIterator]; statusCard.update(currentStatus, currentStatus); dashboard.sendUpdates(); delay(5000); }
Testing the code
As usual, to test the code, simply compile it and upload it to your ESP32 using the Arduino IDE. Once the procedure finishes, open the IDE serial monitor.
After the ESP32 connects to the WiFi network, it should print the IP address assigned to it on the network. Copy that value, since we are going to need it to access the dashboard.
Then, open a web browser of your choice and type the following in the address bar, changing #yourDeviceIp# by the IP you have just copied:
Upon navigating to this URL, you should get a result similar to figure 1. As can be seen, we have obtained a web page with the dashboard, which shows the status card. The current value shown is for “success”, but it should change periodically to the other values, as we have defined in our code.
References
[1]
Suggested ESP32 Readings
- Getting started with ESP-DASH
- Real-time web dashboard over soft AP
- HTTP async web server
- Generic card on web dashboard | https://techtutorialsx.com/2021/10/27/esp32-dashboard-status-card/ | CC-MAIN-2022-33 | refinedweb | 1,144 | 56.55 |
Ranter
Join devRant
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple APILearn More
- Demolishun19063124dI hope you kept, you know, a "paper trail".
Sounds like a buncha assholes.
- PaperTrail9219124d@Demolishun > "hope you kept, you know, a 'paper trail'."
Weirdly, I still have screenshots of the SharePoint site they used to track the 'improvements' and other misc. docs. I thought someday, they are going to claim Panorama never happened. Like clockwork, around a year later (we still had performance issues), they did. That's another (short) story.
- PaperTrail9219123d@Demolishun > "Sounds like a buncha assholes."
I'll throw in one of the developers changing code told me the DeptMgr's rage was mostly because of the name, not what it was doing. I was into prefixing namespaces after Transformers (Autobots/Decepticons). OptimisPrime.Models, etc.
When I asked about the KnightRider prefix (why it was OK)
Dev: "I don't know, I think he was a fan of the show too and thought it was cool. He keeps referring to MyLibrary as the 'Fucking stupid MyLibrary'. Nobody ever talks about any functionality issues with it."
- dontknowshit294123dI would have asked for a pay increase and then quit.
Sounds like a nightmare.
This is why non technical people, should not be in charge of code. They have no clue and mostly end up trusting those that can make whatever they are selling sound good.
- Nanos11087123dReminds me slightly of the time I saved the companies ass because I had created more backups than I was told to, just in case..
- iSwimInTheC40736122d
- Nanos11087120d@iSwimInTheC
Have to wait for another time !
Might be without power for an extended period of time here. ( aka months. )
-
- Nanos11087119d
- NemeXis26587d"experts"
Related Rants.
rant
wk301 | https://devrant.com/rants/5167975/biggest-challenge-i-overcame-as-dev-one-of-many-avoiding-a-life-sentence-when-th | CC-MAIN-2022-27 | refinedweb | 295 | 66.23 |
/* GDB-friendly replacement for <assert.h>._ASSERT_H #define GDB_ASSERT_H /* PRAGMATICS: "gdb_assert.h":gdb_assert() is a lower case (rather than upper case) macro since that provides the closest fit to the existing lower case macro <assert.h>:assert() that it is replacing. */ #define gdb_assert(expr) \ ((void) ((expr) ? 0 : \ (gdb_assert_fail (#expr, __FILE__, __LINE__, ASSERT_FUNCTION), 0))) /* Version 2.4 and later of GCC define a magical variable `__PRETTY_FUNCTION__' which contains the name of the function currently being defined. This is broken in G++ before version 2.6. C9x has a similar variable called __func__, but prefer the GCC one since it demangles C++ function names. */ #if (GCC_VERSION >= 2004) #define ASSERT_FUNCTION __PRETTY_FUNCTION__ #else #if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L #define ASSERT_FUNCTION __func__ #endif #endif /* This prints an "Assertion failed" message, aksing the user if they want to continue, dump core, or just exit. */ #if defined (ASSERT_FUNCTION) #define gdb_assert_fail(assertion, file, line, function) \ internal_error (file, line, _("%s: Assertion `%s' failed."), \ function, assertion) #else #define gdb_assert_fail(assertion, file, line, function) \ internal_error (file, line, _("Assertion `%s' failed."), \ assertion) #endif #endif /* gdb_assert.h */ | http://opensource.apple.com/source/gdb/gdb-1344/src/gdb/gdb_assert.h | CC-MAIN-2016-30 | refinedweb | 176 | 50.43 |
Caching data efficiently
When crawling websites I usually cache all HTML on disk to avoid having to re-download later. I wrote the pdict module to automate this process. Here is an example:
import pdict # initiate cache cache = pdict.PersistentDict('test.db') # compresses and store content in the database cache[url] = html # iterate all data in the database for key in cache: print cache[key]
The bottleneck here is insertions so for efficiency records can be buffered and then inserted in a single transaction:
# dictionary of data to insert data = {...} # cache each record individually (2m49.827s) cache = pdict.PersistentDict('test.db', max_buffer_size=0) for k, v in data.items(): cache[k] = v # cache all records in a single transaction (0m0.774s) cache = pdict.PersistentDict('test.db', max_buffer_size=5) for k, v in data.items(): cache[k] = v
In this example caching all records at once takes less than a second but caching each record individually takes almost 3 minutes. | https://webscraping.com/blog/Caching-data-efficiently/ | CC-MAIN-2019-18 | refinedweb | 159 | 58.69 |
You need to be using WAS 6.1.0.2 or higher, I think the latest version
is 6.1.0.17?
There are 3 thing that will make you stumble when installing on WAS.
First, you need to make a WAS Shared Library. Make a directory, named
Jetspeed, under ${WAS_INSTALL_ROOT}/optionalLibraries/Apache . And copy
the following files there:
jetspeed-api-2.1-dev.jar
jetspeed-commons-2.1-dev.jar
pluto-1.0.1.jar
portals-bridges-common-1.0.1-dev..jar
portlet-api-1.0.jar
(If your using 2.1.2 then the jetspeed-api jar will be named
jetspeed-api-2.1.1-dev.jar and so on).
Then in the WAS console, define the Shared Library under the environment
section. Make sure to enter the five jars into the Classpath field and
make sure they are separated with a carriage-return (if not it won't
work). So the Classpath field will look like this:
$
Secondly, you need to make a new classloader for the server instance
you'll install jetspeed on and reference the shared libraries from
there:
Select the server to install Jetspeed on, and then expand the Java and
Process Management section and then click on Classloader.
>From the Classloader page, click New.
On General Properties, set Classloader order to Classes loaded with
parent class loader first. Click OK, and then Save.
Then click on the classloader, then click on the Shared libraries
references link. Created a new shared library reference for the server
by clicking on add and select the Jetspeed shared library.
Next install the Jetspeed war, make sure you map this to the web server
and app server. When you install your portal war files, make sure NOT to
map them to the web server or app server.
Thirdly, when you create your datasources, make sure the jndi name is
jndi/jetspeed (you'll need to do this before you install your Portal and
make your restart WAS after creating the datasource and doing the Shared
Library).
-----Original Message-----
From: David Sean Taylor [mailto:david@bluesunrise.com]
Sent: Monday, November 05, 2007 1:45 PM
To: Jetspeed Users List
Subject: Re: How to deploy jetspeed2.1 on WAS 6.1?
Installing?
>
>
> ---------------------------------------------------------------------
> | http://mail-archives.apache.org/mod_mbox/portals-jetspeed-user/200711.mbox/%3C334DF11499913B4B845D3D888F93AD2D29E363@MSGBOSCLL2WIN.DMN1.FMR.COM%3E | CC-MAIN-2017-09 | refinedweb | 373 | 65.83 |
The Preprocessor
Abstract
The preprocessor is increasingly becoming redundant because of equivalent C++ language-based features. The const keyword allows constant identifiers to be defined. Macros are replaced by inline functions, with the template feature defining and declaring type-independent functions and classes. We shall see in the next chapter that the namespace feature associates a name to a given scope. All of const, inline, template and namespace are statically type-checked, whereas the preprocessor bypasses the static type checking mechanism of C++.
KeywordsLine Number Class Point Source File Null Directive Head File
These keywords were added by machine and not by the authors. This process is experimental and the keywords may be updated as the learning algorithm improves.
Preview
Unable to display preview. Download preview PDF.
© Springer-Verlag London Limited 1996 | https://link.springer.com/chapter/10.1007/978-1-4471-3378-0_18 | CC-MAIN-2018-30 | refinedweb | 132 | 50.02 |
go to bug id or search bugs for
New/Additional Comment:
Description:
------------
Objects can either be compared by checking if they are equivalent (are references to the same object) or have the same values, which may lead to severe performance penalties or recursion errors while checking. (See)
When using database stored objects, the identifier for the object is often stored as a single value within the object and it would be sufficient to compare the IDs of two different objects to know if they represent the same object in the database. In this cases, a === comparision would fail, the == comparison would succeed but could impose large overhead if a lot of other objects are referenced within the object. Sometimes even the == would fail because some caches are filled in one instance but not in the other.
There are several thinkable possibilities to solve this problem:
1. Use a magic method __compare() that returns a token for the object which then is used for comparison
2. Use a magic method __compare($obj) that returns true if the supplied object matches the "questioned" object
3. Use a magic method __compare() that returns an array containing a list of object properties to take into consideration, similar to the __sleep() magic method.
Test script:
---------------
class A {
protected $ID;
public function __construct($id) { $this->ID = $id; }
// Variant 1
public function __compare() { return $this->ID; }
// Variant 2
public function __compare($obj) { return ($this->ID == $obj->ID); }
// Variant 3
public function __compare() { return array('ID'); }
}
$a1 = new A(10);
$a2 = new A(20);
$a3 = new A(10);
echo ($a1 === $a2 ? "YES" : "NO") . "\n";
echo ($a1 === $a3 ? "YES" : "NO") . "\n";
Expected result:
----------------
NO
YES
Add a Patch
Add a Pull Request
This is a duplicate of
> This is a duplicate of
Indeed, a dupe of bug #25772. However, that bug report has been
closed as WONTFIX in the meantime, and even though I agree that
"those things are going to be to complicated and confusing", I
think pointing to the RFC process[1] is more appropriate nowadays.
Anybody is welcome to start it! For the time being, I'm
suspending this ticket.
[1] <> | https://bugs.php.net/bug.php?id=51875&edit=1 | CC-MAIN-2022-27 | refinedweb | 355 | 55.17 |
0
im currently trying to create a button widget using Tkiner and would like to know how to get a number from that button when i click on it. I have tried lots of methods and ideas from different people and i still haven't got the right bit of code. any help is very helpful.
def createEight(self): top=self.winfo_toplevel() top.rowconfigure(0, weight=1) top.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.Button = Button ( self, text=" 8 ", font=("Arial", 12), bg="white", fg="blue", cursor="crosshair") self.Button.grid(row=2, column=1, sticky=N+E+S+W) | https://www.daniweb.com/programming/software-development/threads/277925/tk | CC-MAIN-2016-50 | refinedweb | 109 | 55 |
How to connect to epo server 5.0, through python script?dipaliepo Oct 21, 2013 10:56 PM
import mcafee
mc = mcafee.client('epo-windows','8443','admin','Infyepo@123')
print ("hello");
When I try to connect to epo server 5.0 , which is located on remote machine by using above python script I am getting following excepion.
Please suggest the solution.
Traceback (most recent call last):
File "C:\Python33\lib\urllib\request.py", line 1248, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File "C:\Python33\lib\http\client.py", line 1061, in request
self._send_request(method, url, body, headers)
File "C:\Python33\lib\http\client.py", line 1099, in _send_request
self.endheaders(body)
File "C:\Python33\lib\http\client.py", line 1057, in endheaders
self._send_output(message_body)
File "C:\Python33\lib\http\client.py", line 902, in _send_output
self.send(msg)
File "C:\Python33\lib\http\client.py", line 840, in send
self.connect()
File "C:\Python33\lib\http\client.py", line 1194, in connect
self.timeout, self.source_address)
File "C:\Python33\lib\socket.py", line 417, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 11004] getaddrinfo failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python33\lib\mcafee.py", line 305, in get_response
sock = self.create_socket(url, fileargs)
File "C:\Python33\lib\mcafee.py", line 375, in create_socket
return self.opener.open(url)
File "C:\Python33\lib\urllib\request.py", line 469, in open
response = self._open(req, data)
File "C:\Python33\lib\urllib\request.py", line 487, in _open
'_open', req)
File "C:\Python33\lib\urllib\request.py", line 447, in _call_chain
result = func(*args)
File "C:\Python33\lib\urllib\request.py", line 1283, in https_open
context=self._context, check_hostname=self._check_hostname)
File "C:\Python33\lib\urllib\request.py", line 1251, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 11004] getaddrinfo failed>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\PythonWorkspace\de.vogella.python.first\src\webapiscriptexample-1.py", line 4, in <module>
mc = mcafee.client('epo-windows','8443','admin','Infyepo@123')
File "C:\Python33\lib\mcafee.py", line 537, in __init__
self._invoker.save_token()
File "C:\Python33\lib\mcafee.py", line 243, in save_token
response = self.get_response(url)
File "C:\Python33\lib\mcafee.py", line 313, in get_response
log_and_raise_error(logging.ERROR, 'Failed to reach the server %s:%s. Error/reason: %s' % (self.host,self.port,str(e)))
File "C:\Python33\lib\mcafee.py", line 92, in log_and_raise_error
raise CommandInvokerError(code, msg)
mcafee.CommandInvokerError: Failed to reach the server epo-windows:8443. Error/reason: <urlopen error [Errno 11004] getaddrinfo failed>
1. Re: How to connect to epo server 5.0, through python script?jbrooks2 Oct 22, 2013 11:52 AM (in response to dipaliepo)
The version of Python you are using appears to be Python 3.3. The mcafee.py script is not 3.x compatible. It's only compatible with 2.x and has been tested against 2.7. I would suggest running against 2.7 and try again.
2. Re: How to connect to epo server 5.0, through python script?tnichola Oct 22, 2013 11:58 AM (in response to dipaliepo)
dipaliepo,
I took the python client from MFS 5.0.0 and ran the script you have above (but pointed to oriondemo) and it worked as I expected. No errors and displayed, "hello".
Can you use the python client shipped with MFS or do you need Python 3.3 for a reason? | https://community.mcafee.com/thread/61690 | CC-MAIN-2017-34 | refinedweb | 596 | 56.32 |
The previous guide, which teaches you to Specify the code to
run on a thread, shows how to define a task that executes on a separate
thread. If you only want to run the task once, this may be all you need. If you want
to run a task repeatedly on different sets of data, but you only need one execution running at a
time, an
IntentService suits your needs. To automatically run tasks
as resources become available, or to allow multiple tasks to run at the same time (or both),
you need to provide a managed collection of threads. To do this, use an instance of
ThreadPoolExecutor, which runs a task from a queue when a thread
in its pool becomes free. To run a task, all you have to do is add it to the queue.
A thread pool can run multiple parallel instances of a task, so you should ensure that your
code is thread-safe. Enclose variables that can be accessed by more than one thread in a
synchronized block. This approach will prevent one thread from reading the variable
while another is writing to it. Typically, this situation arises with static variables, but it
also occurs in any object that is only instantiated once. To learn more about this, read the
Processes and threads overview guide.
Define the thread pool class
Instantiate
ThreadPoolExecutor in its own class. Within this class,
do the following:
- Use static variables for thread pools
- You may only want a single instance of a thread pool for your app, in order to have a single control point for restricted CPU or network resources. If you have different
Runnabletypes, you may want to have a thread pool for each one, but each of these can be a single instance. For example, you can add this as part of your global field declarations (for Kotlin we can create an object):
Kotlin
// Creates a single static instance of PhotoManager object PhotoManager { ... }
Java
public class PhotoManager { ... static { ... // Creates a single static instance of PhotoManager sInstance = new PhotoManager(); } ...
- Use a private constructor
- Making the constructor private ensures that it is a singleton, which means that you don't have to enclose accesses to the class in a
synchronizedblock (for Kotlin it is not necessary to have a private constructor because this is defined as an object so will only be initialised once):
Kotlin
object PhotoManager { ... }
Java
public class PhotoManager { ... /** * Constructs the work queues and thread pools used to download * and decode images. Because the constructor is marked private, * it's unavailable to other classes, even in the same package. */ private PhotoManager() { ... }
- Start your tasks by calling methods in the thread pool class.
- Define a method in the thread pool class that adds a task to a thread pool's queue. For example:ThreadPool. execute(downloadTask.getHTTPDownloadRunnable()); ... }
- Instantiate a
Handlerin the constructor and attach it to your app's UI thread.
- A
Handlerallows your app to safely call the methods of UI objects such as
Viewobjects. Most UI objects may only be safely altered from the UI thread. This approach is described in more detail in the lesson Communicate with the UI thread. For example: = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when * the Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { ... } ... } }
Determine the thread pool parameters
Once you have the overall class structure, you can start defining the thread pool. To
instantiate a
ThreadPoolExecutor object, you need the
following values:
- Initial pool size and maximum pool size
- The initial number of threads to allocate to the pool, and the maximum allowable number. The number of threads you can have in a thread pool depends primarily on the number of cores available for your device. This number is available from the system environment:(); }
availableProcessors()returns the number of active cores, which may be less than the total number of cores.
- Keep alive time and time unit
- The duration that a thread will remain idle before it shuts down. The duration is interpreted by the time unit value, one of the constants defined in
TimeUnit.
- A queue of tasks
- The incoming queue from which
ThreadPoolExecutortakes
Runnableobjects. To start code on a thread, a thread pool manager takes a
Runnableobject from a first-in, first-out queue and attaches it to the thread. You provide this queue object when you create the thread pool, using any queue class that implements the
BlockingQueueinterface. To match the requirements of your app, you can choose from the available queue implementations; to learn more about them, see the class overview for
ThreadPoolExecutor. This example uses the
LinkedBlockingQueueclass:
To create a pool of threads, instantiate a thread pool manager by calling
ThreadPoolExecutor().
This creates and manages a constrained group of threads. Because the initial pool size and
the maximum pool size are the same,
ThreadPoolExecutor creates
all of the thread objects when it is instantiated. For example:. | https://developer.android.com/training/multiple-threads/create-threadpool?hl=ja | CC-MAIN-2019-13 | refinedweb | 821 | 60.85 |
Heya Ludo, On Tue 26 May 2009 19:10, address@hidden (Ludovic Courtès) writes: > "Andy Wingo" <address@hidden> writes: > >> +#if BUILDING_LIBGUILE && HAVE_VISIBILITY >> +# define SCM_API extern __attribute__((__visibility__("default"))) >> +#elif BUILDING_LIBGUILE && defined _MSC_VER > > This should be: > > #if defined BUILDING_LIBGUILE && BUILDING_LIBGUILE && HAVE_VISIBILITY I believe that this is strictly equivalent. Quoth the CPP manual: #if expression controlled text #endif /* expression */ expression is a C expression of integer type, subject to stringent restrictions. It may contain * Integer constants. * Character constants ... * Arithmetic operators ... * Macros ... * Uses of the defined operator ... * Identifiers that are not macros, which are all considered to be the number zero. This allows you to write #if MACRO instead'. But I guess that we want to support -Wundef or something, and this is in a public header, so I suppose you are right :) > Also, I'd have preferred `_GUILE_WITHIN_GUILE', which is clearly in > Guile's name space, and is similar to GMP's `__GMP_WITHIN_GMP' ("rule of > least surprise"). What do you think? I don't care :) I thought I recalled that Neil wanted something else, and Bruno had this in the gnulib docs, so I just used that. Please tell me to change it if you want it changed :-) Cheers, Andy -- | https://lists.gnu.org/archive/html/guile-devel/2009-05/msg00045.html | CC-MAIN-2021-43 | refinedweb | 198 | 60.75 |
Duplicate strings.
char *_strdup(
const char *strSource
);
wchar_t *_wcsdup(
const wchar_t *strSource
);
unsigned char *_mbsdup(
const unsigned char *strSource
);
Null-terminated source string.
Each of these functions returns a pointer to the storage location for the copied string or NULL if storage cannot be allocated..
_tcsdup
_strdup
_mbsdup
_wcsdup.
<string.h>
Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium Edition, Windows NT 4.0, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003
<string.h> or <wchar.h>
_mbsdup
<mbstring.h>
For additional compatibility information, see Compatibility in the Introduction.
// crt_strdup.c
#include <string.h>
#include <stdio.h>
int main( void )
{
char buffer[] = "This is the buffer text";
char *newstring;
printf( "Original: %s\n", buffer );
newstring = _strdup( buffer );
printf( "Copy: %s\n", newstring );
free( newstring );
}
Original: This is the buffer text
Copy: This is the buffer text
System::String::Clone | http://msdn.microsoft.com/en-us/library/y471khhc(VS.80).aspx | crawl-002 | refinedweb | 145 | 50.84 |
Change the usage message for a command (QNX Neutrino)
usemsg [-ct] [-f info_file] [-i id[=value]] [-s string] loadfile [msgfile]
Linux, Mac, Microsoft Windows
#ifdef __USAGE ... #endif
Note that there are two underscores before USAGE.
You don't have to specify a value for the DATE and NAME ids.
The DATE, NAME, and QNX_BUILDID keys are added automatically when any other key is added.
The id is translated into uppercase.
If you specify multiple -s options, usemsg searches for them in order, and uses the first string section found.
The usemsg utility lets you examine or change the usage record contained within a QNX Neutrino executable program. All utilities supplied with the QNX Neutrino RTOS are shipped with a usage message describing their options. This information is kept in a resource record in the load file. Since this usage text isn't loaded into memory when the program is run, it doesn't affect the size of your program at runtime. The maximum size of a usage message is 400 lines of 1024 characters, which is likely beyond your wildest dreams of verbosity.
The use utility prints usage messages. For example:
use ls use more use pidin
Developers may use the usemsg utility to add usage messages to their programs.
Displaying help messages in ported executables
If you're porting or developing an executable that already has a help message invoked by an argument, you can make use display the existing help message by adding one extra line in the executable, like this:
%digit> cmd argument
where digit is where to read the output from, either 1 (stdout) or 2 (stderr). The use utility itself always prints to stdout, but executables may print to stdout or stderr.
For example, if some_gnu_tool has an option --help that sends a help message to stdout, add a line like this:
%1> some_gnu_tool --help
or:
%1> %C --help
In this example, when someone types:
use some_gnu_tool
The use utility spawns:
some_gnu_tool --help
and then prints the output.
If the executable sends its output to stderr, add this line instead:
%2> some_gnu_tool --help
Adding or changing a usage message is scanned and all text between an #ifdef __USAGE and the next #endif are links to the same load file, they can each have their own usage within the same usage record in the file.
The grammar consists of the special symbol % in the first column followed by an action character as follows:
To extract the entire usage message, including all languages and the grammar control sequences, name the loadfile and don't specify a msgfile.
The %-command and %=language are both optional. If both are specified, the %-command is followed by one or more %=language sections followed by another %-command and another set of %=language sections.. | https://www.qnx.com/developers/docs/7.1/com.qnx.doc.neutrino.utilities/topic/u/usemsg.html | CC-MAIN-2022-27 | refinedweb | 461 | 56.79 |
I'm working on my first Xamarin.Forms app, a PCL. I just implemented a Sqlite database and used Chapter 7, including its example code, of Dan Hermes' "Xamarin Mobile Application Development: Cross-Platform C# and Xamarin.Forms Fundamentals" book to guide me. The implementation actually looks to be the same as in the Xamarin.Forms "Todo" application, available on Github, with a Database class in each platform target that implements a DbConnect method, which itself basically builds the db path for each platform and creates a new SQLiteConnection with the path.
However, I'm getting a NullReferenceException in Android (I've tried WinPhone 8.1 so far and that works fine), on this line in the PCL's Database class (just a locking object, db instance variable, and constructor):
database = DependencyService.Get<IDatabase>().DbConnect();
I hit F11 to step-in and it told me I didn't have the DependencyService.cs source file. I happened to see the "DependencyService.cs Deep Dive" thread and now that I have the .cs file downloaded, whenever I hit F11 now it just says "Missing Frame Source" or whatever and I can't pick the file.
So. Any ideas on what's going wrong? Any way I can step into the Xamarin.Forms code now that I have the DependencyService.cs file?
Thank you so much for any help.
I think it's a problem with android implementation . Where is the string 'attribute ' ? Inside or outside namespace?
Why are you wasting time trying to debug DependencyService.cs?
Your problem is that you didn't register a native implementation of IDatabase. You said there is a class Database for each platform. You need to register the Android implementation in the native Android project:
Oh jeez, yeah that was it. Sorry guys, that was a derp mistake.
I appreciate the help, man.
@clamum Mark as answer.
I have register the native implementation of IDatabase still getting the null refrence exception. Please someone help me out | https://forums.xamarin.com/discussion/comment/208952 | CC-MAIN-2019-22 | refinedweb | 330 | 60.72 |
From source code inspection, I think there is a bug with 4 level page table with vhpt_miss handler. In the code path of rechecking page table entry against previously read value after tlb insertion, *pte value in register r18 was overwritten with value newly read from pud pointer, render the check of new *pte against previous *pte completely wrong. Though the bug is none fatal and the penalty is to purge the entry and retry. For functional correctness, it should be fixed. The fix is to use a different register so new *pud don't trash *pte. (btw, the comments in the cmp statement is wrong as well, which I will address in the next patch). Signed-off-by: Ken Chen <kenneth.w.chen@intel.com> --- ./arch/ia64/kernel/ivt.S.orig 2005-11-16 23:35:27.086799703 -0800 +++ ./arch/ia64/kernel/ivt.S 2005-11-17 00:14:51.247903555 -0800 @@ -209,13 +209,13 @@ ENTRY(vhpt_miss) ld8 r25=[r21] // read L4 entry again ld8 r26=[r17] // read L3 PTE again #ifdef CONFIG_PGTABLE_4 - ld8 r18=[r28] // read L2 entry again + ld8 r19=[r28] // read L2 entry again #endif cmp.ne p6,p7=r0,r0 ;; cmp.ne.or.andcm p6,p7=r26,r20 // did L3 entry change #ifdef CONFIG_PGTABLE_4 - cmp.ne.or.andcm p6,p7=r29,r18 // did L4 PTE change + cmp.ne.or.andcm p6,p7=r19,r29 // did L4 PTE change #endif mov r27=PAGE_SHIFT<<2 ;; - To unsubscribe from this list: send the line "unsubscribe linux-ia64" in the body of a message to majordomo@vger.kernel.org More majordomo info at on Thu, 17 Nov 2005 01:38:42 -0800
This archive was generated by hypermail 2.1.8 : 2005-11-17 20:39:29 EST | http://www.gelato.unsw.edu.au/archives/linux-ia64/0511/15901.html | CC-MAIN-2020-16 | refinedweb | 290 | 65.93 |
3. Types¶
QL is a statically typed language, so each variable must have a declared type. A type is a set of values.
For example, the type
int is the set of integers.
Note that a value can belong to more than one of these sets, which means that it can have more
than one type.
The kinds of types in QL are primitive types, classes, character types, class domain types, algebraic datatypes, and database types.
3.1. Primitive types¶
These types are built in to QL and are always available in the global namespace, independent of the database that you are querying.
- boolean: This type contains the values
trueand
false.
- float: This type contains 64-bit floating point numbers, such as
6.28and
-0.618.
- int: This type contains 32-bit two’s complement integers, such as
-1and
42.
- string: This type contains finite strings of 16-bit characters.
- date: This type contains dates (and optionally times).
QL has a range of built-in operations defined on primitive types. These are available by using dispatch on expressions of the appropriate type. For example,
1.toString() is the string representation of the integer constant
1. For a full list of built-in operations available in QL, see the
section on built-ins in the QL language specification.
3.2. Classes¶
You can define your own types in QL. One way to do this is to define a class.
- Classes provide an easy way to reuse and structure code. For example, you can:
- Group together related values.
- Define member predicates on those values.
- Define subclasses that override member predicates.
A class in QL doesn’t “create” a new object, it just represents a logical property. A value is in a particular class if it satisfies that logical property.
3.2.1. Defining a class¶
To define a class, you write:
- The keyword
class.
- The name of the class. This is an identifier starting with an uppercase letter.
- The types to extend.
- The body of the class, enclosed in braces.
For example:
class OneTwoThree extends int { OneTwoThree() { // characteristic predicate this = 1 or this = 2 or this = 3 } string getAString() { // member predicate result = "One, two or three: " + this.toString() } predicate isEven() { // member predicate this = 2 } }
This defines a class
OneTwoThree, which contains the values
1,
2, and
3. The
characteristic predicate captures the logical property of
“being one of the integers 1, 2, or 3.”
OneTwoThree extends
int, that is, it is a subtype of
int. A class in QL must always
extend at least one existing type. Those types are called the base types of the class. The
values of a class are contained within the intersection of the base types (that is, they are in
the class domain type). A class inherits all member predicates from its
base types.
A class can extend multiple types. See Multiple inheritance below.
- To be valid, a class:
- Must not extend itself.
- Must not extend a final class.
- Must not extend types that are incompatible. (See Type compatibility.)
You can also annotate a class. See the list of annotations available for classes.
3.2.2. Class bodies¶
- The body of a class can contain:
- A characteristic predicate declaration.
- Any number of member predicate declarations.
- Any number of field declarations.
When you define a class, that class also inherits all non-private member predicates and fields from its supertypes. You can override those predicates and fields to give them a more specific definition.
Characteristic predicates¶
These are predicates defined inside the body of a class. They are logical
properties that use the variable
this to restrict the possible values in the class.
Member predicates¶
These are predicates that only apply to members of a particular class. You can call a member predicate on a value. For example, you can use the member predicate from the above class:
1.(OneTwoThree).getAString()
This call returns the result
"One, two or three: 1".
The expression
(OneTwoThree) is a cast. It ensures that
1 has type
OneTwoThree instead of just
int. Therefore, it has access to the member predicate
getAString().
Member predicates are especially useful because you can chain them together. For example, you
can use
toUpperCase(), a built-in function defined for
string:
1.(OneTwoThree).getAString().toUpperCase()
This call returns
"ONE, TWO OR THREE: 1".
Note
Characteristic predicates and member predicates often use the variable
this.
This variable always refers to a member of the class—in this case a value belonging to the
class
OneTwoThree.
In the characteristic predicate, the variable
this
constrains the values that are in the class.
In a member predicate,
this acts in the same way as any
other argument to the predicate.
Fields¶
These are variables declared in the body of a class. A class can have any number of field
declarations (that is, variable declarations) within its body. You can use these variables in
predicate declarations inside the class. Much like the variable
this, fields
must be constrained in the characteristic predicate.
For example:
class SmallInt extends int { SmallInt() { this = [1 .. 10] } } class DivisibleInt extends SmallInt { SmallInt divisor; // declaration of the field `divisor` DivisibleInt() { this % divisor = 0 } SmallInt getADivisor() { result = divisor } } from DivisibleInt i select i, i.getADivisor()
In this example, the declaration
SmallInt divisor introduces a field
divisor, constrains
it in the characteristic predicate, and then uses it in the declaration of the member predicate
getADivisor. This is similar to introducing variables in a select clause
by declaring them in the
from part.
You can also annotate predicates and fields. See the list of annotations that are available.
3.2.3. Kinds of classes¶
The classes in the above examples are all concrete classes. They are defined by restricting the values in a larger type. The values in a concrete class are precisely those values in the intersection of the base types that also satisfy the characteristic predicate of the class.
A class annotated with
abstract, known as an abstract class, is also a restriction of
the values in a larger type. However, an abstract class is defined as the union of its
subclasses. In particular, for a value to be in an abstract class, it must satisfy the
characteristic predicate of the class itself and the characteristic predicate of a subclass.
An abstract class is useful if you want to group multiple existing classes together under a common name. You can then define member predicates on all those classes. You can also extend predefined abstract classes: for example, if you import a library that contains an abstract class, you can add more subclasses to it.
Example
If you are writing a security query, you may be interested in identifying all expressions that can be interpreted as SQL queries. You can use the following abstract class to describe these expressions:
abstract class SqlExpr extends Expr { ... }
Now define various subclasses—one for each kind of database management system. For example, you
can define a subclass
class PostgresSqlExpr extends SqlExpr, which contains expressions
passed to some Postgres API that performs a database query.
You can define similar subclasses for MySQL and other database management systems.
The abstract class
SqlExpr refers to all of those different expressions. If you want to add
support for another database system later on, you can simply add a new subclass to
SqlExpr;
there is no need to update the queries that rely on it.
3.2.4. Overriding member predicates¶
If a class inherits a member predicate from a supertype, you can override the inherited
definition. You do this by defining a member predicate with the same name and arity as the
inherited predicate, and by adding the
override annotation.
This is useful if you want to refine the predicate to give a more specific result for the
values in the subclass.
For example, extending the class from the first example:
class OneTwo extends OneTwoThree { OneTwo() { this = 1 or this = 2 } override string getAString() { result = "One or two: " + this.toString() } }
The member predicate
getAString() overrides the original definition of
getAString()
from
OneTwoThree.
Now, consider the following query:
from OneTwoThree o select o, o.getAString()
The query uses the “most specific” definition(s) of the predicate
getAString(), so the results
look like this:
In QL, unlike other object-oriented languages, different subtypes of the same types don’t need to be
disjoint. For example, you could define another subclass of
OneTwoThree, which overlaps
with
OneTwo:
class TwoThree extends OneTwoThree { TwoThree() { this = 2 or this = 3 } override string getAString() { result = "Two or three: " + this.toString() } }
Now the value 2 is included in both class types
OneTwo and
TwoThree. Both of these classes
override the original definition of
getAString(). There are two new “most specific” definitions,
so running the above query gives the following results:
3.2.5. Multiple inheritance¶
A class can extend multiple types. In that case, it inherits from all those types.
For example, using the definitions from the above section:
class Two extends OneTwo, TwoThree {}
Any value in the class
Two must satisfy the logical property represented by
OneTwo,
and the logical property represented by
TwoThree. Here the class
Two contains one
value, namely 2.
It inherits member predicates from
OneTwo and
TwoThree. It also (indirectly) inherits
from
OneTwoThree and
int.
Note
If a subclass inherits multiple definitions for the same predicate name, then it must override those definitions to avoid ambiguity. Super expressions are often useful in this situation.
3.3. Character types and class domain types¶
You can’t refer to these types directly, but each class in QL implicitly defines a character type and a class domain type. (These are rather more subtle concepts and don’t appear very often in practical query writing.)
The character type of a QL class is the set of values satisfying the characteristic predicate of the class. It is a subset of the domain type. For concrete classes, a value belongs to the class if, and only if, it is in the character type. For abstract classes, a value must also belong to at least one of the subclasses, in addition to being in the character type.
The domain type of a QL class is the intersection of the character types of all its supertypes, that is, a value
belongs to the domain type if it belongs to every supertype. It occurs as the type of
this
in the characteristic predicate of a class.
3.4. Algebraic datatypes¶
Note
The syntax for algebraic datatypes is considered experimental and is subject to change. However, they appear in the standard QL libraries so the following sections should help you understand those examples.
An algebraic datatype is another form of user-defined type, declared with the keyword
newtype.
Algebraic datatypes are used for creating new values that are neither primitive values nor entities from the database. One example is to model flow nodes when analyzing data flow through a program.
An algebraic datatype consists of a number of mutually disjoint branches, that each define a branch type. The algebraic datatype itself is the union of all the branch types. A branch can have arguments and a body. A new value of the branch type is produced for each set of values that satisfy the argument types and the body.
A benefit of this is that each branch can have a different structure. For example, if you want
to define an “option type” that either holds a value (such as a
Call) or is empty, you
could write this as follows:
newtype OptionCall = SomeCall(Call c) or NoCall()
This means that for every
Call in the program, a distinct
SomeCall value is produced.
It also means that a unique
NoCall value is produced.
3.4.1. Defining an algebraic datatype¶
To define an algebraic datatype, use the following general syntax:
newtype <TypeName> = <branches>
The branch definitions have the following form:
<BranchName>(<arguments>) { <body> }
- The type name and the branch names must be identifiers starting with an uppercase letter. Conventionally, they start with
T.
- The different branches of an algebraic datatype are separated by
or.
- The arguments to a branch, if any, are variable declarations separated by commas.
- The body of a branch is a predicate body. You can omit the branch body, in which case it defaults to
any(). Note that branch bodies are evaluated fully, so they must be finite. They should be kept small for good performance.
For example, the following algebraic datatype has three branches:
newtype T = Type1(A a, B b) { body(a, b) } or Type2(C c) or Type3()
3.4.2. Standard pattern for using algebraic datatypes¶
Algebraic datatypes are different from classes. In particular, algebraic datatypes don’t have a
toString() member predicate, so you can’t use them in a select clause.
Classes are often used to extend algebraic datatypes (and to provide a
toString() predicate).
In the standard QL language libraries, this is usually done as follows:
- Define a class
Athat extends the algebraic datatype and optionally declares abstract predicates.
- For each branch type, define a class
Bthat extends both
Aand the branch type, and provide a definition for any abstract predicates from
A.
- Annotate the algebraic datatype with private, and leave the classes public.
For example, the following code snippet from the CodeQL data-flow library for C# defines classes
for dealing with tainted or untainted values. In this case, it doesn’t make sense for
TaintType to extend a database type. It is part of the taint analysis, not the underlying
program, so it’s helpful to extend a new type (namely
TTaintType):
private newtype TTaintType = TExactValue() or TTaintedValue() /** Describes how data is tainted. */ class TaintType extends TTaintType { string toString() { this = TExactValue() and result = "exact" or this = TTaintedValue() and result = "tainted" } } /** A taint type where the data is untainted. */ class Untainted extends TaintType, TExactValue { } /** A taint type where the data is tainted. */ class Tainted extends TaintType, TTaintedValue { }
3.5. Database types¶
Database types are defined in the database schema. This means that they depend on the database that you are querying, and vary according to the data you are analyzing.
For example, if you are querying a CodeQL database for a Java project, the database types may
include
@ifstmt, representing an if statement in the Java code, and
@variable,
representing a variable.
3.6. Type compatibility¶
Not all types are compatible. For example,
4 < "five" doesn’t make sense, since you can’t
compare an
int to a
string.
To decide when types are compatible, there are a number of different “type universes” in QL.
- The universes in QL are:
- One for each primitive type (except
intand
float, which are in the same universe of “numbers”).
- One for each database type.
- One for each branch of an algebraic datatype.
- For example, when defining a class this leads to the following restrictions:
- A class can’t extend multiple primitive types.
- A class can’t extend multiple different database types.
- A class can’t extend multiple different branches of an algebraic datatype. | https://help.semmle.com/QL/ql-handbook/types.html | CC-MAIN-2019-51 | refinedweb | 2,489 | 56.45 |
On Fri, May 22, 2015 at 06:53:45AM AEST, Sander Eikelenboom wrote: > Hello Sander, > > Thursday, May 21, 2015, 10:40:24 PM, you wrote: > > > Sunday, May 17, 2015, 2:18:38 PM, you wrote: > > >> Sunday, May 17, 2015, 10:30:31 AM, you wrote: > > >>> Sunday, May 17, 2015, 12:55:55 AM, you wrote: > > >>>> -----BEGIN PGP SIGNED MESSAGE----- > >>>> Hash: SHA512 > > >>>> hi > >>>> As far as I know, espeak does. The issue is that sond icons are not > >>>> usually included in speech-dispatcher packages by default, and they're > >>>> not usually in linux distribution repositories. I remember actually > >>>> grabbing the sound icons package once, but never got it working. This > >>>> is one area that might need help from distro maintainers. I can > >>>> probably get someone to include a sound icons package in arch if it > >>>> will get at least a little use > >>>> Thanks > >>>> Kendell clark > > >>> Added the Debian sound-icons package maintainer and the "Debian Accessibility > >>> Team" mailinglist to the CC. > > >>> I'm using Debian Jessie, it has an seperate package for the sound-icons them > >>> selves and i have it installed: > >>> $ dpkg -l | grep speech > >>> ii espeak 1.48.04+dfsg-1 amd64 Multi-lingual software speech synthesizer > >>> ii espeak-data:amd64 1.48.04+dfsg-1 amd64 Multi-lingual software speech synthesizer: speech data files > >>> ii festival 1:2.1~release-8 amd64 General multi-lingual speech synthesis system > >>> ii festival-dev 1:2.1~release-8 amd64 Development kit for the Festival speech synthesis system > >>> ii festlex-poslex 1.4.0-5 all Part of speech lexicons and ngram from English > >>> ii libespeak-dev:amd64 1.48.04+dfsg-1 amd64 Multi-lingual software speech synthesizer: development files > >>> ii libespeak1:amd64 1.48.04+dfsg-1 amd64 Multi-lingual software speech synthesizer: shared library > >>> ii libflite1:amd64 1.4-release-12 amd64 Small run-time speech synthesis engine - shared libraries > >>> ii libgsm1:amd64 1.0.13-4 amd64 Shared libraries for GSM speech compressor > >>> ii libopencore-amrnb0:amd64 0.1.3-2.1 amd64 Adaptive Multi Rate speech codec - shared library > >>> ii libopencore-amrwb0:amd64 0.1.3-2.1 amd64 Adaptive Multi-Rate - Wideband speech codec - shared library > >>> ii libsonic0:amd64 0.1.17-1.1 amd64 Simple library to speed up or slow down speech > >>> ii libspeechd-dev 0.8-7 amd64 Speech Dispatcher: Development libraries and header files > >>> ii libspeechd2:amd64 0.8-7 amd64 Speech Dispatcher: Shared libraries > >>> ii mbrola 3.01h+1-2 amd64 Multilingual software speech synthesizer > >>> ii python3-speechd 0.8-7 all Python interface to Speech Dispatcher > >>> ii sound-icons 0.1-3 all Sounds for speech enabled applications > >>> ii speech-dispatcher 0.8-7 amd64 Common interface to speech synthesizers > >>> ii speech-dispatcher-audio-plugins:amd64 0.8-7 amd64 Speech Dispatcher: Audio output plugins > >>> ii speech-dispatcher-festival 0.8-7 amd64 Festival support for Speech Dispatcher > >>> ii speech-tools 1:2.1~release-8 amd64 Edinburgh Speech Tools - user binaries > > >>> Double checked and they are in: /usr/share/sounds/sound-icons/ which corresponds > >>> with the path in speech-dispatchers espeak.conf file. > > >>> Is there by your knowledge an option on package build-time that could be > >>> involved (and is perhaps not enabled) ? > > >>> I will try to switch on some more debugging again, see if it comes up with > >>> something (can't remember it did last time i tried). > > >>> Thanks for your time ! > > >>> -- > >>> Sander > > >> Here is my simple python test script: > >> #!/usr/bin/env python3 > > >> import speechd > > >> ssipclient = speechd.SSIPClient('sound-icon-test', socket_path='/run/user/1000/speech-dispatcher/speechd.sock') > >> ssipclient.sound_icon('start') > >> ssipclient.sound_icon('trumpet-12') > >> ssipclient.sound_icon('trumpet-12.wav') > >> ssipclient.close() > > > >> But instead of playing the sound of the sound-icon, it reads the name. > > >> I have set debug to 5 and attached the speech-dispatcher logs from running this > >> script. With my untrained eye i don't see anything obvious though. > > >> -- > >> Sander > > > >>>> Sander Eikelenboom wrote: > >>>>> Hi All, > >>>>> > >>>>> I'm trying out speech-dispatcher and the python module for a > >>>>> project. Speech works great, but i'm struggling to to get the > >>>>> "sound-icons" to work. The documentation is rather sparse :-( > >>>>> > >>>>> from /etc/speech-dispatcher/modules/espeak.conf it seems that > >>>>> espeak doesn't support sound-icons, which is a but cryptic since > >>>>> after that it shows configuration options for sound-icons ?: # -- > >>>>> > >>>>> > >>>>> > >>>>> I also tried festival, but still to no avail .. > >>>>> > >>>>> So the first question is .. are there any modules/backends that do > >>>>> support playing sound-icons ? > >>>>> > >>>>> Hope you can give me a pointer in the right direction ! > >>>>> > >>>>> -- Sander > >>>>> > > > > Ok i finally determined what the problem is: > > > espeak relies on speech-dispatcher to return 0 for the uri_callback if it has to > > play the sound, if it gets 1 back, it will speak the name of the sound-icon > > instead. > > > But in speech-dispatcher src/modules/espeak.c:uri_callback() the return that > > returns 0 is ifdeffed: > > > static int uri_callback(int type, const char *uri, const char *base) > > { > > int result = 1; > > if (type == 1) { > > /* Audio icon */ > > #if HAVE_SNDFILE > > if (g_file_test(uri, G_FILE_TEST_EXISTS)) { > > result = 0; > > } > > #endif > > } > > return result; > > } > > > And Debians speech-dispatchers isn't compiled with libsndfiledev1, so it always > > returns 1. > > > But since the code in the ifdef has no relation with libsndfiledev, is it even > > needed in the first place ? > > > Both solutions make sound-icons work for me on Debian Jessie: > > - recompiling with libsndfiledev installed > > or > > - removing the ifdef from uri_callback > > > But removing the ifdef as it seems pointless is looking like the best solution > > to me. > > Hmm that seems to be incorrect, probably tested with a stale tree or something. > When returning 0, it seems to be speech-dispatches that is going to play the > sound instead of espeak, using the code in > src/modules/module_utils.c:module_play_file() > > So the only solution seems to be for Debian to compile with libsndfiledev as > build dependency. Git master and the 0.8 branch has already got a patch in it that bumps libsndfile to a mandetory build depednecy, and the ifdefs are removed in that patch as well. ?So as of 0.8.3, libsndfile will be required, such that the sound icon experience is not impaired for users. Luke | https://lists.debian.org/debian-accessibility/2015/05/msg00040.html | CC-MAIN-2019-18 | refinedweb | 1,025 | 55.95 |
import java.io.File; import java.io.IOException; import java.util.Random; /** * Create a uniquely named temporary file. * * @param near if null, the temporary file will be created in the current directory. * If near is a valid file, then the temporary file will be created in the * same directory as near. * If near represents a file, the temporary file will be created in the * same directory as near. * If near represents a directory, the temporary file will be created in that * directory. * If near is invalid, then the temporary file will be created in the current * directory. * @param prefix name of application to prefix to file name. * @return a temporary File with a unique name of the form ~xxxxx99999999.temp. */ static File getTempFile ( File near, String prefix ) throws IOException { String path = null; if ( near != null ) if ( near.isFile() ) path = near.getParent(); else if ( near.isDirectory() ) path = near.getPath(); Random wheel = new Random(); // seeded from the clock File tempFile = null; do { // generate random a number 10,000,000 .. 99,999,999 int unique = ( wheel.nextInt() & Integer. MAX_VALUE ) %90000000 + 10000000; tempFile = new File( path, '~' + prefix + Integer.toString ( unique) + ".temp" ); } while ( tempFile.exists() ); // We "finally" found a name not already used. Nearly always the first time. // Quickly stake our claim to it by opening/closing it to create it. // In theory somebody could have grabbed it in that tiny window since // we checked if it exists, but that is highly unlikely. new FileOutputStream( tempFile ).close(); // debugging peek at the name generated. if ( false ) { out.println( tempFile.getCanonicalPath()); } return tempFile; } // end getTempFile | http://www.mindprod.com/jgloss/snippet/iframe/temporaryfiles.example1.javafrag.htm | CC-MAIN-2017-47 | refinedweb | 258 | 62.54 |
Created on 2012-10-19 10:15 by mark.dickinson, last changed 2012-11-03 13:52 by asvetlov. This issue is now closed.
The ThreadPoolExecutor unnecessarily keeps references to _WorkItem objects. With the attached patch (which lacks a test), all tests still pass, and the references are removed as soon as they're no longer needed.
A new patch (with tests), and a fuller explanation:
At work, we've got Python talking to a customer's existing COM library; we're using Thomas Heller's 'comtypes' library to do that. Unfortunately, comtypes depends quite a lot on __del__-time cleanup, so reference counting matters. (I'm well aware that this isn't the recommended way to deal with resource cleanup in Python, but rewriting the existing infrastructure isn't a realistic option here.)
Anyway, it turned out that the concurrent.futures executors were indirectly holding onto references to COM objects, causing issues with our application.
The attached patch adds a few 'del' statements to remove references that are no longer needed. For the ProcessExecutor, some of those 'del' statements had to go into the multiprocessing.Queue implementation.
The troublesome pattern (in both multiprocessing and futures) takes the form (simplified):
def my_worker_function(...):
...
while <exit_condition_not_satisfied>:
obj = blocking_wait_for_next_item()
do_processing(obj)
...
The issue is that the reference to obj is kept until the completion of the next blocking wait call. I'm suggesting just adding an extra 'del obj' after 'do_processing(obj)'.
Sounds fine to me. You might want to make the test CPython-specific.
The concurrent.futures stuff looks good to me.
Could you add a comment explaining why the delete is necessary? And, as Antoine said, the test should be CPython only.
LGTM
Updated patch to execute tests only for CPython.
Added comments to patch
New changeset 70cef0a160cf by Andrew Svetlov in branch 'default':
Issue #16284: Prevent keeping unnecessary references to worker functions in concurrent.futures ThreadPoolExecutor.
Committed. Thanks. | https://bugs.python.org/issue16284 | CC-MAIN-2021-21 | refinedweb | 318 | 58.48 |
A preprocessed T4 template is an easy, out-of-the-box technology you can use for generating text from a template at runtime. Preprocessed templates are a little different than the T4 templates you might have used in the past. For details, read Oleg Sych's post on the topic.
As an example, let's say you add a preprocessed template named "LetterTemplate.tt" to a project, with the following content:
<#@ template language="C#" #> Hi <#= Model.FirstName #>, Thank you for the email. Although our schedules are very busy, we decided to take some time and write you a personal reply. We appreciate the thoughtful feedback on show <#= Model.ShowNumber #>, and we want to promise you, <#= Model.FirstName #>, that we will try harder. Sincerely,
For this example, only three pieces of code are required. First there is the partial class to extend the definition of a class generated from the template:
public partial class LetterTemplate { public LetterModel Model { get; set; } }
Secondly is the definition of LetterModel:
public class LetterModel { public string FirstName { get; set; } public string ShowNumber { get; set; } }
And finally, only a few lines of code are required to execute the template and produce a result.
var template = new LetterTemplate(); template.Model = new LetterModel() { FirstName = "...", ShowNumber = "..." }; var message = template.TransformText();
TranformText is all you need , yet the generation scenarios can be much more complex. | https://odetocode.com/blogs/scott/archive/2011/01/04/preprocessed-t4-templates.aspx | CC-MAIN-2021-21 | refinedweb | 224 | 57.98 |
April 2019
Volume 34 Number 4
[Artificially Intelligent]
How Do Neural Networks Learn?
In my previous column (“A Closer Look at Neural Networks,” msdn.com/magazine/mt833269), I explored the basic structure of neural networks and created one from scratch with Python. After reviewing the basic structures common to all neural networks, I created a sample framework for computing the weighted sums and output values. Neurons themselves are simple and perform basic mathematical functions to normalize their outputs between 1 and 0 or -1 and 1. They become powerful, however, when they’re connected to each other. Neurons are arranged in layers in a neural network and each neuron passes on values to the next layer. Input values cascade forward through the network and affect the output in a process called forward propagation.
However, exactly how do neural networks learn? What is the process and what happens inside a neural network when it learns? In the previous column, the focus was on the forward propagation of values. For supervised learning scenarios, neural networks can leverage a process called backpropagation.
Backpropagation, Loss and Epochs
Recall that each neuron in a neural network takes in input values multiplied by a weight to represent the strength of that connection. Backpropagation discovers the correct weights that should be applied to nodes in a neural network by comparing the network’s current outputs with the desired, or correct, outputs. The difference between the desired output and the current output is computed by the Loss, or Cost, function. In other words, the Loss function tells us how accurate our neural network is at making predictions for a given input.
You might be familiar with the loss (error) function associated with classical statistics linear regression, as shown in Figure 1. That loss function provides the average of the squared differences between correct output values (the yi) and the computed values, which depend on the slope (m) and the y-intercept (b) of the regression line. The loss function for a neural network classifier uses the same general principle -- the difference between correct output values and computed output values. There are, in fact, three common loss functions for neural networks: mean squared error, cross entropy error, and binary cross entropy error. The demo program in this article uses cross entropy error, which is a complex topic in its own right.
Figure 1 The Cost, or Loss, Function
The algorithm then adjusts each weight to minimize the difference between the computed value and the correct value. The term “backpropagation” comes from the fact that the algorithm goes back and adjusts the weights and biases after computing an answer. The smaller the Loss for a network, the more accurate it becomes. The learning process, then, can be quantified as minimizing the loss function’s output. Each cycle of forward propagation and backpropagation correction to lower the Loss is called an epoch. Simply put, backpropagation is about finding the best input weights and biases to get a more accurate output or “minimize the Loss.” If you’re thinking this sounds computationally expensive, it is. In fact, compute power was insufficient until relatively recently to make this process practical for wide use.
Gradient Descent, Learning Rate and Stochastic Gradient Descent
How are the weights adjusted in each epoch? Are they randomly adjusted or is there a process? This is where a lot of beginners start to get confused, as there are a lot of unfamiliar terms thrown around, like gradient descent and learning rate. However, it’s really not that complicated when explained properly. The Loss function reduces all the complexity of a neural network down to a single number that indicates how far off the neural network’s, answer is from the desired answer. Thinking of the neural network’s output as a single number allows us to think about its performance in simple terms. The goal is to find the series of weights that results in the lowest loss value, or the minimum.
Plotting this on a graph, as in Figure 2, shows that the Loss function has its own curve and gradients that can be used as a guide to adjust the weights. The slope of the Loss function’s curve serves as a guide and points to the minimum value. The goal is to locate the minimum across the entire curve, which represents the inputs where the neural network is most accurate.
Figure 2 Graph of the Loss Function with a Simple Curve
In Figure 2, adding more to the weights reaches a low point and then starts to climb again. The slope of the line reveals the direction to that lowest point on the curve, which represents the lowest loss. When the slope is negative, add to the weights. When the slope is positive, subtract from the weights. The specific amount added or subtracted to the weights is known as the Learning Rate. Determining an ideal learning rate is as much an art as it is a science. Too large and the algorithm could overshoot the minimum. Too low and the training will take too long. This process is called Gradient Descent. Readers who are more familiar with the intricacies of calculus will see this process for what it is: determining the derivative of the Loss function.
Rarely, however, is the graph of a Loss function as simple as the one in Figure 2. In practice, there are many peaks and valleys. The challenge then becomes how to find the lowest of the low points (the global minimum) and not get fooled by low points nearby (local minima). The best approach in this situation is to pick a point along the curve at random and then proceed with the gradient descent process previously described, hence the term “Stochastic Gradient Descent.” For a great explanation of the mathematical concepts on this process, watch the YouTube video, “Gradient Descent, How Neural Networks Learn | Deep Learning, Chapter 2,” at youtu.be/IHZwWFHWa-w.
For the most part, this level of neural network architecture has been largely abstracted away by libraries such as Keras and TensorFlow. As in any software engineering endeavor, knowing the fundamentals always helps when faced with challenges in the field.
Putting Theory to Practice
In the previous column, I had created a neural network from scratch to process the MNIST digits. The resulting code base to bootstrap the problem was great at illustrating the inner workings of neural network architectures, but was impractical to bring forward. There exist so many frameworks and libraries now that perform the same task with less code.
To get started, open a new Jupyter notebook and enter the following into a blank cell and execute it to import all the required libraries:
import keras from keras.models import Sequential from keras.layers import Dense from keras.utils import to_categorical import matplotlib.pyplot as plt
Note that the output from this cell states that Keras is using a TensorFlow back end. Because the MNIST neural network example is so common, Keras includes it as part of its API, and even splits the data into a training set and a test set. Write the following code into a new cell and execute it to download the data and read it into the appropriate variables:
# import the data from keras.datasets import mnist # read the data (X_train, y_train), (X_test, y_test) = mnist.load_data()
Once the output indicates that the files are downloaded, use the following code to briefly examine the training and test dataset:
print(X_train.shape) print(X_test.shape)
The output should read that the x_train dataset has 60,000 items and the x_test dataset has 10,000 items. Both consist of a 28x28 matrix of pixels. To see a particular image from the MNIST data, use MatPlotLib to render an image with the following code:
plt.imshow(X_train[10])
The output should look like a handwritten “3.” To see what’s inside the testing dataset, enter the following code:
plt.imshow(X_test[10])
The output shows a zero. Feel free to experiment by changing the index number and the dataset to explore the image datasets.
Shaping the Data
As with any AI or data science project, the input data must be reshaped to fit the needs of the algorithms. The image data needs to be flattened into a one-dimensional vector. As each image is 28x28 pixels, the one-dimensional vector will be 1 by (28x28), or 1 by 784. Enter the following code into a new cell and execute (note that this will not produce output text):
num_pixels = X_train.shape[1] * X_train.shape[2] X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32') X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32')
Pixel values range from zero to 255. In order to use them, you’ll need to normalize them to values between zero and one. Use the following code to do that:
X_train = X_train / 255 X_test = X_test / 255
Then enter the following code to take a look at what the data looks like now:
X_train[0]
The output reveals an array of 784 values between zero and one.
The task of taking in various images of handwritten digits and determining what number they represent is classification. Before building the model, you’ll need to split the target variables into categories. In this case, you know that there are 10, but you can use the to_categorical function in Keras to determine that automatically. Enter the following code and execute it (the output should display 10):
y_train = to_categorical(y_train) y_test = to_categorical(y_test) num_classes = y_test.shape[1] print(num_classes)
Build, Train and Test the Neural Network
Now that the data has been shaped and prepared, it’s time to build out the neural networks using Keras. Enter the following code to create a function that creates a sequential neural network with three layers with an input layer of num_pixels (or 784) neurons:
def classification_model(): model = Sequential() model.add(Dense(num_pixels, activation='relu', input_shape=(num_pixels,))) model.add(Dense(100, activation='relu')) model.add(Dense(num_classes, activation='softmax')) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) return model
Compare this code to the code from my last column’s “from scratch” methods. You may notice new terms like “relu” or “softmax” referenced in the activation functions. Up until now, I’ve only explored the Sigmoid activation function, but there are several kinds of activation functions. For now, keep in mind that all activation functions compress an input value by outputting a value between 0 and 1 or -1 and 1.
With all of the infrastructure in place, it’s time to build, train and score the model. Enter the following code into a blank cell and execute it:
model = classification_model() model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, verbose=2) scores = model.evaluate(X_test, y_test, verbose=0)
As the neural network runs, note that the loss value drops with each iteration. Accordingly, the accuracy also improves. Also, take note of how long each epoch takes to execute. Once completed, enter the following code to see the accuracy and error percentages:
print('Model Accuracy: {} \n Error: {}'.format(scores[1], 1 - scores[1]))
The output reveals an accuracy of greater than 98 percent and an error of 1.97 percent.
Persisting the Model
Now that the model has been trained to a high degree of accuracy, you can save the model for future use to avoid having to train it again. Fortunately, Keras makes this easy. Enter the following code into a new cell and execute it:
model.save('MNIST_classification_model.h5')
This creates a binary file that’s about 8KB in size and contains the optimum values for weights and biases. Loading the model is also easy with Keras, like so:
from keras.models import load_model pretrained_model = load_model('MNIST_classification_model.h5')
This h5 file contains the model and can be deployed along with code to reshape and prepare the input image data. In other words, the lengthy process of training a model needs only to be done once. Referencing the predefined model doesn’t require the computationally expensive process of training and, in the final production system, the neural network can be implemented rapidly.
Wrapping Up
Neural networks can solve problems that have confounded traditional algorithms for decades. As we’ve seen, their simple structure hides their true complexity. Neural networks work by propagating forward inputs, weights and biases. However, it’s the reverse process of backpropagation where the network actually learns by determining the exact changes to make to weights and biases to produce an accurate result.
Learning, in the machine sense, is about minimizing the difference between the actual result and the correct result. This process is tedious and compute-expensive, as evidenced by the time it takes to run through one epoch. Fortunately, this training needs only to be done once and not each time the model is needed. Additionally, I explored using Keras to build out this neural network. While it is possible to write the code needed to build out neural networks from scratch, it’s far simpler to use existing libraries like Keras, which take care of the minute details for you. experts for reviewing this article: Andy Leonard
Discuss this article in the MSDN Magazine forum | https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/april/artificially-intelligent-how-do-neural-networks-learn | CC-MAIN-2020-05 | refinedweb | 2,204 | 54.32 |
Zero Friction Unit Testing for Visual Studio .NET
Syndicated from Kiwidude's Geek Spot.
Coverage exclusions are my personal favourite new feature. This offers a way for NCoverExplorer to automatically remove from the coverage tree items not relevant to your analysis when a coverage file is loaded - such as unit test fixtures, third party libraries etc. In the screenshot shown you can see the default exclusions I have included with NCoverExplorer - for instance any assemblies ending in ".Tests" will be excluded. You can add exclusions at the class, assembly and namespace level. I have also added support for the NCover 1.5.x feature of "exclusion attributes" if they exist in the coverage.xml file (although NCover still has some kinks to be worked out in a future release before you can rely on this feature)..
Themes came about as an answer to another much requested feature of more customisation of the GUI to include fonts and background colours. A "theme" is a group of settings covering most aspects of the appearance of the coverage tree, statistics pane and source code highlighting.
You can of course add your own themes as shown in the screenshots on this blog entry. Themes are easily toggled between using the new View->Themes menu.
Sorting and Coverage options came from a couple of user feature requests as shown here.!).
Thanks also to Jamie and others who have been kind enough to test the beta versions and provide invaluable feedback.
There are numerous other minor usability tweaks and enhancements I haven't mentioned here that you can read about in the release notes or discover for yourselves. I look forward to any feedback!
Download TestDriven.Net 2.0.1545 Combined Install
Download NCoverExplorer 1.3.2 binariesMirror Site
Release NotesFAQ
This release seems to crash if NUnit 2.6 is not installed, whereas the previous version seemed to work fine with NUnit 2.7. Did something change?
Hi Adam,
I haven't been able to repro this. Could you give me any more details?
Thanks, Jamie. | http://weblogs.asp.net/nunitaddin/archive/2006/03/15/440266.aspx | crawl-002 | refinedweb | 341 | 66.13 |
Hi, I wrote this code, but the last part I did it by trial and error and by seeing something similar. I don't understand how to print the number of occurrences. I did it, but I don't understand why I had to put " if (array[i] > 0) "
Code Java:
/*PP 8.1 Design and implement an application that reads an arbitrary number of integers that are in the range 0 to 50 inclusive and counts how many occurrences of each are entered. After all input has been processed, print all of the values (with the number of occurrences) that were entered one or more times. */ import java.util.*; public class arbArray { public static void main(String[]args) { final int FINAL=51; int[] array = new int[FINAL]; Scanner scan = new Scanner(System.in); for (int i = 0; i < array.length; i++) { System.out.println("Enter a number for location "+i+":"); int n = scan.nextInt(); while (n < 0 || n > 50) { System.out.println("Please enter a number between 0 and 50 for location "+i+" :"); n = scan.nextInt(); } array[n]++; } for (int i = 0; i < array.length; i++) { if (array[i] > 0) { System.out.println(i + ": " + array[i]); // Print the number of occurrences for the numbers entered. } } } } | http://www.javaprogrammingforums.com/%20object-oriented-programming/33418-java-array-printingthethread.html | CC-MAIN-2018-17 | refinedweb | 206 | 66.94 |
NAME
Start execution on a process.
SYNOPSIS
#include <zircon/syscalls.h> zx_status_t zx_process_start(zx_handle_t handle, zx_handle_t thread, zx_vaddr_t entry, zx_vaddr_t stack, zx_handle_t arg1, uintptr_t arg2);
DESCRIPTION
zx_process_start() is similar to
zx_thread_start(), but is used for the
purpose of starting the first thread in a process.
zx_process_start() causes a thread to begin execution at the program
counter specified by entry and with the stack pointer set to stack.
The arguments arg1 and arg2 are arranged to be in the architecture
specific registers used for the first two arguments of a function call
before the thread is started. All other registers are zero upon start.
The first argument (arg1) is a handle, which will be transferred from
the process of the caller to the process being started, and an
appropriate handle value will be placed in arg1 for the newly started
thread. If
zx_process_start() returns an error, arg1 is closed rather
than transferred to the process being started.
Alternatively, arg1 can be ZX_HANDLE_INVALID instead of a handle.
In this case the process starts with ZX_HANDLE_INVALID (i.e. zero)
in its first argument register instead of a handle. This means there
are no handles in the process and can never be any handles to any
objects shared outside the process.
zx_process_start() is the only
way to transfer a handle into a process that doesn't involve the process
making some system call using a handle it already has (arg1 is usually
the "bootstrap" handle). A process with no handles can make the few
system calls that don't require a handle, such as
zx_process_exit(),
if it's been provided with a vDSO mapping. It can create new kernel
objects with system calls that don't require a handle, such as
zx_vmo_create(), but there is no way to make use of those objects
without more handles and no way to transfer them outside the process.
Its only means of communication is via the memory mapped into its
address space by others.
RIGHTS
handle must be of type ZX_OBJ_TYPE_PROCESS and have ZX_RIGHT_WRITE.
thread must be of type ZX_OBJ_TYPE_THREAD and have ZX_RIGHT_WRITE.
arg1 must have ZX_RIGHT_TRANSFER.
RETURN VALUE
zx_process_start() returns ZX_OK on success.
In the event of failure, a negative error value is returned.
ERRORS
ZX_ERR_BAD_HANDLE process or thread or arg1 is not a valid handle.
ZX_ERR_WRONG_TYPE process is not a process handle or thread is not a thread handle.
ZX_ERR_ACCESS_DENIED The handle thread lacks ZX_RIGHT_WRITE or thread does not belong to process, or the handle process lacks ZX_RIGHT_WRITE or arg1 lacks ZX_RIGHT_TRANSFER.
ZX_ERR_BAD_STATE process is already running or has exited.
ZX_ERR_INVALID_ARGS entry is not a userspace address, is not a
canonical address, or is not
0. | https://fuchsia.dev/fuchsia-src/reference/syscalls/process_start | CC-MAIN-2021-31 | refinedweb | 441 | 62.98 |
Following our previous article of setting up Laravel and working with the view, today we will be looking at the C in MVC: Controllers. Let’s take a look first at exactly what the controller’s job is in the hierarchy of an application. Then, we will get some practice in setting up a controller, and how we can pass information from a controller to our view.
The Controller
We already saw the view, and we can see that it’s responsible for what the user actually sees and interacts with. The Controller’s job is to pass information between the view and the model. The model itself is responsible for the business logic, things like accessing and returning results from a database. This is the basic idea of how an MVC application or framework would work. Below, see a quick look at what this interaction might look like.
- User requests a category page – /stuff
- Route picks up /stuff and passes it to the Stuff Controller
- Controller initiates a stuff object which queries the database for the items in the category
- Stuff model object passes the info found back to controller to process
- Controller passes needed data to view
- View displays data to user and waits for new input
This is a pretty basic example of how a MVC application might work and what the controller’s purpose is in it. Let’s go ahead and set up a new controller now. Laravel Course provides some handy command line tools for doing this. You could always copy and paste the existing controller and rename it, but this way is much easier. Navigate to your Laravel project folder in your command line, then run the following command.
Php artisan make:controller TestController
You should now see a TestController.php file in your app/Http/controllers folder. It should look similar to this:
namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; class TestController extends Controller { }
Don’t worry about the namespace and “use” commands just yet, we’ll go over these when we look at models and when we integrate other parts of Laravel. The important thing to see is that our controller extends Laravel’s built in controller class. This allows us to use the basic functionality it provides; you’ll see this type of inheritance used throughout the entirety of the framework.
Right now the controller doesn’t do much, there’s no actual code to fire in it. Let’s fix that. Going back to our example above, why don’t we create a simple function to display a stuff page? To start we’ll create a public function that simply returns a view, much like the function passed in routes.php file in the earlier tutorial.
namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; class TestController extends Controller { public function showStuff() { Return view(‘stuff’); } }
Now we have that go ahead and make a stuff.php file and stick that into your views folder. If you need a refresher on how to do that, check out the getting started with Laravel tutorial, where we go over making views.
At this point, we now need a way to tell our route to fire the showStuff() function. If you navigate to the /show route now, you’ll get a route not found error, which makes sense since we never created one to handle it.
In our last example we passed a function to the route and were able to return the view through that. This time however, we’ll be passing the controller to the route to let it know what we want to use. The syntax for that is
So ours would be:
We pass this just like we did the function. Open up your routes.php file and add the following:
Route::get('stuff', '[email protected]' );
It really is that simple. This simply tells the route to fire the specific function in the controller. Easy!
This is great and all, but wouldn’t it be nice if we could pass some data back to the view, it is an important part of an application after all. Add to your controller:
namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; class TestController extends Controller { public function showStuff() { $value = “test”; Return view(‘stuff’); } }
We’ve now got a new value in our controller, but no way to access it. If we try to access the $value variable in the stuff.php file, you’ll get an undefined variable error. This makes sense since the value will fall out of scope once we access the function. To fix this we only need to add one little extra bit of code:
namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; class TestController extends Controller { public function showStuff() { $value = “test”; return view(‘stuff’)->with(‘value’, $value); } }
Now, we are telling the view to be returned but also to pass with it a variable named value with $value assigned to it. We could make a change like:
return view(‘stuff’)->with(‘stuffVariable’, $value);
Go back to your view and now try to access a variable $stuffVariable. You can name it whatever you like and it’s passed to the view. You can also do multiple withs if needed. That would look something like this:
return view(‘stuff’)->with(‘stuffVariable1’, $value)->with(‘stuffVariable2’, $value);
Now on the page you’ll have two different variables, $stuffVariable1 and $stuffVariable2, both with the same value. Not very interesting in this situation, but you can see how easy it would be to return the values of several database queries for interest.
There’s a lot more you can do with controllers, but this is more than enough to get you started. Practice setting up some new routes with controllers and experimenting with how they work. This is the basic building blocks of an MVC application and we’re well on our way to getting started building our first one. Next we’ll finish up with Models, and then finally begin working on our simple to do list application using Laravel. Stay tuned! | https://blog.eduonix.com/web-programming-tutorials/learn-about-the-controllers-in-laravel/ | CC-MAIN-2020-45 | refinedweb | 1,026 | 68.6 |
Synchronization Primitives
This chapter is not intended as an introduction to synchronization. It is assumed that you have some understanding of the basic concepts of locks and semaphores already. If you need additional background reading, synchronization is covered in most introductory operating systems texts. However, since synchronization in the kernel is somewhat different from locking in an application this chapter does provide a brief overview to help ease the transition, or for experienced kernel developers, to refresh your memory.
As an OS X kernel programmer, you have many choices of synchronization mechanisms at your disposal. The kernel itself provides two such mechanisms: locks and semaphores.
A lock is used for basic protection of shared resources. Multiple threads can attempt to acquire a lock, but only one thread can actually hold it at any given time (at least for traditional locks—more on this later). While that thread holds the lock, the other threads must wait. There are several different types of locks, differing mainly in what threads do while waiting to acquire them.
A semaphore is much like a lock, except that a finite number of threads can hold it simultaneously. Semaphores can be thought of as being much like piles of tokens. Multiple threads can take these tokens, but when there are none left, a thread must wait until another thread returns one. It is important to note that semaphores can be implemented in many different ways, so Mach semaphores may not behave in the same way as semaphores on other platforms.
In addition to locks and semaphores, certain low-level synchronization primitives like test and set are also available, along with a number of other atomic operations. These additional operations are described in
libkern/gen/OSAtomicOperations.c in the kernel sources. Such atomic operations may be helpful if you do not need something as robust as a full-fledged lock or semaphore. Since they are not general synchronization mechanisms, however, they are beyond the scope of this chapter.
Semaphores
Semaphores and locks are similar, except that with semaphores, more than one thread can be doing a given operation at once. Semaphores are commonly used when protecting multiple indistinct resources. For example, you might use a semaphore to prevent a queue from overflowing its bounds.
OS X uses traditional counting semaphores rather than binary semaphores (which are essentially locks). Mach semaphores obey Mesa semantics—that is, when a thread is awakened by a semaphore becoming available, it is not executed immediately. This presents the potential for starvation in multiprocessor situations when the system is under low overall load because other threads could keep downing the semaphore before the just-woken thread gets a chance to run. This is something that you should consider carefully when writing applications with semaphores.
Semaphores can be used any place where mutexes can occur. This precludes their use in interrupt handlers or within the context of the scheduler, and makes it strongly discouraged in the VM system. The public API for semaphores is divided between the MIG–generated
task.h file (located in your build output directory, included with
#include <mach/task.h>) and
osfmk/mach/semaphore.h (
included with #include <mach/semaphore.h>).
The public semaphore API includes the following functions:
which are described in
<mach/semaphore.h> or
xnu/osfmk/mach/semaphore.h (except for create and destroy, which are described in
<mach/task.h>.
The use of these functions is relatively straightforward with the exception of the
semaphore_create,
semaphore_destroy, and
semaphore_signal_thread calls.
The
value and
semaphore parameters for
semaphore_create are exactly what you would expect—a pointer to the semaphore structure to be filled out and the initial value for the semaphore, respectively.
The
task parameter refers to the primary Mach task that will “own” the lock. This task should be the one that is ultimately responsible for the subsequent destruction of the semaphore. The
task parameter used when calling
semaphore_destroy must match the one used when it was created.
For communication within the kernel, the
task parameter should be the result of a call to
current_task. For synchronization with a user process, you need to determine the underlying Mach task for that process by calling
current_task on the kernel side and
mach_task_self on the application side.
The
policy parameter is passed as the policy for the wait queue contained within the semaphore. The possible values are defined in
osfmk/mach/sync_policy.h. Current possible values are:
The FIFO policy is, as the name suggests, first-in-first-out. The fixed priority policy causes wait queue reordering based on fixed thread priority policies. The prepost policy causes the
semaphore_signal function to not increment the counter if no threads are waiting on the queue. This policy is needed for creating condition variables (where a thread is expected to always wait until signalled). See the section Wait Queues and Wait Primitives for more information.
The
semaphore_signal_thread call takes a particular thread from the wait queue and places it back into one of the scheduler’s wait-queues, thus making that thread available to be scheduled for execution. If
thread_act is
NULL, the first thread in the queue is similarly made runnable.
With the exception of
semaphore_create and
semaphore_destroy, these functions can also be called from user space via RPC. See Calling RPC From User Applications for more information.
Condition Variables
The BSD portion of OS X provides
msleep,
wakeup, and
wakeup_one, which are equivalent to condition variables with the addition of an optional time-out. You can find these functions in
sys/proc.h in the Kernel framework headers.
The
msleep call is similar to a condition variable. It puts a thread to sleep until
wakeup or
wakeup_one is called on that channel. Unlike a condition variable, however, you can set a timeout measured in clock ticks. This means that it is both a synchronization call and a delay. The prototypes follow:
The three sleep calls are similar except in the mechanism used for timeouts. The function
msleep0 is not recommended for general use.
In these functions,
channel is a unique identifier representing a single condition upon which you are waiting. Normally, when
msleep is used, you are waiting for a change to occur in a data structure. In such cases, it is common to use the address of that data structure as the value for
channel, as this ensures that no code elsewhere in the system will be using the same value.
The
priority argument has three effects. First, when
wakeup is called, threads are inserted in the scheduling queue at this priority. Second, if the bit
(priority & PCATCH) is set,
msleep0 does not allow signals to interrupt the sleep. Third, if the bit
(priority & PDROP) is zero,
msleep0 drops the mutex on sleep and reacquires it upon waking. If
(priority & PDROP) is one,
msleep0 drops the mutex if it has to sleep, but does not reacquire it.
The
subsystem argument is a short text string that represents the subsystem that is waiting on this channel. This is used solely for debugging purposes.
The
timeout argument is used to set a maximum wait time. The thread may wake sooner, however, if
wakeup or
wakeup_one is called on the appropriate channel. It may also wake sooner if a signal is received, depending on the value of
priority. In the case of
msleep0, this is given as a mach abstime deadline. In the case of
msleep, this is given in relative time (seconds and nanoseconds).
Outside the BSD portion of the kernel, condition variables may be implemented using semaphores.
Locks
OS X (and Mach in general) has three basic types of locks: spinlocks, mutexes, and read-write locks. Each of these has different uses and different problems. There are also many other types of locks that are not implemented in OS X, such as spin-sleep locks, some of which may be useful to implement for performance comparison purposes.
Spinlocks
A spinlock is the simplest type of lock. In a system with a test-and-set instruction or the equivalent, the code looks something like this:
In other words, until the lock is available, it simply “spins” in a tight loop that keeps checking the lock until the thread’s time quantum expires and the next thread begins to execute. Since the entire time quantum for the first thread must complete before the next thread can execute and (possibly) release the lock, a spinlock is very wasteful of CPU time, and should be used only in places where a mutex cannot be used, such as in a hardware exception handler or low-level interrupt handler.
Note that a thread may not block while holding a spinlock, because that could cause deadlock. Further, preemption is disabled on a given processor while a spinlock is held.
There are three basic types of spinlocks available in OS X:
lck_spin_t (which supersedes
simple_lock_t),
usimple_lock_t, and
hw_lock_t. You are strongly encouraged to not use
hw_lock_t; it is only mentioned for the sake of completeness. Of these, only
lck_spin_t is accessible from kernel extensions.
The
u in
usimple stands for uniprocessor, because they are the only spinlocks that provide actual locking on uniprocessor systems. Traditional simple locks, by contrast, disable preemption but do not spin on uniprocessor systems. Note that in most contexts, it is not useful to spin on a uniprocessor system, and thus you usually only need simple locks. Use of usimple locks is permissible for synchronization between thread context and interrupt context or between a uniprocessor and an intelligent device. However, in most cases, a mutex is a better choice.
The spinlock functions accessible to kernel extensions consist of the following:
Prototypes for these locks can be found in
<kern/locks.h>.
The arguments to these functions are described in detail in Using Lock Functions.
Mutexes
A mutex, mutex lock, or sleep lock, is similar to a spinlock, except that instead of constantly polling, it places itself on a queue of threads waiting for the lock, then yields the remainder of its time quantum. It does not execute again until the thread holding the lock wakes it (or in some user space variations, until an asynchronous signal arrives).
Mutexes are more efficient than spinlocks for most purposes. However, they are less efficient in multiprocessing environments where the expected lock-holding time is relatively short. If the average time is relatively short but occasionally long, spin/sleep locks may be a better choice. Although OS X does not support spin/sleep locks in the kernel, they can be easily implemented on top of existing locking primitives. If your code performance improves as a result of using such locks, however, you should probably look for ways to restructure your code, such as using more than one lock or moving to read-write locks, depending on the nature of the code in question. See Spin/Sleep Locks for more information.
Because mutexes are based on blocking, they can only be used in places where blocking is allowed. For this reason, mutexes cannot be used in the context of interrupt handlers. Interrupt handlers are not allowed to block because interrupts are disabled for the duration of an interrupt handler, and thus, if an interrupt handler blocked, it would prevent the scheduler from receiving timer interrupts, which would prevent any other thread from executing, resulting in deadlock.
For a similar reason, it is not reasonable to block within the scheduler. Also, blocking within the VM system can easily lead to deadlock if the lock you are waiting for is held by a task that is paged out.
However, unlike simple locks, it is permissible to block while holding a mutex. This would occur, for example, if you took one lock, then tried to take another, but the second lock was being held by another thread. However, this is generally not recommended unless you carefully scrutinize all uses of that mutex for possible circular waits, as it can result in deadlock. You can avoid this by always taking locks in a certain order.
In general, blocking while holding a mutex specific to your code is fine as long as you wrote your code correctly, but blocking while holding a more global mutex is probably not, since you may not be able to guarantee that other developers’ code obeys the same ordering rules.
A Mach mutex is of type
mutex_t. The functions that operate on mutexes include:
as described in
<kern/locks.h>.
The arguments to these functions are described in detail in Using Lock Functions.
Read-Write Locks
Read-write locks (also called shared-exclusive locks) are somewhat different from traditional locks in that they are not always exclusive locks. A read-write lock is useful when shared data can be reasonably read concurrently by multiple threads except while a thread is modifying the data. Read-write locks can dramatically improve performance if the majority of operations on the shared data are in the form of reads (since it allows concurrency), while having negligible impact in the case of multiple writes.
A read-write lock allows this sharing by enforcing the following constraints:
Multiple readers can hold the lock at any time.
Only one writer can hold the lock at any given time.
A writer must block until all readers have released the lock before obtaining the lock for writing.
Readers arriving while a writer is waiting to acquire the lock will block until after the writer has obtained and released the lock.
The first constraint allows read sharing. The second constraint prevents write sharing. The third prevents read-write sharing, and the fourth prevents starvation of the writer by a steady stream of incoming readers.
Mach read-write locks also provide the ability for a reader to become a writer and vice-versa. In locking terminology, an upgrade is when a reader becomes a writer, and a downgrade is when a writer becomes a reader. To prevent deadlock, some additional constraints must be added for upgrades and downgrades:
Upgrades are favored over writers.
The second and subsequent concurrent upgrades will fail, causing that thread’s read lock to be released.
The first constraint is necessary because the reader requesting an upgrade is holding a read lock, and the writer would not be able to obtain a write lock until the reader releases its read lock. In this case, the reader and writer would wait for each other forever. The second constraint is necessary to prevent the deadlock that would occur if two readers wait for the other to release its read lock so that an upgrade can occur.
The functions that operate on read-write locks are:
This is a more complex interface than that of the other locking mechanisms, and actually is the interface upon which the other locks are built.
The functions
lck_rw_lock and
lck_rw_unlock lock and unlock a lock as either shared (read) or exclusive (write), depending on the value of
lck_rw_type., which can contain either
LCK_RW_TYPE_SHARED or
LCK_RW_TYPE_EXCLUSIVE. You should always be careful when using these functions, as unlocking a lock held in shared mode using an exclusive call or vice-versa will lead to undefined results.
The arguments to these functions are described in detail in Using Lock Functions.
Spin/Sleep Locks
Spin/sleep locks are not implemented in the OS X kernel. However, they can be easily implemented on top of existing locks if desired.
For short waits on multiprocessor systems, the amount of time spent in the context switch can be greater than the amount of time spent spinning. When the time spent spinning while waiting for the lock becomes greater than the context switch overhead, however, mutexes become more efficient. For this reason, if there is a large degree of variation in wait time on a highly contended lock, spin/sleep locks may be more efficient than traditional spinlocks or mutexes.
Ideally, a program should be written in such a way that the time spent holding a lock is always about the same, and the choice of locking is clear. However, in some cases, this is not practical for a highly contended lock. In those cases, you may consider using spin/sleep locks.
The basic principle of spin/sleep locks is simple. A thread takes the lock if it is available. If the lock is not available, the thread may enter a spin cycle. After a certain period of time (usually a fraction of a time quantum or a small number of time quanta), the spin routine’s time-out is reached, and it returns failure. At that point, the lock places the waiting thread on a queue and puts it to sleep.
In other variations on this design, spin/sleep locks determine whether to spin or sleep according to whether the lock-holding thread is currently on another processor (or is about to be).
For short wait periods on multiprocessor computers, the spin/sleep lock is more efficient than a mutex, and roughly as efficient as a standard spinlock. For longer wait periods, the spin/sleep lock is significantly more efficient than the spinlock and only slightly less efficient than a mutex. There is a period near the transition between spinning and sleeping in which the spin/sleep lock may behave significantly worse than either of the basic lock types, however. Thus, spin/sleep locks should not be used unless a lock is heavily contended and has widely varying hold times. When possible, you should rewrite the code to avoid such designs.
Using Lock Functions
While most of the locking functions are straightforward, there are a few details related to allocating, deallocating, and sleeping on locks that require additional explanation. As the syntax of these functions is identical across all of the lock types, this section explains only the usage for spinlocks. Extending this to other lock types is left as a (trivial) exercise for the reader.
The first thing you must do when allocating locks is to allocate a lock group and a lock attribute set. Lock groups are used to name locks for debugging purposes and to group locks by function for general understandability. Lock attribute sets allow you to set flags that alter the behavior of a lock.
The following code illustrates how to allocate an attribute structure and a lock group structure for a lock. In this case, a spinlock is used, but with the exception of the lock allocation itself, the process is the same for other lock types.
Listing 17-1 Allocating lock attributes and groups (lifted liberally from kern_time.c)
The first argument to the lock initializer, of type
lck_grp_t, is a lock group. This is used for debugging purposes, including lock contention profiling. The details of lock tracing are beyond the scope of this document, however, every lock must belong to a group (even if that group contains only one lock).
The second argument to the lock initializer, of type
lck_attr_t, contains attributes for the lock. Currently, the only attribute available is lock debugging. This attribute can be set using
lck_attr_setdebug and cleared with
lck_attr_setdefault.
To dispose of a lock, you simply call the matching free functions. For example:
The other two interesting functions are
lck_spin_sleep and
lck_spin_sleep_deadline. These functions release a spinlock and sleep until an event occurs, then wake. The latter includes a timeout, at which point it will wake even if the event has not occurred.
The parameter
lck_sleep_action controls whether the lock will be reclaimed after sleeping prior to this function returning. The valid options are:
LCK_SLEEP_DEFAULT
Release the lock while waiting for the event, then reclaim it. Read-write locks are held in the same mode as they were originally held.
LCK_SLEEP_UNLOCK
Release the lock and return with the lock unheld.
LCK_SLEEP_SHARED
Reclaim the lock in shared mode (read-write locks only).
LCK_SLEEP_EXCLUSIVE
Reclaim the lock in exclusive mode (read-write locks only).
The
event parameter can be any arbitrary integer, but it must be unique across the system. To ensure uniqueness, a common programming practice is to use the address of a global variable (often the one containing a lock) as the event value. For more information on these events, see Event and Timer Waits.
The parameter
interruptible indicates whether the scheduler should allow the wait to be interrupted by asynchronous signals. If this is false, any false wakes will result in the process going immediately back to sleep (with the exception of a timer expiration signal, which will still wake
lck_spin_sleep_deadline).
Copyright © 2002, 2013 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2013-08-08 | https://developer.apple.com/library/content/documentation/Darwin/Conceptual/KernelProgramming/synchronization/synchronization.html | CC-MAIN-2017-43 | refinedweb | 3,420 | 53.71 |
What's New in Offline Files for Windows Vista
Based on customer feedback, the Offline Files feature has been redesigned for Windows Vista®, and it utilizes many of the improvement available in this version of the Windows operating system.
This document describes some of the functionalities of and changes to Offline Files in Windows Vista. It is intended for general users of Offline Files and system administrators.
What does Offline Files do?
Before the introduction of Offline Files, Windows users could access files available on a shared network resource only when connected to the network. By using Offline Files, Windows users can access files that are available on a shared network resource and continue to work with network files when the computer is not connected to the network.
Offline Files maintains a local cache of remote files and folders on your computer, so that they are available to you when you are working offline. You continue to access these files in the same way that you accessed them when you were online because the shared network resource paths and namespaces are preserved.
When your network connection is restored, any changes that you made while working offline are updated to the network by default. If you and someone else on the network have made changes to the same file, you have the option of saving your version of the file to the network, the other user's version, or both.
In Offline Files in Windows XP, modes of operation affect an entire network server or domain-based Distributed File System (DFS) namespace. In Windows Vista, modes of operation apply to individual DFS scopes and individual Server Message Block (SMB) shared folders.
A DFS scope is defined as a folder in a domain-based DFS namespace that corresponds to a DFS link. If a network error is detected when connecting to a folder or a file in a domain-based DFS namespace, Offline Files in Windows Vista will not bring the whole domain offline (as it does in Windows XP). It will bring offline only the DFS link that includes the folder or file that had the error.
Consider the scenario of the following domain-based DFS namespace:
\\DFSdomain\folder1\folder2\folder3\folder4\file1
Assume that the namespace has the following configuration:
- Folder2 is a DFS link to: \\server1\folder2
- Folder4 is a DFS link to: \\server2\folder4
If there is a network error connecting to file1, only folder4 and file1 will be brought offline. The rest of the DFS namespace remains online. If there is a network error connecting to folder2 or folder3, these two folders are brought offline, but folder4 and file1 remain online.
Online mode
When Offline Files determines that there has been a network error during a file operation (browse, open, create, read, or write), it automatically transitions the SMB shared folder or DFS scope where the error occurred to auto offline mode.
In auto offline mode, all open, create, read, and write requests are satisfied from the local cache. There are certain operations that you cannot perform while in this mode—for example, changes to the namespace (changing the name of or deleting a folder) or accessing the previous version of a file. However, you can create new folders, continue to browse the part of the namespace that is available to you offline, and also see that part of the namespace for which you only have placeholders. For a detailed explanation about how this works in Offline Files for Windows Vista, see "Consistent namespaces" in this document.
While in auto offline mode, Offline Files will attempt to reconnect every two minutes by default. When a network connection is available, Offline Files automatically transitions to online mode. For more details about what happens during a transition to online mode, see "Seamless offline to online transition" in this document.
When you are in auto offline mode, the details pane in Windows Explorer shows Offline status: Offline (not connected).
Manual offline mode
While working in online mode, you can force a transition to offline mode by clicking Work offline on the Windows Explorer Command Bar.
This change in operation mode affects only the SMB shared resource or DFS scope that you are currently browsing in Windows Explorer. Other SMB shared resources and DFS scopes will continue to be online. This mode of operation persists even after you restart your computer.
Access to files and folders in manual offline mode is the same as in auto offline mode. The difference between these two offline modes is that in manual offline mode, you can initiate a synchronization process for a folder or file at any time. (In auto offline mode, you do not have this option because a network connection is not available.) After the synchronization process has completed, the file or folder continues to be available offline.
If you have an open file in the SMB shared resources or DFS scope that has not yet been copied to the local cache, a warning message appears when you force that shared resource or scope into manual offline mode. You have the following options:
- Close the open file before transitioning to offline mode
- Ignore the warning
- Choose to not go offline
If you ignore the warning and continue with the transition to offline mode, any unsaved changes to the files that have not been cached may be lost.
While in manual offline mode, you can return to online mode by clicking Work online on the Windows Explorer Command Bar. For more details about what happens during a transition to online mode, see "Seamless offline to online transition" in this document.
When you are in manual offline mode, the details pane in Windows Explorer shows Offline status: Offline (working offline).
Slow-link mode
If the Configure slow-link mode Group Policy setting has been enabled by the domain administrator, an SMB shared resource or DFS scope can automatically be transitioned to slow-link mode. This happens if you are working in online mode and the performance of your connection to that SMB shared resource or DFS scope is determined to be low. For a detailed explanation about how slow-link mode works in Offline Files for Windows Vista, see "Improved slow-link mode" in this document.
When you are in slow-link mode, the details pane in Windows Explorer shows Offline status: Offline (slow connection). transition from offline mode to online mode in Windows Vista is non-disruptive for the user. Unlike previous versions, you do not need to close applications or manually start the synchronization process.
When Offline Files in Windows Vista detects that an SMB shared resource or a DFS scope is available for reconnection, that share or scope is seamlessly transitioned to online mode. The transition to online mode of an SMB shared resource or DFS scope works as follows:
-
Optimized file synchronization
One of the performance enhancements of Offline Files in Windows Vista is a faster synchronization process. This is achieved by using a new synchronization algorithm that does the following:
- Reduces the time and bandwidth needed to identify differences between the local cache and the server
- Determines which parts of a file in the local cache have changed, and then updates only those parts of the file on the network server
The process of updating only parts of a file on the server is called Bitmap Differential Transfer. It takes place during synchronization of the local cache to the server.
Bitmap Differential Transfer
Offline Files in Windows Vista uses Bitmap Differential Transfer. Bitmap Differential Transfer tracks which blocks of a file in the local cache are modified while you are working offline and then sends only those blocks to the server. In Windows XP, Offline Files copies the entire file from the local cache to the server, even if only a small part of the file was modified while offline.
Because Bitmap Differential Transfer can make the synchronization more efficient, Offline Files in Windows Vista supports all file types. Offline Files in Windows XP could not synchronize large files efficiently; therefore, certain types of files were specifically excluded from the local cache.
Improved slow-link mode
Offline Files in Windows Vista incorporates a slow-link mode of operation to improve the experience for mobile and traveling users who connect to the corporate network with low-throughput connections. This mode of operation can also improve the experience for users who connect to servers located in remote locations where network latency is high.
Performance of a network connection is automatically determined by measuring throughput and packet latency between the client computer and the server that hosts an SMB shared resource or a DFS scope. When low performance is detected, the SMB shared resource or DFS scope is automatically transitioned to slow-link mode.
When you are in slow-link mode, all read and write requests are satisfied from the local cache. You can manually initiate a synchronization process at any time by clicking Sync on the Windows Explorer Command Bar, or by using Sync Center. After the synchronization process has completed, you continue to work in slow-link mode.
In this mode, all read and write requests are satisfied from the local cache, so Offline Files cannot determine the performance of the network connection. The only way to return to online mode is to manually make this transition. To do this, click Work online on the Windows Explorer Command Bar. After you have transitioned to online mode, Offline Files will reassess the performance of the network connection every five minutes (default setting). If network performance continues to be low, you will automatically be transitioned back to slow-link mode.
Enabling slow-link mode
The slow-link mode of operation is not enabled by default. The domain administrator must enable the Configure slow-link mode Group Policy setting. If this policy setting is disabled or has not been configured, Offline Files will not transition an SMB shared resource or DFS scope to slow-link mode.
The performance of a network connection is determined by measuring throughput and packet latency between the client computer and the server that hosts the SMB shared resource or DFS scope. You can configure the threshold values for minimum throughput and maximum packet latency in the Configure slow-link mode Group Policy setting. For more details about this and other new Group Policy settings available for Offline Files in Windows Vista, see "Group policy settings added or changed for Offline Files in Windows Vista" in this document.
Users can configure how often Offline Files will determine network performance after a manual transition to online mode. To configure the computer, in Control Panel, click Network and Internet, and then click Offline Files. On the Network tab, specify a number of minutes. The default setting is to check network performance every five minutes.
Consistent namespaces
In Windows XP, after transitioning to offline mode, only files that have been selected to be made available offline, or have been cached automatically, remain visible to the user. For example, if a folder has ten files and only three are selected to be made available offline, when you are in offline mode, the folder will appear to only contain those three files. The other seven files are not visible until you return to online mode. This can cause confusion and an inconsistent experience between online and offline modes.
To provide a consistent experience in online and offline modes, Offline Files in Windows Vista creates a placeholder for files and folders that are not available offline. The placeholder appears as a fainter image of the file or folder, and it indicates to the user that a file or folder exists in the shared folder, but it is not currently available offline.
When a file in a shared folder is selected to be made available offline, placeholders are created for the other files and folders that are contained in the parent folder but not in any subfolders. As in the previous example, if you have selected three files to be made available offline, and the folder where those files reside contains another seven files. When you transition offline, you will see all ten files. The three files that you selected to be made available offline will look like normal files, and the other seven files will have an icon overlay that identifies them as placeholder files.
The following figure shows a folder with three files that have been made available offline, and seven files and one subfolder for which placeholders have been created.
If you try to open a placeholder, an error message alerts you that the file is not currently available.
Another instance where placeholders are created is when you access a file in a shared folder that has the automatic caching option enabled. Because the file you accessed will be made automatically available on your computer offline, Offline Files creates placeholders for all files and subfolders that are in the same folder.
Caching
When you create a shared folder on a server, there are three caching options available for that folder:
- Manual caching (default). If you want a file in the shared folder to be available on your computer when you are offline, you must manually select it to be made available offline.
- Automatic caching. When this option is selected, every time you access a file in a shared folder, the file will be made temporarily available on your computer offline.
- No caching. Files in the shared folder cannot be made available offline.
Specific files can also be selected to be cached automatically by using the Administratively assigned offline files Group Policy setting.
Cache size management
In Windows XP, there was no limit to the amount of disk space used by files that were cached manually. The only limit that could be specified was the amount of disk space occupied by files that were cached automatically.
With Offline Files in Windows Vista, you can specify a limit for the total size of the local cache. This limit includes automatically cached files and manually cached files. There is also a limit (within the total local cache size limit) for the amount of disk space used by automatically cached files.
For example, you can specify that the total cache size-limit for storing offline files on your computer is 5 gigabytes (GB), and within that limit, only 2 GB can be used to store files that are cached automatically. With this limit, files that were cached automatically are removed on a least-recently used basis as the disk space used by this type of files approaches the limit you specify.
Files that were cached manually are never removed from the local cache. When the total local cache size limit is reached and all files that were cached automatically have already been removed, you can not make files available offline until you specify a new limit or delete files from the local cache by using the Offline Files control panel item
These two local cache size limits can be specified in the Disk Usage tab of the Offline Files control panel item or with a Group Policy setting.
Per-user encryption
Offline Files in Windows XP offers the ability to encrypt your local cache, but the encryption can only occur within the context of the local system. Offline Files in Windows Vista offers enhanced security by encrypting each file in the local cache by using each user's local certificate.
This enhanced encryption not only protects all files in the local cache from unauthorized access (for example, if a laptop is lost or stolen), but it prevents cached files from becoming accessible to other users of the same computer.
Because the local cache is per computer and not per user, there is only one copy of each file stored in the local cache. When the cache is encrypted, the first user who selects a file to be made available offline is the only user who will have access to that file when working offline. Other users will be able to access that file only when working online.
Encryption of offline files can be enabled manually by using either of the following features:
- The Offline Files control panel item
- The Encrypt the Offline Files cache Group Policy setting
When a user manually enables encryption of the local cache, only those files in the cache to which the user has access are encrypted. If there are files in the local cache that the user does not have access to, those files are only encrypted when a user who has access to those files logs on to that computer.
When encryption is enabled by using the Encrypt the Offline Files cache Group Policy setting, the encryption process begins the next time a user logs on to the computer. As with manually-enabled encryption, only those files that a user has access to are encrypted.
The encryption process of a local cache that already contains files can take some time to complete. Newly cached files are immediately encrypted, while the encryption process of the existing files keeps running in the background. You can check the status of the encryption process at any time by using the Offline Files control panel item.
The following screenshots show several of the features that are available in the user interface for Offline Files in Windows Vista. To access Offline Files, in Control Panel, click Network and Internet, and then click Offline Files. To access Indexing Options, in Control Panel, click System and Maintenance, and then click Indexing Options.
Figure 2 shows Always Available Offline and Sync, the menu items available when Offline Files is enabled and you right-click a file or folder. A check mark is present on the menu when the selected file is available offline.
Figure 3 shows the file icon overlays that tell the user which files are available and unavailable offline. Auto-cached files do not show the overlays. This figure also shows the Sync and Work Offline Command Bar buttons. These buttons are available only when Offline Files is enabled or when the files in the folder being viewed have been cached.
Figure 4 shows the two optional columns for Offline Files in Windows Explorer: Offline availability and Offline status. In the Windows Explorer Details view, you can make these columns available by right-clicking the column heading area and then selecting the columns.
Figure 5 shows the new Offline Files tab, which is accessed by right-clicking a file or folder that is available offline, and then clicking Properties. From this location, you can specify that a file or folder is always available offline, and you can manually synchronize your local copy with the version on the network..
Figure 8 shows the General tab in Offline Files. You can use the options on this tab to perform general management tasks including enabling or disabling Offline Files; opening Sync Center; and viewing any SMB shared folders, mapped network drives, or other files or folders that are available offline.
Figure 9 shows the Disk Usage tab in Offline Files. You can use this tab to view the total disk spaced that is being used by Offline Files and the space that is available to cache more files or folders in the Offline Files cache. You can also set the limits for the amount of disk space that can be used by automatically cached files and all offline files. You can use this UI to delete automatically cached files from the local cache of Offline Files. | https://technet.microsoft.com/library/cc749449.aspx | CC-MAIN-2015-22 | refinedweb | 3,255 | 56.08 |
MATLAB Speaks Python
MATLAB is a great computing environment for engineers and scientists. MATLAB also provides access to general-purpose languages including C/C++, Java, Fortran, .NET, and Python. Today's guest blogger, Toshi Takeuchi, would like to talk about using MATLAB with Python.
Contents
- Why Not Use Both?
- Setting up Python in MATLAB
- Karate Club Dataset
- To Import or Not to Import
- Extracting Data from a Python Object
- Handling a Python List and Tuple
- Handling a Python Dict
- Visualizing the Graph in MATLAB
- Passing Data from MATLAB to Python
- Community Detection with NetworkX
- Streamlining the Code
- Summary
Why Not Use Both?
When we discuss languages, we often encounter a false choice where you feel you must choose one or the other. In reality, you can often use both. Most of us don't work alone. As part of a larger team, your work is often part of a larger workflow that involves multiple languages. That's why MATLAB provides interoperability with other languages including Python. Your colleagues may want to take advantage of your MATLAB code, or you need to access Python-based functionality from your IT systems. MATLAB supports your workflow in both directions.
Today I would like to focus on calling Python from MATLAB to take advantage of some existing Python functionality within a MATLAB-based workflow.
In this post, we will see:
- How to import data from Python into MATLAB
- How to pass data from MATLAB to Python
- How to use a Python package in MATLAB
Setting up Python in MATLAB
MATLAB supports Python 2.7, 3.6 and 3.7 as of this writing (R2019b). And here's another useful link.
I assume you already know how to install and manage Python environments and dependencies on your platform of choice, and I will not discuss it here because it is a complicated topic of its own.
Let's enable access to Python in MATLAB. You need to find the full path to your Python executable. Here is an example for Windows. On Mac and Linux, your operating system command may be different.
pe = pyenv; if pe.Status == "NotLoaded" [~,exepath] = system("where python"); pe = pyenv('Version',exepath); end
If that doesn't work, you can also just pass the path to your Python executable as string.
pe = pyenv('Version','C:\Users\username\AppData\Local\your\python\path\python.exe')
myPythonVersion = pe.Version py.print("Hello, Python!")
myPythonVersion = "3.7" Hello, Python!
Karate Club Dataset
Wayne Zachary published a dataset that contains a social network of friendships between 34 members of a karate club at a US university in the 1970s. A dispute that erupted in this club eventually caused it to break up into two factions. We want to see if we can algorithmically predict how the club would break up based on its interpersonal relationships.
This dataset is included in NetworkX, a complex networks package for Python. We can easily get started by importing the dataset using this package.
I am using NetworkX 2.2. To check the package version in Python, you would typically use the version package attribute like this:
>>> networkx.__version__
MATLAB doesn't support class names or other identifiers starting with an underscore(_) character. Instead, use the following to get the help content on the package, including its current version.
> py.help('networkx')
To Import or Not to Import
Typically, you do this at the start of your Python script.
import networkx as nx G = nx.karate_club_graph()
However, this is not recommended in MATLAB because the behavior of the import function in MATLAB is different from Python's.
The MATLAB way to call Python is to use py, followed by a package or method like this:
nxG = py.networkx.karate_club_graph();
If you must use import, you can do it as follows:
import py.networkx.* nxG = karate_club_graph();
As you can see, it is hard to remember that we are calling a Python method when you omit py, which can be confusing when you start mixing MATLAB code and Python code within the same script.
Extracting Data from a Python Object
The following returns the karate club dataset in a NetworkX graph object.
myDataType = class(nxG)
myDataType = 'py.networkx.classes.graph.Graph'
You can see the methods available on this object like this:
methods(nxG)
You can also see the properties of this object.
properties(nxG)
A NetworkX graph contains an edges property that returns an object called EdgeView.
edgeL = nxG.edges; myDataType = class(edgeL)
myDataType = 'py.networkx.classes.reportviews.EdgeView'
To use this Python object in MATLAB, the first step is to convert the object into a core Python data type such as a Python list.
edgeL = py.list(edgeL); myDataType = class(edgeL)
myDataType = 'py.list'
Now edgeL contains a Python list of node pairs stored as Python tuple elements. Each node pair represents an edge in the graph. Let's see the first 5 tuple values.
listContent = edgeL(1:5)
listContent = Python list with no properties. [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
Handling a Python List and Tuple
The Python way for handling a list or tuple typically looks like this, where you process individual elements in a loop.
for i in l: print i # l is the list for u, v in t: print((u, v)) # t is the tuple
The MATLAB way is to use arrays instead. The Python list can be converted into a cell array.
edgeC = cell(edgeL); myDataType = class(edgeC)
myDataType = 'cell'
This cell array contains Python tuple elements.
myDataType = class(edgeC{1})
myDataType = 'py.tuple'
The Python tuple can also be converted to a cell array. To convert the inner tuple elements, we can use cellfun.
edgeC = cellfun(@cell, edgeC, 'UniformOutput', false); myDataType = class(edgeC{1})
myDataType = 'cell'
The resulting nested cell array contains Python int values.
myDataType = class(edgeC{1}{1})
myDataType = 'py.int'
Handling a Python Dict
Now let's also extract the nodes from the dataset. We can follow the same steps as we did for the edges.
nodeL = py.list(nxG.nodes.data); nodeC = cell(nodeL); nodeC = cellfun(@cell, nodeC, 'UniformOutput', false);
An inner cell array contains both Python int and dict elements.
cellContent = nodeC{1}
cellContent = 1×2 cell array {1×1 py.int} {1×1 py.dict}
Python dict is a data type based on key-value pairs. In this case, the key is 'club' and the value is 'Mr. Hi'.
cellContent = nodeC{1}{2}
cellContent = Python dict with no properties. {'club': 'Mr. Hi'}
Mr. Hi was a karate instructor at the club. The other value in the Python dict is 'Officer', and the officer was a leader of the club. They were the key individuals of the respective factions. The node attribute indicates which faction an individual node belongs to. In this case, Node 1 belonged to Mr. Hi's faction.
The Python way for handling a dict typically looks like this, where you process individual elements in a loop.
for k, v in d.items(): print (k, v)
Again, the MATLAB way is to use an array. The Python dict can be converted to a struct array.
nodeAttrs = cellfun(@(x) struct(x{2}), nodeC); myDataType = class(nodeAttrs)
myDataType = 'struct'
We can extract the individual values into a string array. The club was evidently evenly divided between the factions.
nodeAttrs = arrayfun(@(x) string(x.club), nodeAttrs); tabulate(nodeAttrs)
Value Count Percent Mr. Hi 17 50.00% Officer 17 50.00%
Let's extract the nodes that belong to Mr. Hi's faction.
group_hi = 1:length(nodeAttrs); group_hi = group_hi(nodeAttrs == 'Mr. Hi');
Visualizing the Graph in MATLAB
MATLAB also provides graph and network capabilities and we can use them to visualize the graph.
Let's convert Python int values in the edge list to double and extract the nodes in the edges into separate vectors.
s = cellfun(@(x) double(x{1}), edgeC); t = cellfun(@(x) double(x{2}), edgeC);
MATLAB graph expects column vectors of nodes. Let's transpose them.
s = s'; t = t';
The node indices in Python starts with 0, but the node indices must start with non-zero value in MATLAB. Let's fix this issue.
s = s + 1; t = t + 1;
Now, we are ready to create a MATLAB graph object and plot it, with Mr. Hi's faction highlighted.
G = graph(s,t); G.Nodes.club = nodeAttrs'; figure P1 = plot(G); highlight(P1, group_hi,'NodeColor', '#D95319', 'EdgeColor', '#D95319') title({'Zachary''s Karate Club','Orange represents Mr. Hi''s faction'})
Passing Data from MATLAB to Python
In this case, we already have the NetworkX graph object, but for the sake of completeness, let's see how we could create this Python object within MATLAB.
Let's create an empty NetworkX graph.
nxG2 = py.networkx.Graph();
You can add edges to this graph with the add_edges_from method. It accepts a Python list of tuple elements like this:
[(1,2),(2,3),(3,4)]
This is not a valid syntax in MATLAB. Instead we can use a 1xN cell array of node pairs like this:
myListofTuples = {{1,2},{2,3},{3,4}};
When we pass this nested cell array to py.list, MATLAB automatically converts it to a Python list of tuple elements.
myListofTuples = py.list(myListofTuples); myDataType = class(myListofTuples{1})
myDataType = 'py.tuple'
Let's extract the edge list from the MATLAB graph. It is a 78x2 matrix of double values. In MATLAB, double is the default numeric data type.
edgeL = G.Edges.EndNodes; myDataType = class(edgeL)
myDataType = 'double'
If we convert an array of double values to a Python list, the values will be converted to Python float, but the default numeric data type in Python is int. So we cannot use double.
listContent = py.list(edgeL(1,:))
listContent = Python list with no properties. [1.0, 2.0]
Also, Python indexing is 0-based while MATLAB is 1-based. We need to convert the array of double elements to int8 and change the variable elements to 0-based indexing.
edgeL = int8(edgeL) - 1; myDataType = class(edgeL)
myDataType = 'int8'
We can use num2cell to convert the matrix of int8 values to a 78x2 cell array, where each element is in a separate cell.
edgeL = num2cell(edgeL); myDataType = class(edgeL)
myDataType = 'cell'
We can place the node pairs in the same cell by converting the 78x2 cell array to a 78x1 cell array using num2cell.
edgeL = num2cell(edgeL,2); [rows,cols] = size(edgeL)
rows = 78 cols = 1
The add_edges_from method expects a 1xN Python list. Now let's turn this into a 1xN cell array by transposing the Nx1 cell array, converting it to a Python list and adding it to the empty NetworkX graph object.
nxG2.add_edges_from(py.list(edgeL'));
The edges were added to the NetworkX graph object. Let's check the first 5 tuple values.
edgeL = py.list(nxG2.edges); listContent = edgeL(1:5)
listContent = Python list with no properties. [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
The nodes were also added in the graph, but they currently don't have any attributes, as you can see below in the first 3 elements of the node list.
nodeL = py.list(nxG2.nodes.data); listContent = nodeL(1:3)
listContent = Python list with no properties. [(0, {}), (1, {}), (2, {})]
To add attributes, we need to use the set_node_attributes method. This method expects a nested Python dict. Here is how to create a dict in MATLAB.
myDict = py.dict(pyargs('key', 'value'))
myDict = Python dict with no properties. {'key': 'value'}
The set_node_attributes method expects a nested dict. The keys of the outer dict are the nodes, and values are dict arrays of key-value pairs like this:
{0: {'club': 'Mr. Hi'}, 1: {'club': 'Officer'}}
Unfortunately, this won't work, because pyargs expects only a string or char value as the key.
>> py.dict(pyargs(0, py.dict(pyargs('club', 'Mr. Hi')))) Error using pyargs Field names must be string scalars or character vectors.
Instead, we can create an empty dict, and add the inner dict from the tuple data, using 0-based indexing, with the update method like this:
attrsD = py.dict; for ii = 1:length(nodeAttrs) attrD = py.dict(pyargs('club', G.Nodes.club(ii))); attrsD.update(py.tuple({{int8(ii - 1), attrD}})) end
Then we can use the set_node_attributes to add attributes to the nodes.
py.networkx.set_node_attributes(nxG2, attrsD); nodeL = py.list(nxG2.nodes.data); listContent = nodeL(1:3)
listContent = Python list with no properties. [(0, {'club': 'Mr. Hi'}), (1, {'club': 'Mr. Hi'}), (2, {'club': 'Mr. Hi'})]
Community Detection with NetworkX
NetworkX provides the greedy_modularity_communities method to find communities within a graph. Let's try this algorithm to see how well it can detect the factions!
Since this club split into two groups, we expect to see 2 communities.
communitiesL = py.networkx.algorithms.community.greedy_modularity_communities(nxG2); myDataType = class(communitiesL)
myDataType = 'py.list'
The returned Python list contains 3 elements. That means the algorithm detected 3 communities within this graph.
num_communitieis = length(communitiesL)
num_communitieis = 3
The list contains a frozenset. A Python frozenset is the same as a Python set, except its elements are immutable. And a Python set is similar to a Python list, except all its elements are unique, whereas a list can contain the same element multiple times.
listContent = communitiesL{1}
listContent = Python frozenset with no properties. frozenset({32, 33, 8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31})
Let's convert it into nested cells.
communitiesC = cell(communitiesL); communitiesC = cellfun(@(x) cell(py.list(x)), communitiesC, 'UniformOutput', false); myDataType = class(communitiesC{1}{1})
myDataType = 'py.int'
The inner most cell contain Python int values. Let's convert them to double.
for ii = 1:length(communitiesC) communitiesC{ii} = cellfun(@double, communitiesC{ii}); end myDataType = class(communitiesC{1}(1))
myDataType = 'double'
Since the nodes are 0-based indexed in Python, we need to change them to 1-based indexed in MATLAB.
communitiesC = cellfun(@(x) x + 1, communitiesC, 'UniformOutput', false);
Let's plot the communities within the graph.
tiledlayout(1,2) nexttile P1 = plot(G); highlight(P1, group_hi,'NodeColor', '#D95319', 'EdgeColor', '#D95319') title({'Zachary''s Karate Club','Orange represents Mr. Hi''s faction'}) nexttile P2 = plot(G); highlight(P2, communitiesC{1},'NodeColor', '#0072BD', 'EdgeColor', '#0072BD') highlight(P2, communitiesC{2},'NodeColor', '#D95319', 'EdgeColor', '#D95319') highlight(P2, communitiesC{3},'NodeColor', '#77AC30', 'EdgeColor', '#77AC30') title({'Zachary''s Karate Club','Modularity-based Communities'})
If you compare these plots, you can see that the two communities on the right in orange and green, when combined, roughly overlap with Mr. Hi's faction.
We can also see that:
- Community 1 represents the 'Officer' faction
- Community 3 represents the devoted 'Mr. Hi' faction
- Community 2 represents the people who had connections with both factions
Interestingly, Community 2 ultimately ended up siding with Mr. Hi's faction.
Let's see if there is any difference between the output of the algorithm and the actual faction.
diff_elements = setdiff(group_hi, [communitiesC{2} communitiesC{3}]); diff_elements = [diff_elements setdiff([communitiesC{2} communitiesC{3}], group_hi)]
diff_elements = 9 10
The community detection algorithm came very close to identifying the actual faction.
Streamlining the Code
Up to this point we have been examining what data type is returned in each step. If you already know the data types, you can combine many of these steps into a few lines of code.
To get the karate club data and create a MATLAB graph, you can just do this:
nxG = py.networkx.karate_club_graph(); edgeC = cellfun(@cell, cell(py.list(nxG.edges)), 'UniformOutput', false); nodeC = cellfun(@cell, cell(py.list(nxG.nodes.data)), 'UniformOutput', false); nodeAttrs = cellfun(@(x) struct(x{2}), nodeC); nodeAttrs = arrayfun(@(x) string(x.club), nodeAttrs); s = cellfun(@(x) double(x{1}), edgeC)' + 1; t = cellfun(@(x) double(x{2}), edgeC)' + 1; G = graph(s,t); G.Nodes.club = nodeAttrs';
To create a Python graph from the MATLAB data, you can do this:
nxG2 = py.networkx.Graph(); edgeL = num2cell(int8(G.Edges.EndNodes) - 1); nxG2.add_edges_from(py.list(num2cell(edgeL, 2)')); attrsD = py.dict; for ii = 1:length(G.Nodes.club) attrD = py.dict(pyargs('club', G.Nodes.club(ii))); attrsD.update(py.tuple({{int8(ii - 1), attrD}})) end py.networkx.set_node_attributes(nxG2, attrsD);
And to detect the communities, you can do this:
communitiesC = cell(py.networkx.algorithms.community.greedy_modularity_communities(nxG2)); communitiesC = cellfun(@(x) cell(py.list(x)), communitiesC, 'UniformOutput', false); for ii = 1:length(communitiesC) communitiesC{ii} = cellfun(@double, communitiesC{ii}); end communitiesC = cellfun(@(x) x + 1, communitiesC, 'UniformOutput', false);
Summary
In this example, we saw how we can use Python within MATLAB. It is fairly straight forward once you understand how the data type conversion works. Things to remember:
- Python is 0-based indexed vs MATLAB is 1-based indexed
- Python's default numeric data type is int whereas it's double for MATLAB
- Instead of loops, convert Python data into suitable types of MATLAB arrays
- Use cell arrays for Python list and tuple
- Use struct arrays for Python dict
In this example, we used a Python library in our MATLAB workflow to get the data and detect communities. I could have coded everything in MATLAB, but it was easier to leverage existing Python code and I was able to complete my tasks within the familiar MATLAB environment where I can be most productive.
Are you a coding polyglot? Share how you use MATLAB and Python together here.
Published with MATLAB® R2019b
To leave a comment, please click here to sign in to your MathWorks Account or create a new one. | https://blogs.mathworks.com/loren/2020/03/03/matlab-speaks-python/?s_tid=blogs_rc_3 | CC-MAIN-2021-43 | refinedweb | 2,907 | 57.37 |
This assignment has two parts. Part 1 is due at 11 PM on Sep 12 2019. Part 1 will not be accepted past this time (the regular late policy does not apply to Part 1).
Part 2 is due at 11 PM on Sep 17 2019. For Part 2, see the late policy for information on late submissions. Make sure to follow the submission instructions.
Each student must do this assignment alone. You may work in pairs from Programming Assignment 2 (not Part 2) onwards. You may discuss this assignment with the instructor, TA, and other students, but you may not share code.
In this assignment, you will write several Java classes to be used later in the semester to represent a symbol table. This is a simple assignment to get you up to speed with your computing environment, Java, and our programming and testing conventions.
Make sure you read through everything carefully. The assignment appears long but it is less work than it might initially seem. If it seems difficult, ask for help; you may be misunderstanding something.
The SymTable class will be used by the compiler you write later in the semester to represent a symbol table: a data structure that stores the identifiers declared in the program being compiled (e.g., function and variable names) and information about each identifier (e.g., its type, where it will be stored at runtime). The symbol table will be implemented as a List of HashMaps. Eventually, each HashMap will store the identifiers declared in one scope in the program being compiled.
The HashMap keys will be Strings (the declared identifier names) and the associated information will be Syms (you will also implement the Sym class). For now, the only information in a Sym will be the type of the identifier, represented using a String (e.g., “int”, “double”, etc.).
The DuplicateSymException and EmptySymTableException classes will define exceptions that can be thrown by methods of the SymTable class.
In addition to defining the four classes, you will write a main program to test your implementation. You will be graded on the correctness of your Sym and SymTable classes, on how thoroughly you test the classes that you implement, on the efficiency of your code, and on your programming style.
The Sym Class
The Sym class must be in a file named Sym.java. You must implement the following Sym constructor and public methods (and no other public or protected methods):
The SymTable Class
The SymTable class must be in a file named SymTable.java. It must be implemented using a List of HashMaps. (Think about the operations that will be done on a SymTable to decide whether to use an ArrayList or a LinkedList.) The HashMaps must map a String to a Sym. This means that the SymTable class will have a (private) field of type List<HashMap<String,Sym>>.
List and HashMap are defined in the java.util package. This means that you will need to have the line
import java.util.*;
You must implement the following SymTable constructor and public methods (and no other public or protected methods):
The DuplicateSymException and EmptySymTableException Classes
These two classes (which must be in files named DuplicateSymException.java and EmptySymTableException.java) will simply define the two checked exceptions that can be thrown by the SymTable class. Each exception must be able to be created using a constructor that takes no arguments.
To define a checked exception named XXX, you can use code like this:
public class XXX extends Exception { }
Note that the class has an empty body (it will have a no-argument constructor by default).
The main program
To test your SymTable implementation, you will write a main program in a file named P1.java. The program must not expect any command-line arguments or user input. It can read from one or more files; if you set it up to do that, be sure to hand in the file(s) along with P1.java.
Be sure that your P1.java tests all of the Sym and SymTable operations and all situations under which exceptions are thrown. Also think about testing both “boundary” and “non-boundary” cases.
It is up to you how your program works. A suggested approach is to write your program so that output is only produced if one of the methods that it is testing does not work as expected (e.g., if the lookupLocal method of the SymTable class returns null when you expect it to return a non-null value). This will make it much easier to determine whether your test succeeds or fails. The one exception to this approach is that P1.java will need to test the print method of the SymTable class and that will cause output to be produced.
To help you understand better the kind of code you would write using this suggested approach, look at TestList.java. This file contains a main program designed to test a (fictional) List class whose methods are documented in TestList.java. You are being asked to write something similar (in a file called P1.java) to test the Sym and SymTable classes. You should be able to write P1.java before you write the classes that it's designed to test.
Test Code
After the Part 1 deadline, download our P1.java file and test it against the expected output. Make sure that your actual output matches this.
On a Linux machine you can see whether two files match by using the diff utility. For example, typing diff file1 file2 compares the two files file1 and file2. Typing diff -b -B file1 file2 does the same comparison, but ignores differences in whitespace.
If you send the output of P1.java to a file, you can use diff to make sure that it matches the expected output. To send the output of P1.java to a file named out.txt (on a Linux machine) type java P1 >| out.txt.
Deadlines are at the top of the page. See instructions for submitting assignments.
By the Part 1 deadline, submit your P1.java file (and the files that it reads, if any).
By the Part 2 deadline, submit the rest of your .java files. This should include your Sym.java, SymTable.java, DuplicateSymException.java, and EmptySymTableException.java.
You may work in the environment of your choice, but be aware that your submitted code must run on the department lab Linux machines.
Do not turn in any .class files and do not create any subdirectories in your submission. If you accidentally turn in (or create) extra files or subdirectories, make a new submission that does not include them.
Remember, your P1.java is worth 15% of the grade for this assignment and will not be accepted past the deadline.
For this program, extra emphasis will be placed on style. In particular,
Every class, method, and field must have a comment that describes its purpose. Comments should also be used to explain anything that would not be obvious to an experienced Java programmer who has read this assignment.
Identifiers must conform to standard Java conventions. UPPER_CASE with underscores for named constants, CamelCase starting with a capital letter for classes, and camelCase starting with a lower-case letter for other identifiers. Names should help a reader to understand the code.
Indentation must be consistent and clear. Use either one tab character or four spaces for each level of indentation. Do not mix spaces and tabs for indentation; either always use tabs or never use them.
Avoid lines that are longer than 80 characters (including indentation).
Each field or method must be declared public, protected, or private. If you have good reason to give a field or method “package” (default) access – which is highly unlikely – you must include a comment explaining why.
The goal is to make your code readable to an experienced Java programmer who is used to the conventions. The goal is not to develop your own personal style, even if it's “better” than the standard. For more advice on Java programming style, see Code Conventions for the Java Programming Language. See also the style and commenting standards used in CS 302 and CS 367.
Also be very sure that you use the specified file names (being careful about the upper- and lower-case letters in those names). And be sure that the output that is produced when we run our P1.java using your implementations of the Sym, SymTable, DuplicateSymException, and EmptySymTableException classes matches the expected output that we provide. We will test that output by automatically comparing it to the expected output and you will lose points for even minor differences. | http://pages.cs.wisc.edu/~aws/courses/cs536-f19/asn/p1/p1.html | CC-MAIN-2019-43 | refinedweb | 1,445 | 65.73 |
Marriage Tips from true life experience
Things that this hub is going to cover
Best advise from experience
Thoughts on having a spouse
Thoughts on being married
Family time is key
5 major Tips & things to avoid as a happily married couple
True love is worth all time spent
Best advise from experience
Hey KrystalD thanks for asking such a great question about the subject of marriage, my advise about marriage is to stay true to yourself and be honest with your spouse or fiancee. Life may have its ups and down's, but you must hang on tightly to keep things going in any marriage, because being married is fun filled, with all the twists and turns that you may not enjoy at all times.
Marriage is surely worth the struggles, when two people have chosen to get married for the right reasons, and when the love is unified between both partners in the physical, mental, and most importantly in all spiritual ways possible. This Unity can be established by joint belief systems, good morals, love and mutual respect for one another as well as the tender loving care for family.
This marriage thing, definitely takes a level of emotional balance, and the overall interdependent well being of a happy couple, so try to work towards making your lives together, equate to more of a higher value in every way shape and form, as you both go along as a married couple.
I also think that good healthy eating, exercise, having fun together, sharing everything with each other, and even group meditation may help a marriage a great deal in this department, and also help to establish a strong positively based productive family with a wholesome foundation. (Seek an expert Marriage Counselor or family therapist, if your marriage has gotten out of hand, or your family may be in need of counseling assistance.)
Love is one magnetic experience
Thoughts on having a spouse-
If your partner truly loves you. things will surely work out for the better in due time, just keep working at it, and never expect anything to turn out perfect, and for your marriage partner to magically change their behavior patterns, before or after the marriage begins.
My wife is a woman who is bright and full of liveliness, she's knowledgeable in terms of life as a whole, has a high IQ or high leveled mental capacity, she is a challenging and effective communicator, skillful, intelligent, very loving, caring, and most of all she possesses both inward and outward beauty that radiates, and emanates into my atmosphere. In other words these are just some of the reasons why I love her so much.
Try figuring out what you love about your fiancee, significant other, or spouse, then list it to get an idea of such love you have for them, because it works wonders for me to tell her when she asks me, and I mean what I say to her in every way.
Her show of affection allows for me to become much more passionate for our relationship, and how we share things evenly, sharing is definitely a key to a great marriage, so be mindful of that. We do many things with one another, and find many ways to make time for one another, as well as making time for our family. Balance is something that's not easy to establish in ones life, but must be worked on in every sense of the word.
Marriage Life deepen's love
Thoughts on being married-
- My marriage is only a good one, because I refuse to give in to the temptations outside of my marriage, and my wife appears to be doing the same in return (Remain truly committed to the relationship).
- It definitely takes two to make it work, money or no money, for better and for worse, and beauty alone simply cannot keep two folks together for long. (True love, Courage & prayer helps)
- Realize there's much more at work behind the scene's to a marriage between two adults, and you must be in it for the long haul. (Dedication to one another)
Plan things out prior to starting a family its worth it to plan
You can get your kids involved
Family meal time books
Family time is key -
"I feel that dinner time or any meal times is the key element that brings all families together, and so I strongly believe that the heart to the family is through the stomach. With that being stated I also firmly believe that by repairing that factor in a family, the children will follow suit in doing the right things for themselves as well as for others, because they can learn the simplistic understanding of family values at the dinner table, which can be applied to their every day life."
Tips & Family Factoids-
- A vast majority of today's American families aren't into eating home cooked meals anymore, and so this is how many family structures simply fall out of synch, and many of the responsibilities of daily chores, nightly cleaning, etc.... These core family values are simply lacking in most of our youth, as well as adults today.
- This particular issue needs to be addressed or fixed, before a true marriage relation is to even think of lasting, and so both partners need to consider getting much more familiar with the kitchen, and into cooking for one another wholesome hearty meals as well as for their children, if any are present or to come.
- Open up them cook books, watch some cool online cooking videos, and get into making your family the best meals you can find is my best recommendation, and look for organic food alternatives for healthy cooking, as well as more veggies for the healing factors of your meal preparations for the family, it will help boost the families energies 10 fold.
5 major Tips & things to avoid as a happily married couple
1 - Trust is a key element to a good and long lasting relationship as well, it will make or break any marriage no matter what. Many people simply can't trust their partners with money, or finances. If this is the case early in the marriage think twice, because it can potentially arise in the future, so be wise and look to marry someone who's much more trustworthy with money.
2 - Lust for having sex with others besides your spouse, is a huge issue in most relationships, especially in marriages, and is the cause for many break-ups or even divorce. So try to be mindful of what you choose to say, do, or think about others, and try not to worry so much about your spouse is my best advise, because if they're due to become unfaithful to you, then you're surely bound to find out in due time.
3 - Patience is a virtue, is what many people say to one another, but in all honesty in order for a love life to flourish, one must invest their time into the other. This takes a great deal of patience, and so if your not the patient type, and are into rushing everything, you might just want to rethink things a bit, because this part of a marriage, can also be the difference from experiencing a life of awesomeness with your spouse, or one that feels like a heavy burden, or worse off.
4 - Arguments are bound to happen between partners, and as a married couple, expect to have confrontations with one another, it actually is said to be therapeutic, but be very careful how you go about it all. Just because two people can't seem to agree on certain topics doesn't mean you should do harm to the other person, whether with words or anything physical in nature.
5 - Forgiving your spouse with love- Try to think about the love factor, and the fact that y'all both have a long life to live with one another, simply give the other person a chance to breath, to get their point across, and back off at times. You don't always have to be the victor or winner of the conversation, or choice in what to do next. "Give it a breather", your wife, or husband will love you more for simply backing down every now and then.
More great! articles about the love thing
- Birthday Greetings on Hubpages- To the love of my li...
A love poem for my wife on her birthday, some things are simply priceless.
- Love is all this to me, so what is it to you
A cool poem all about love, encompassing the wholeness of it all in some truly creative ways.
- Cheating in a relationship, and how hard it is to f...
Relationships can be tough, and finding out someone has cheated on you is even tougher. This article is an answer to a Q&A, which is meant to provide help for those who find it hard to forgive, but also it informs folks of ways to detect the stag
- How to know that you truly love someone
Love life is good at time and can be bad as well, this hub is all about how to know whether or not you truly love someone.
More by this Author
- 32
My mom died of breast cancer and like many other countless victims of the disease, medically there's no known cure. To my surprise I found a documentary that suggests there was a doctor who has proven claims.
Awesome hubexplorer! This was very thorough and honest. All relationships take work and marriage is a huge commitment. I agree that balance and communication are huge components. I think for some of us single folks, these can be important to remember once entering relationships.
I also think you are completely right about mental and spiritual connections creating happiness. The physical realm seems to be the least important (though they mean something).
Falling in love too quickly based on physical attraction can certainly be a road block on the path to something lasting.
Thanks for taking the time to write this hub because it certainly gave me some things to think about.
some very useful tips brought out by you cloudexplorer, marriage is indeed a sacred bond which is to be made after thorough decision, because it is with that person we intend to spend our life with
sharing it
5 | http://hubpages.com/relationships/Marriage-Tips-from-true-life-experiences | CC-MAIN-2016-50 | refinedweb | 1,747 | 55.31 |
To anyone that can help,
I am engineer and I am using a Javelin Stamp to run five servo motors for a robot that will mimic nature. When I try and send information to the controller it gives me a constant yellow when I am connected to the logic level serial input. When i am connected to the RS-232 input i get a flashing green and constant red light. I would greatly appreciate anyone that could help me out. Below is the simple test code that i have been using in Java. Thanks!!!
Sincerely,
import stamp.peripheral.servo.pololu.*; import stamp.core.*; public class pololu_msc_test { static Uart tx = new Uart(Uart.dirTransmit,CPU.pin1,Uart.dontInvert,Uart.speed9600,Uart.stop1); static void main() { System.out.println("Pololu mode (jumper not installed) test program"); while (true) { //get servo numbers, the green led will flash to identify servo numbers tx.sendByte(0x80); tx.sendByte(0x02); tx.sendByte(0x10); CPU.delay(31500); //wait 3 secs } } } | https://forum.pololu.com/t/micro-servo-controller/253 | CC-MAIN-2022-27 | refinedweb | 163 | 57.57 |
CodePlexProject Hosting for Open Source Software
According to the following statement should be true regarding DefaultValueHandling and setting it to Ignore
"For value types like int and DateTime the serializer will skip the default unitialized value for that value type"
I cannot get it to work as described though (using .net 4 and json 4.5.7)
Consider the following class
public class D {
public int No;
public string Name;
public double Amount;
public bool Check;
public D Parent;
public byte Byte;
public uint Uint;
}
Used in the test below
[Test]
public void TestMethod3() {
var d = new D();
var settings = new JsonSerializerSettings{DefaultValueHandling = DefaultValueHandling.Ignore};
Console.WriteLine(JsonConvert.SerializeObject(d,settings));
//writes {"No":0,"Amount":0.0,"Check":false,"Byte":0,"Uint":0}
}
It should (by my iterpretation of the documentation) write {}, but it doesn't.
/Dan
Why has no one replied? I am having the same issues on 4.5.
Oddly, if you specify DefaultValue(0), etc on these, it works.
It seems like the default value its reading is incorrect? Are they defaulted to something like -1 instead?
This has been fixed in 4.5.9
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://json.codeplex.com/discussions/360883 | CC-MAIN-2018-05 | refinedweb | 224 | 57.98 |
Database connection sql server 2005 - JDBC
Database connection sql server 2005 Hi all i am developing an application in struts and i need to connect database for that application using sql server 2005.. can anyone tell me how to make database connection ..plz help me
Merge databases in SQL SErver 2005
Merge databases in SQL SErver 2005 Please help me to merge databases in SQL server 2005
jsp sql server 2005 connectivity
jsp sql server 2005 connectivity your jsp mysql tutorial is very help full.Please tell me how to connect jsp with SQL server 2005
connect sql server 2005 using php
connect sql server 2005 using php how to connect sql server 2005 using php program. how mssql_connect will work
how to connect SQL Server 2005 using php
how to connect SQL Server 2005 using php i need to connect SQL Server 2005 using php. how can i connect . how to use mssql_connect function
How to display single row from sql server 2005
How to display single row from sql server 2005 I am doing MCA project work. I am new in ejb and struct. i m using sql server 2005,jsp, ejb module, action classes and struct, i have a table which contains ID and Name, i want show
Using C# DataGridView to insert record into Microsoft SQL Server 2005 database - SQL
Using C# DataGridView to insert record into Microsoft SQL Server 2005 database Dear Sir,
I am new to Microsoft SQL Server 2005. Currently, i'm creating a sales database system using C# and Microsoft SQL Server 2005.
I had
How to search the table name in MS SQL Database 2005 from application
How to search the table name in MS SQL Database 2005 from application How to search the table name in MS SQL Database 2005 from application from our helpdesk application? application might be in html
SQL Server
SQL Server Hii,
What is SQL Server ?
hello,
SQL Server is a DBMS system provided by Microsoft
sql server - SQL
sql server what is SQL server? & what is oracle? are they same
sql server - SQL
sql server How many no of tables can be joined in same sql server
Sql Server - SQL
sql server trigger example Can any one tell me the live example of triggers in SQL Server? if u click pistal trigger ,it auotmatically shoot bullet it's like newtons 3rd law (every action s having an equal reaction
Export SQL database schema from SQL server management studion express2005 into MS excel file
Export SQL database schema from SQL server management studion express2005 into MS excel file HI I need to export Database Schema from SQL Server... server management studio express 2005
connecting to database - Struts
to MS SQL Server 2005 database.
My first is what do i write in struts-configuration.xml file
that enable me to use methods in the model class to display... information.
XML in SQL Server
XML in SQL Server Hi.....
please anyone tell me about
What is the purpose of FOR XML in SQL Server?
Thanks
How to send the data selected from drop down menu from html page to sql 2005 database.
How to send the data selected from drop down menu from html page to sql 2005 database. Dear Sir,
If I want to save the information provided by user from html drop down menu such as
check-in date for hotel reservation. connection with sql - Struts
DataBase connection with sql How to connect sql and send db error in struts? what are the tag should i code in struts-confic.xml
SQL SERVER 2008
SQL SERVER 2008 when i am fill the all fields in the form.but when i am retrive from the database it shows only firstname,age,address.remaining fields was shows as null.and it shows the gender as the on.i can't understand what
SQL
SQL what data type we use for the uploading the video and image files in MySQL server 2008
SQL connection error in android
SQL connection error in android hi,
i am android developer . recently i made one application connect with sql server 2005 using jtds...:sql:Exception : BUFFERDIR connection property invalid.
if you have any answer
Sql Server 2008 with textbox
Sql Server 2008 with textbox **Hi, I tried to insert into DB using textbox in a form using vb by visual studio 2010 but its always catch an error...
myconn = New SqlConnection("server=localhost;" & "Initial Catalog=4 to SQL Server Connectivity
Java to SQL Server Connectivity Hi, heres my code
private void bookedButton()
{
try
{
Class.forName... with sql server connectivity at the background to save the data.
Now, after
populating the combo box - Struts
populating the combo box Hi
I am having problem populating the combo box with a table in MS SQL Server 2005 Management Studio Express.
Belo... the model class -
public ArrayList getAllSectors(String main_sector_id
jdbc odbc sql server exception
jdbc odbc sql server exception Hi,
I am trying to use sql server with java jdbc odbc but I am getting this exception
java.sql.SQLException: [Microsoft][SQL Server Native Client 10.0][SQL Server]Incorrect syntax near '@P1
Struts 1)in struts server side validations u are using programmatically validations and declarative validations? tell me which one is better ?
2) How to enable the validator plug-in file
How to create a .mdf file from script (.sql)
How to create a .mdf file from script (.sql) Hi,
I have a sql database in 2008 server. now i want it to convert to 2005. so i script it. just help me to create a .mdf file back from the script
How to insert image in sql database from user using servlet
How to insert image in sql database from user using servlet pls tell me accept image from user and insert image in sql server 2005 database using servlet and jsp
Struts
web applications quickly and easily. Struts combines Java Servlets, Java Server...Struts What is Struts?
Hi hriends,
Struts is a web page... developers, and everyone between.
Thanks.
Hi friends,
Struts is a web
Java servlet with jsp on sql server
Java servlet with jsp on sql server How to delete a user by an admin with check box in Java Servlet with jsp on Sql Server?
Here...;
<form name=myname method=post
<table border="1">
The server encountered internal error() - Struts
The server encountered internal error() Hello,
I'm facing the problem in struts application.
Here is my web.xml
MYAPP...
config
2
action
web server - Struts
SQL Server Training
SQL Server Training
Microsoft's product SQL Server is a relational database management system (RDBMS....
This SQL Server training course will train you everything like installing SQL
JAVA
JAVA how to insert data from netbeans 7.0 into SQL server 2005 software using Struts
SQL Server row comparison using two tables
SQL Server row comparison using two tables insertion process are completed in table1.string comparison using table2 to table1 if any changes in these tables and then upadated
java and sql server NOT Mysql - JSP-Servlet
java and sql server NOT Mysql Hi guys.
Thank you all for the various helps you render to everyone. Please the question I asked the last time... image from MS SQL server NOT MySQL. Or is it not possible to do it in MS SQL server
Online exam using c# and SQL server
Online exam using c# and SQL server hello, i'm making the (window based)online examination system using C#.net and SQL SERVER. my database is stored on server. my question is: if during the examination server gets failed
How to read textfile and create SQL server table ?
How to read textfile and create SQL server table ? hi sir, your site... trying to read textfile and create table in sql server but it gives error.../questions/16415498/creating-a-table-in-sql-database-by-reading-textfile-in-java
To retrieve image from SQL Server Database - Java Server Faces Questions
To retrieve image from SQL Server Database Sir/Madam,
I am trying to retrieve image from SQL Server 2000 database in Visual Web JSF Page using... or in Image Component.
please help me in retrieving and displaying image from SQL Server
Error while SQL Server connection to Java
Error while SQL Server connection to Java import java.sql.*;
public...");
con=DriverManager.getConnection("jdbc:odbc:SQL_SERVER;user=DTHOTA;password...("password", " ");
con=DriverManager.getConnection("jdbc:odbc:SQL_SERVER", prop
multiboxes - Struts
in javascript code or in struts bean. Hi friend,
Code to solve
Sending form data from HTML page to SQLserver 2005 database by calling servlet code
Sending form data from HTML page to SQLserver 2005 database by calling servlet...="post" action="">
<center>
<...*;
import javax.servlet.http.*;
public class Registration extends HttpServlet
struts - Struts
struts Hi,
I need the example programs for shopping cart using struts with my sql.
Please send the examples code as soon as possible.
please send it immediately.
Regards,
Valarmathi
Hi Friend,
Please
How to add value from sql server in dropdownlist
How to add value from sql server in dropdownlist I have created a hospital management project using jsp servlet, where one form name is patient registration, in that form i have taken id, name, and i want to retrieve a patient
sql and .net
sql and .net I want get coding of connecting data base sql server 2000 to .net please help to export the query result in SQL Server to .csv file?
how to export the query result in SQL Server to .csv file? how to write table data into CSV file using SQL SERVER 2008
insert and retrive image from sql server database in jsp
insert and retrive image from sql server database in jsp what is the code to insert and retrive an image from sql server database in jsp
database - SQL
Server,
* MySQL does not support Triggers, SQL Server does.
* MySQL does not support User Defined Functions, SQL Server does.
* MySQL does not have Cursor Support, SQL Server does.
* MySQL does not support Stored
division in sql
count ( member_id) from member)
output = 2005
Now i have to divide above 2... in sql
The query used to display all tables names in SQL Server.
The query used to display all tables names in SQL Server. What is the query used to display all tables names in SQL Server (Query analyzer
SQL or UNICODE - SQL
......
I had also change my backhand to SQL SERVER but retrieves same for UNICODE...SQL or UNICODE Hi again............
I have got something new... java.util.*;
class MSAccess{
public static void main(String[] args) {
try
Open Source SQL
be a routine step.
SQL Server 2005 leaves open... server to use, it truly depends on your needs.
Despite the fact that MS SQL... match up with Oracle, SQL Server, DB2, or Sybase.?
Free open
How to insert multiple drop down list data in single column in sql database using servlet
drop down list box for year,month and day into dateofbirth column in sql server 2005..
pls help me...How to insert multiple drop down list data in single column in sql database
chat server
chat server i want to develop chat server through jsp+struts+spring+hibernate so please guide me
SQL
by most of the database systems including Oracle, Sybase, Microsoft SQL Server... SQL - SQL Introduction
SQL - An Introduction to the Structured Query Language
SQL stands for Structured
struts validations - Struts
struts validations hi friends i an getting an error in tomcat while running the application in struts validations
the error in server...
---------------------------------
Visit for more information.
JAVA
JAVA how to insert data from netbeans 7.0 into sql server 2005 software using Struts?
Have a look at the following link:
Struts: Insert data into mysql database
saving the changes in Microsoft sql sever - SQL
saving the changes in Microsoft sql sever How do we commit the changes in Microsoft sql server
Struts Articles
.
4. The UI controller, defined by Struts' action class/form bean... application. The example also uses Struts Action framework plugins in order to initialize the scheduling mechanism when the web application starts. The Struts Action
STRUTS INTERNATIONALIZATION
STRUTS INTERNATIONALIZATION
--------------------------------
by Farihah Noushene B.E.
================================
(published in Developer IQ - Oct 2005... to implement
Internationalization (abbreviated as I18N) in Struts Architecture - Struts
the interactive form based applications with server pages.
Struts...Struts Architecture
Hi Friends,
Can u give clear struts architecture with flow. Hi friend,
Struts is an open source
Struts Books
application
Struts Action Invocation Framework (SAIF) - Adds features like Action interceptors and Inversion of Control (IoC) to Struts.
Struts BSF - A Struts Action implementation that uses BSF-compatible
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... not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet
Struts Alternative
properties of the respective Action class. Finally, the same Action instance...
Struts Alternative
Struts is very robust and widely used framework, but there exists the alternative to the struts framework
java
java how to insert data from netbeans 7.0 into sql server 2005 software?
Have a look at the following link:
Struts: Insert data into mysql database
jboss and struts - Struts
Deploy JBoss and Struts how to deploy struts 2 applications in jboss 4... the WAR file to the /server/default/deploy folder. Hello,You...;JBoss_home>/server/default/deploy folder.Jboss will automatically deploy
JDBC Connection code to connect servlet with SQL Server 2008
JDBC Connection code to connect servlet with SQL Server 2008 Please ans me why it is not connect i use netbeans IDE7.0 Jdk 1.7 i also add... is not supported by this driver. Use the sqljdbc4.jar class library, which provides
date range in sql
date range in sql How can I select a random date from a date range in SQL server
validations in struts - Struts
I an getting an error in tomcat while running the application in struts validations
the error in server as "validation disabled"
plz give me reply as soon...}.
-------------------------------
Visit for more information. Java
Struts for Java What do you understand by Struts for Java? Where Struts for Java is used?
Thanks
Hi,
Struts for Java is programming framework. The Struts for Java is software development framework for creating
how to insert image into server
how to insert image into server how to insert an image into sql server and retrieve it using j import data from sql server table into an excel file by creating the rows dynamically in the excel according to the dataabase??
How to import data from sql server table into an excel file by creating... data from sql server table into an excel file by creating the rows dynamically in the excel according to the dataabase??
There is a table in sql server having
validation - Struts
validation Hi Deepak can you please tell me about struts validations perticularly on server side such as how they work whats their role etc.?
thank you
my sql innodb
my sql innodb Write a java program that connects to a MySQL server and checks if the InnoDB plug-in is installed on it. If so, your program should print the total number of disk writes by MySQL
Tomcat Server error - Framework
Tomcat Server error I am doing problem on struts,spring integration.in that at the time of tomcat server starting SEVERE: Error listenerStart occurs.why this error will occurs please tell the Tutorials
Struts application, specifically how you test the Action class.
The Action class... into a Struts enabled project.
5. Struts Action Class Wizard - Generates Java starter code for a Struts Action class.
7. BC4J JSP Struts Application Wizard | http://roseindia.net/tutorialhelp/comment/95692 | CC-MAIN-2014-42 | refinedweb | 2,621 | 62.68 |
View all headers
Path: cs.uu.nl!phil.uu.nl!humbolt.nl.linux.org!news.nl.linux.org!surfnet.nl!txtfeed1.tudelft.nl!tudelft.nl!txtfeed2.tudelft.nl!eweka!lightspeed.eweka.nl!border2.nntp.ams.giganews.com!border1.nntp.ams.giganews.com!nntp.giganews.com!proxad.net!diablo.voicenet.com!207.115.63.139.MISMATCH!newscon06.news.prodigy.com!newscon02.news.prodigy.com!prodigy.net!newstrans.cos.agilent.com!sdd.hp.com!news.compaq.com!news.cpqcorp.net!53ab2750!not-for-mail
Newsgroups: comp.os.vms,comp.sys.dec,comp.answers,news.answers
Followup-To: poster
Distribution: world
X-Newsreader: mxrn 6.18-32C
From: hoffman@xdelta.hp.nospam (Hoff Hoffman)
References: <RdISe.11789$RS3.3916@news.cpqcorp.net> <0hISe.11790$RS3.9268@news.cpqcorp.net> <3jISe.11791$RS3.9709@news.cpqcorp.net> <AkISe.11792$RS3.7150@news.cpqcorp.net> <imISe.11793$RS3.10200@news.cpqcorp.net> <lpISe.11794$RS3.10480@news.cpqcorp.net> <UqISe.11795$RS3.4702@news.cpqcorp.net> <RsISe.11796$RS3.3215@news.cpqcorp.net> <ruISe.11797$RS3.8411@news.cpqcorp.net>
Approved: news-answers-request@mit.edu
Reply-To: hoff@hp.nospam
Organization: HP
Subject: OpenVMS Frequently Asked Questions (FAQ), Part 10/11
Summary: This posting contains answers to frequently asked questions about
the HP OpenVMS operating system, and the computer systems on which
it runs.
Lines: 2374
Message-ID: <1wISe.11798$RS3.8847@news.cpqcorp.net>
Date: Sun, 04 Sep 2005 20:09:33 GMT
NNTP-Posting-Host: 16.32.80.251
X-Complaints-To: abuse@HP.com
X-Trace: news.cpqcorp.net 1125864573 16.32.80.251 (Sun, 04 Sep 2005 13:09:33 PDT)
NNTP-Posting-Date: Sun, 04 Sep 2005 13:09:33 PDT
Xref: cs.uu.nl comp.os.vms:455756 comp.sys.dec:105309 comp.answers:61653 news.answers:293369
View main headers
Archive-name: dec-faq/vms/part10
Posting-Frequency: quarterly
Last-modified: 02 Sep 2005
Version: VMSFAQ_20050902-10.TXT
Hardware Information
of a new or replacement server. You may or may
not have some success looking for this or of any
other now-unavailable sites using the world-wide
web archives at:
o
__________________________________________________________
14.21 Why does my LK401 keyboard unexpectedly autorepeat?
There are several modes of failure:
o Pressing 2 and 3 keys at the same time causes
one key to autorepeat when released. Check the
hardware revision level printed on the bottom of
the keyboard. If the revision level is C01, the
keyboard firmware is broken. Call field service to
replace the keyboard with any revision level other
than C01.
o Pressing certain keys is always broken. Typical
symptoms are: delete always causes a autorepeat,
return needs to be pressed twice, etc. This is
frequently caused by having keys depressed while
the keyboard is being initialized. Pressing ^F2
several times or unplugging and replugging the
keyboard frequently fix this problem. (Ensure you
have current ECO kits applied; there is a patch
available to fix this problem.)
o A key that was working spontaneously stops working
correctly. This may be either of the two previous
cases, or it may be bad console firmware. Ensure
that you have the most recent firmware installed
on your Alpha system. In particular, an old version
of the DEC 3000 SRM firmware is known to have a bug
that can cause this keyboard misbehaviour.
14-50
Hardware Information
__________________________________________________________
14.22 Problem - My LK411 sends the wrong keycodes or some keys
are dead.
o DE500-XA
auto-detection, no auto-negotiation,
OpenVMS V6.2-1H1 and ALPBOOT ECO, also V7.0 and
later and ECO.
Device hardware id 02000011 and 02000012.
Component part number 54-24187-01
o DE500-AA
auto-detection, auto-negotiation,
OpenVMS V6.2 and ALPBOOT and ALPLAN ECOs, or V7.1
and later and ECO.
Device hardware id 02000020 and 20000022.
Component part number 54-24502-01
o DE500-BA
auto-detection, auto-negotiation,
OpenVMS V6.2-1H3 and CLUSIO, ALPBOOT, ALPLAN and
ALPCPU ECOs, or V7.1-1H1 or later and ECO.
Device hardware id 02000030 (check connector, vs
DE500-FA) (other values on old Alpha SRM firmware)
Component part number 54-24602-01
14-51
Hardware Information
o DE500-FA (100 megabit fibre optic Ethernet)
OpenVMS V7.1-1H1 and later
Device hardware id 02000030 (check connector, vs
DE500-BA) (other values possible on old Alpha SRM
firmware)
Component part number 54-24899-01.
________________________________________________________________
Table 14-4 DE500 Speed and Duplex Settings
________________________________________________________________
EWx0_MODE_setting_________________Meaning_______________________
Twisted-Pair 10 Mbit/sec, nofull_duplex
Full Duplex, Twisted-Pair 10 Mbit/sec, full_duplex
AUI 10 Mbit/sec, nofull_duplex
BNC 10 Mbit/sec, nofull_duplex
Fast 100 Mbit/sec, nofull_duplex
FastFD (Full Duplex) 100 Mbit/sec, full_duplex
Auto-Negotiate____________________Negotiation_with_remote_device
14-52
Hardware Information.
__________________________________________________________.
14-53
Hardware Information:
14-54
Hardware Information
Issuing 6-byte MODE SENSE QIOW to get current values for page 01h
Page Code ................. 01h
Page Name ................. Read-Write Error Recovery
Saveable .................. Yes
Size ...................... 10
Hex Data .................. E6 08 50 00 00 00 08 00
00 00
The E6 shown indicates that the AWRE and ARRE bits are
set, and this is incompatible with OpenVMS versions
prior to V6.2. Further along in the same SCSI_INFO
display, if you also see:
Issuing 6-byte MODE SENSE QIOW to get changeable values for page 81h
Page Code ................. 01h
Page Name ................. Read-Write Error Recovery
Saveable .................. Yes
Size ...................... 10
Hex Data .................. C0 08 50 00 00 00 08 00
00 00.)
14-55
Hardware Information
14-56
Hardware Information.
________________________________________________________________
Table 14-5 DEC MMJ Pin-out
_______________________________________________________
Pin_____Description____________________________________
1 Data Terminal Ready (DTR)
2 Transmit (TXD)
3 Transmit Ground (TXD-)
14-57
Hardware Information
________________________________________________________________
Table 14-5 (Cont.) DEC MMJ Pin-out
_______________________________________________________
Pin_____Description____________________________________
4 Receive Ground (RXD-)
5 Receive (RXD)
_________6_______Data_Set_Ready_(DSR)___________________________
+------------------+
| 1 2 3 4 5 6 |
+------------+ ++
+____+:
Terminal Host
MMJ MMJ
DTR 1 --->---------->----------->--- 6 DSR
TXD 2 --->---------->----------->--- 5 RXD
3 ------------------------------ 4
4 ------------------------------ 3
RXD 5 ---<----------<-----------<--- 2 TXD
DSR 6 ---<----------<-----------<--- 1 DTR.
14-58
Hardware Information
________________________________________________________________
Table 14-6 PC DB9 Pin-out
_______________________________________________________
Pin_____Description____________________________________
1 Data Carrier Detect (DCD)
2 Received Data
3 Transmit Data
4 Data Terminal Ready (DTR)
5 Ground
6 Data Set Ready (DSR)
7 Request To Send (RTS)
8 Clear To Send
_________9_______floating_______________________________________
The MicroVAX DB9 console connector pin-out predates
the PC-style DB9 pin-out (adapters discussed in
Section 14.27), and uses a then-common (and older)
standard pin-out, and uses the EIA-232 series standard
signals shown in Table 14-7.
________________________________________________________________
Table 14-7 MicroVAX DB9 Pin-out
_______________________________________________________
Pin_____Description____________________________________
1 Protective Ground
2 Transmited Data
3 Received Data
4 Request To Send (RTS)
5 Data Terminal Ready (DTR)
6 Data Set Ready (DSR)
7 Signal Ground
8 Shorted to pin 9 on MicroVAX and VAXstation
2000...
_________9_______...series_systems,_otherwise_left_floating.____
When pin 8 is shorted to pin 9, this is a BCC08 (or
variant) cable, most commonly used as a console cable
14-59
Hardware Information
on the MicroVAX 2000 and VAXstation 2000 series. (Other
systems may or may not tolerate connecting pin 8 to pin
9.)
The BN24H looks like this:
MMJ RJ45
1---------8
2---------2
3---------1
4---------3
5---------6
6---------7
The BN24J looks like this:
MMJ RJ45
1---------7
2---------6
3---------3
4---------1
5---------2
6---------8
Also see:
o
o
o
o For adapters and connectors, see Section 14.27.
__________________________________________________________
14.27 What connectors and wiring adapters are available?
The H8571-B and H8575-B convert the (non-2000-series)
MicroVAX DB9 to the DECconnect DEC-423 Modified
Modular Jack (MMJ) pin-out; to the MMJ DECconnect
wiring system. The MicroVAX 2000 and VAXstation 2000
requires a BCC08 cable (which has the 8-9 short, see
Section 14.26) and the H8571-C or the H8571-D DB25-to-
MMJ adapter for use with DECconnect. (For a discussion
of the console bulkhead on the MicroVAX II series and
on other closely-related series systems, please see
Section 14.3.3.4.)
14-60
Hardware Information
Somewhat less ancient HP (HP, Compaq or DIGITAL logo)
systems will use either the DECconnect MMJ wiring
directly or-on most (all?) recent system designs-
the PC-compatible DB9 9-pin pin-out; the PC-style COM
serial port interface and connection.
There are two DB9 9-pin pin-outs, that of the H8571-
B and similar for the MicroVAX and other and older
systems, and that of the H8571-J for the PC-style COM
port, AlphaStation, Integrity, and other newer systems.
The older MicroVAX DB9 and the PC-style DB9 pin-outs
are not compatible.
________________________________________________________________
Table 14-8 DECconnect MMJ Connectors and Adapters
_______________________________________________________
Part________Converts_BC16E_MMJ_male_to_fit_into________
H8571-A EIA232 DB25 25-pin female (common).
Functionally similar to the H8575-A, though
the H8575-A has better ESD shielding.
H8571-B Older MicroVAX (other than the MicroVAX
2000) DB9 EIA232 serial port. Functionally
similar to the H8575-B, though the H8575-B
has better ESD shielding. Note: Cannot be
used on a PC, Alpha nor Integrity DB9 9-pin
connector.
H8571-C 25 pin DSUB Female to MMJ, Unfiltered
H8571-D EIA232 25 pin male (modem-wired)
H8571-E 25 pin DSUB Female to MMJ, Filtered
H8571-J PC, Alpha, Integrity 9 pin (DB9) male (PC-
style COM serial port) Note: Cannot be used
on the older MicroVAX DB9 9-pin connector
H8572-0 BC16E MMJ double-female (MMJ extender)
H8575-A EIA232 DB25 25-pin female (common).
Functionally similar to the H8571-A, though
the H8575-A has better ESD shielding.
14-61
Hardware Information
________________________________________________________________
Table 14-8 (Cont.) DECconnect MMJ Connectors and Adapters
_______________________________________________________
Part________Converts_BC16E_MMJ_male_to_fit_into________
H8575-B Older MicroVAX (other than the MicroVAX
2000) DB9 EIA232 serial port. Functionally
similar to the H8571-B, though the H8575-B
has better ESD shielding. Note: Cannot be
used on a PC, Alpha nor Integrity DB9 9-pin
connector
H8575-D 25 Pin to MMJ with better ESD Protection
H8575-D 25 Pin to MMJ with better and ESD
Protection
H8575-E 25 Pin Integrity rx2600 Management
Processor (MP) port to MMJ, with ESD
Protection
H8577-AA 6 pin Female MMJ to 8 pin MJ
BC16E-** MMJ cable with connectors, available in
_____________________various_lengths____________________________
Numerous additional adapters and cables are available
from the (now out of print) OPEN DECconnect Building
Wiring Components and Applications Catalog, as well as
descriptions of the above-listed parts.
The DECconnect wiring system has insufficient signaling
for modems, and particularly lacks support for modem
control signals.
The H8571-A and H8575-A are MMJ to DB25 (female) and
other connector wiring diagrams and adapter-, cable-
and pin-out-related discussions are available at:
o
Jameco has offered a USB-A to PS/2 Mini DIN 6 Adapter
(as part 168751), for those folks wishing to (try to)
use PS/2 Keyboards via USB-A connections.
The LK463 USB keyboard is also a potential option, for
those wishing to connect an OpenVMS keyboard to USB
systems or (via the provided adapter) to PS/2 systems.
The LK463 provides the classic OpenVMS keyboard and
14-62
Hardware Information
keyboard layout on USB-based system configurations,
including operations with the USB connection on
specific Alpha systems (and specifically on those with
supported USB connections) and on Integrity servers.
For information on the Alpha console COM port(s) or on
the VAX console port, please see Section 14.3.
__________________________________________________________
14.28 What is flow control and how does it work?
XON/XOFF is one kind of flow control.
In ASCII, XON is the <CTRL/Q> character, and XOFF is
the <CTRL/S>.
XON/XOFF flow control is typically associated with
asynchronous serial line communications. XON/XOFF is an
in-band flow control, meaning that the flow control is
mixed in with the data.
CTS/RTS is another type of flow control, and is
sometimes called hardware flow control. Out-of-band
means that seperate lines/pins from the data lines
(pins) are used to carry the CTS/RTS signals.
Both kinds of flow control are triggered when a
threshold is reached in the incoming buffer. The flow
control is suppose to reach the transmitter in time to
have it stop transmitting before the receiver buffer is
full and data is lost. Later, after a sufficient amount
of the receiver's buffer is freed up, the resume flow
control signal is sent to get the transmitter going
again.
DECnet Phase IV on OpenVMS VAX supports the use of
asynchronous serial communications as a network
line; of asynch DECnet. The communication devices
(eg. modems, and drivers) must not be configured
for XON/XOFF flow control. The incidence of these
(unexpected) in-band characters will corrupt data
packets. Further, the serial line device drivers
might normally remove the XON and XOFF characters
from the stream for terminal applications, but DECnet
configures the driver to pass all characters through
and requires that all characters be permitted. (The
communication devices must pass through not only the
14-63
Hardware Information
XON and XOFF characters, they must pass all characters
including the 8-bit characters. If data compression is
happening, it must reproduce the source stream exactly.
No addition or elimination of null characters, and full
data transparency.
An Ethernet network is rather different than an
asynchronous serial line. Ethernet specifies the
control of data flow on a shared segment using CSMA/CD
(Carrier Sense Multiple Access, with Collision Detect)
An Ethernet station that is ready to transmit listens
for a clear channel (Carrier Sense). When the channel
is clear, the station begins to transmit by asserting
a carrier and encoding the packet appropriately. The
station concurrently listens to its own signal, to
permit the station to detect if another station began
to transmit at the same time-this is called collision
detection. (The collision corrupts the signal in a
way that can reliably be detected.) Upon detecting the
collision, both stations will stop transmitting, and
will back off and try again a little later. (You can
see a log of this activity in the DECnet NCP network
counters.)
DECnet provides its own flow control, above and beyond
the flow control of the physical layer (if any). The
end nodes handshake at the beginning to establish
a transmit window size-and a transmitter will only
send that much data before stopping and waiting for
an acknowledgement. The acknowledgement is only sent
when the receiver has confirmed the packet is valid. (A
well-configured DECnet generally avoids triggering any
underlying (out-of-band) flow control mechanism.)
__________________________________________________________
14.29 CD and DVD device requirements?
Read access to DVD-ROM, DVD+R/RW, DVD-R/RW, CD-ROM, and
CD-R/RW devices on ATAPI (IDE) connections is generally
handled transparently by SYS$DQDRIVER, and SYS$DQDRIVER
will transparently de-block the media-native 2048
byte disk blocks with the 512-byte blocks expected
by OpenVMS and by native OpenVMS software.
14-64
Hardware Information
Read access to DVD-ROM, DVD+R/RW, DVD-R/RW, CD-ROM, and
CD-R/RW devices on SCSI is handled by DKDRIVER, though
SYS$DKDRIVER will not transparently de-block the native
2048-byte disk blocks into the 512-byte blocks expected
by OpenVMS. The drive or external software is expected
to provide this de-blocking, thus either a 512-byte
block capable drive (such as all RRD-series SCSI CD-ROM
drives) is required, or host software is required for
a 2048-byte block drive. Third-party SCSI drives with
UNIX references in their support documentation or with
explicit 512-byte selectors or swiches will generally
(but not always, of course) operate with OpenVMS.
At least some of the Plextor PlexWriter SCSI drives
can be successfully accessed (for read and write) from
OpenVMS, as can at least one Pioneer SCSI DVD drive
(for CD media). The Pioneer SCSI DVD drive switches
to 2048 byte blocks for DVD media, and a block-size
conversion tool (written by Glenn Everhart) or other
similar tool can be applied.
OpenVMS also has supported HP DVD drives for the ATAPI
(IDE) bus.
For some related information (and details on a
commercial DVDwrite package), please see:
o
hardware.html
No device driver currently presently permits direct
block-oriented recording on DVD-RAM nor DVD+RW media,
nor other recordable or rewritable media.
Recording (writing) of CD and DVD optical media
requires a recording or media mastering application
or tool, and both commercial and non-commercial options
are available. See Section 9.7 for related details on
CDRECORD (both non-DVD and DVD versions are available,
and at least one commercial version is available),
and also see DVDwrite (commercial) or DVDRECORD (open
source).
14-65
Hardware Information
For information on the GKDRIVER (SYS$GKDRIVER)
generic SCSI device driver and of the the IO$_DIAGNOSE
$qio[w] interfaces (of SYS$DKDRIVER, SYS$DNDRIVER and
SYS$DQDRIVER) that are utilized by most CD and DVD
recording tools to send commands to SCSI, USB or ATAPI
devices (most USB and ATA devices-or more correctly,
most ATAPI devices-can use SCSI-like command packets),
please see the SYS$EXAMPLES:GKTEST.C example, and see
DECW$EXAMPLES:DECW$CDPLAYER.C example and please see
the various associated sections of the OpenVMS I/O
User's Reference Manual.
For information on creating bootable optical media on
OpenVMS, please see Section 9.7.3.
14-66
_______________________________________________________
15 Information on Networks and Clusters
The following sections contain information on OpenVMS
Networking with IP and DECnet, and on clustering and
volume shadowing, on Fibre Channel, and on related
products and configurations.
__________________________________________________________
15.1 How to connect OpenVMS to a Modem?
Please see the Ask The Wizard area topics starting with
(81), (1839), (2177), (3605), etc.
o
For additional information on the OpenVMS Ask The
Wizard (ATW) area and for a pointer to the available
ATW Wizard.zip archive, please see Section 3.8.
__________________________________________________________
15.2 OpenVMS and IP Networking?
The following sections contain information on OpenVMS
and IP networking, as well as IP printing topics.
_____________________________
15.2.1 How to connect OpenVMS to the Internet?
Some tutorial information and tips for connecting
OpenVMS systems to the Internet are available at:
o
_____________________________
15.2.2 Connecting to an IP Printer?
To connect a printer via the IP telnet or lpr/lpd
protocols, you will need to install and configure an IP
stack on OpenVMS, and configure the appropriate print
queue.
15-1
Information on Networks and Clusters
With current OpenVMS IP implementations, the choice
of telnet or lpr/lpd really amounts to determining
which of these works better with the particular printer
involved.
To support network printing, the printer must include
an internal or external NIC or JetDirect; an adapter
connecting the network and the printer.
While it is normally possible to use a host-connected
printer-when the host supports an LPD or telnet daemon,
and OpenVMS and most other operating systems have the
ability to serve locally-attached printers to other
hosts on the network-it is generally far easier and
far more effective to use a printer that is directly
attached to the network. If your present printer does
not have a NIC or a JetDirect, acquire an internal (if
available) or external NIC or JetDirect. Or replace the
printer. And obviously, most any operating system that
can serve its local printers usually also provides
a client that can access remote network-connected
printers.
Please see the Ask The Wizard (ATW) area topics-
starting with topic (1020)-for additional information
on IP-based network printing.
o
For additional information on the OpenVMS Ask The
Wizard (ATW) area and for a pointer to the available
ATW Wizard.zip archive, please see Section 3.8.
Please see Section 15.2.3 for information on Postscript
printing.
_____________________________
15.2.3 How do I connect a PostScript printer via TCP/IP?
Using TCP/IP Services (UCX) as the TCP/IP stack, it is
possible to configure queues using the UCX$TELNETSYM
(TCP/IP Services prior to V5.0) or TCPIP$TELNETSYM
(with V5.0 and later) in order to print to Postscript
printers. This assumes however that the printer itself
can convert whatever is passed to it into something
intelligible. As an example, if the printer has an IP
15-2
Information on Networks and Clusters
address of 123.456.789.101 and jobs should be passed to
port 9100 then :
$ INITIALIZE/QUEUE/ON="123.456.789.101:9100" -
/PROCESSOR=UCX$TELNETSYM -
my_ip_queue
$ INITIALIZE/QUEUE/ON="123.456.789.101:9100" -
/PROCESSOR=TCPIP$TELNETSYM -
my_ip_queue
The port number of 9100 is typical of HP JetDirect
cards but may be different for other manufacturers
cards.
As a better alternative, DCPS Version 1.4 and later
support IP queues using either HP TCP/IP Services
for OpenVMS software or Process Software Multinet
for OpenVMS. The usage of this type of interface is
documented in the DCPS documentation or release notes,
and the DCPS$STARTUP.TEMPLATE startup template file.
For general and additional (non-Postscript) IP printing
information, please see topic (1020) and other topics
referenced in that topic elsewhere within the Ask The
Wizard area.
o
For additional information on the OpenVMS Ask The
Wizard (ATW) area and for a pointer to the available
ATW Wizard.zip archive, please see Section 3.8. Also
see:
o
Please see Section 15.2.2 for pointers to an
introduction to IP printing.
_____________________________
15.2.4 How do I set a default IP route or gateway on OpenVMS?
If you have TCP/IP Services, then use the command for
TCP/IP Services V5.0 and later:
$ TCPIP
SET ROUTE/GATE=x.x.x.x/DEFAULT/PERMANENT
15-3
Information on Networks and Clusters
And for earlier TCP/IP Services versions, use the
command:
$ UCX
SET ROUTE/GATE=x.x.x.x/DEFAULT/PERMANENT
_____________________________
15.2.5 How can I set up reverse telnet (like reverse LAT)?
Though it may seem obvious, Telnet and LAT are quite
different-with differing capabilities and design goals.
Please see the documentation around the TCP/IP Services
for OpenVMS TELNET command CREATE_SESSION. This command
is the equivilent of the operations performed in
LTLOAD.COM or LAT$SYSTARTUP.COM. There is no TELNET
equivilent to the sys$qio[w] control interface for
LTDRIVER (as documented in the I/O User's Reference
Manual) available, though standard sys$qio[w] calls
referencing the created TN device would likely operate
as expected.
_____________________________
15.2.6 Why can't I use PPP and RAS to connect to OpenVMS Alpha?
OpenVMS Alpha IP PPP does not presently support
authentication, and the Microsoft Windows NT option
to disable authentication during a RAS connection
apparently doesn't currently work-RAS connections will
require authentication-and this will thus prevent RAS
connections.
Future versions of OpenVMS and TCP/IP Services may
add this, and future versions of Microsoft Windows may
permit operations with authentication disabled.
__________________________________________________________
15.3 OpenVMS and DECnet Networking?
The following sections contain information on OpenVMS
and DECnet networking.
15-4
Information on Networks and Clusters
_____________________________
15.3.1 Can DECnet-Plus operate over IP?
Yes. To configure DECnet-Plus to operate over IP
transport and over IP backbone networks, install and
configure DECnet-Plus, and install and configure the
PWIP mechanism available within the currently-installed
IP stack. Within TCP/IP Services, this is a PWIPDRIVER
configuration option within the UCX$CONFIG (versions
prior to V5.0) or TCPIP$CONFIG (with V5.0 and later)
configuration tool.
_____________________________
15.3.2 What does "failure on back translate address request"
mean?
The error message:
BCKTRNSFAIL, failure on the back translate address request
indicates that the destination node is running DECnet-
Plus, and that its naming service (DECnet-Plus DECdns,
LOCAL node database, etc) cannot locate a name to
associate with the source node's address. In other
words, the destination node cannot determine the node
name for the node that is the source of the incoming
connection.
Use the DECNET_REGISTER mechanism (on the destination
node) to register or modify the name(s) and the
address(es) of the source node. Check the namespace
on the source node, as well.
Typically, the nodes involved are using a LOCAL
namespace, and the node name and address settings are
not coherent across all nodes. Also check to make sure
that the node is entered into its own LOCAL namespace.
This can be a problem elsewhere, however. Very rarely,
a cache corruption has been known to cause this error.
To flush the cache, use the command:
$ RUN SYS$SYSTEM:NCL
flush session control naming cache entry "*"
15-5
Information on Networks and Clusters
Also check to see that you are using the latest ECO for
DECnet-Plus for the version you are running. DECnet-
Plus can use the following namespaces:
o DECdns: DECnet-Plus distributed name services.
o LocalFile: a local file containing names and
addresses.
o DNS/BIND: the TCP/IP distributed name services
mechanism.
o The TCP/IP Services (UCX) local host file.
Of these, searching DNS/BIND and LocalFile,
respectively, is often the most appropriate
configuration.
_____________________________
15.3.3 Performing SET HOST/MOP in DECnet-Plus?
First, issue the NCL command SHOW MOP CIRCUIT *
$ RUN SYS$SYSTEM:NCL
SHOW MOP CIRCUIT *
Assume that you have a circuit known as FDDI-0
displayed. Here is an example of the SET HOST/MOP
command syntax utilized for this circuit:
$ SET HOST/MOP/ADDRESS=08-00-2B-2C-5A-23/CIRCUIT=FDDI-0
Also see Section 15.6.3.
_____________________________
15.3.4 How to flush the DECnet-Plus session cache?
$ RUN SYS$SYSTEM:NCL
FLUSH SESSION CONTROL NAMING CACHE ENTRY "*"
__________________________________________________________
15.4 How to determine the network hardware address?
Most Alpha and most VAX systems have a console command
that displays the network hardware address. Many
systems will also have a sticker identifying the
address, either on the enclosure or on the network
controller itself.
15-6
Information on Networks and Clusters
The system console power-up messages on a number of VAX
and Alpha systems will display the hardware address,
particularly on those systems with an integrated
Ethernet network adapter present.
If you cannot locate a sticker on the system, if
the system powerup message is unavailable or does
not display the address, and if the system is at the
console prompt, start with the console command:
A console command similar to one of the following is
typically used to display the hardware address:
SHOW DEVICE
SHOW ETHERNET
SHOW CONFIG
On the oldest VAX Q-bus systems, the following console
command can be used to read the address directly off
the (DELQA, DESQA, or the not-supported-in-V5.5-and-
later DEQNA) Ethernet controller:
E/P/W/N:5 20001920
Look at the low byte of the six words displayed by
the above command. (The oldest VAX Q-bus systems-such
as the KA630 processor module used on the MicroVAX II
and VAXstation II series-lack a console HELP command,
and these systems typically have the primary network
controller installed such that the hardware address
value is located at the system physical address
20001920.)
If the system is a VAX system, and another VAX system
on the network is configured to answer Maintenance
and Operations Protocol (MOP) bootstrap requests
(via DECnet Phase IV, DECnet-Plus, or LANCP), the
MOM$SYSTEM:READ_ADDR.EXE tool can be requested:
B/R5:100 ddcu
Bootfile: READ_ADDR
15-7
Information on Networks and Clusters
Where ddcu is the name of the Ethernet controller in
the above command. The primarly local DELQA, DESQA,
and DEQNA Q-bus controllers are usually named XQA0.
An attempt to MOP download the READ_ADDR program will
ensue, and (if the download is successful) READ_ADDR
will display the hardware address.
If the system is running, you can use DECnet or
TCP/IP to display the hardware address with one of
the following commands.
$! DECnet Phase IV
$ RUN SYS$SYSTEM:NCP
SHOW KNOWN LINE CHARACTERISTICS
$! DECnet-Plus
$ RUN SYS$SYSTEM:NCL
SHOW CSMA-CD STATION * ALL STATUS
$! TCP/IP versions prior to V5.0
$ UCX
SHOW INTERFACE/FULL
$! TCP/IP versions V5.0 and later
$ TCPIP
SHOW INTERFACE/FULL
A program can be created to display the hardware
address, reading the necessary information from
the network device drivers. A complete example C
program for reading the Ethernet or IEEE 802.3 network
controller hardware address (via sys$qio calls to the
OpenVMS network device driver(s)) is available at the
following URL:
o
To use the DECnet Phase IV configurator tool to watch
for MOP SYSID activity on the local area network:
$ RUN SYS$SYSTEM:NCP
SET MODULE CONFIGURATOR KNOWN CIRCUIT SURVEILLANCE ENABLED
15-8
Information on Networks and Clusters
Let the DECnet Phase IV configurator run for at least
20 minutes, and preferably longer. Then issue the
following commands:
$ RUN SYS$SYSTEM:NCP
SHOW MODULE CONFIGURATOR KNOWN CIRCUIT STATUS TO filename.txt
SET MODULE CONFIGURATOR KNOWN CIRCUIT SURVEILLANCE DISABLED
The resulting file (named filename.txt) can now be
searched for the information of interest. Most DECnet
systems will generate MOP SYSID messages identifying
items such as the controller hardware address and the
controller type, and these messages are generated and
multicast roughly every ten minutes.
Information on the DECnet MOP SYSID messages and other
parts of the maintenance protocols is included in the
DECnet network architecture specifications referenced
in section DOC9.
_____________________________
15.4.1 How do I reset the LAN (DECnet-Plus NCL) error counters?
On recent OpenVMS releases:
$ RUN SYS$SYSTEM:LANCP
SET DEVICE/DEVICE_SPECIFIC=FUNCTION="CCOU" devname
_____________________________
15.4.2 How do I install DECnet Phase IV on VMS 7.1?
On OpenVMS V7.1, all DECnet binaries were relocated
into separate installation kits-you can selectively
install the appropriate network: DECnet-Plus (formerly
known as DECnet OSI), DECnet Phase IV, and HP TCP/IP
Services (often known as UCX).
On OpenVMS versions prior to V7.1, DECnet Phase IV was
integrated, and there was no installation question. You
had to install the DECnet-Plus (DECnet/OSI) package on
the system, after the OpenVMS upgrade or installation
completed.
15-9
Information on Networks and Clusters
During an OpenVMS V7.1 installation or upgrade, the
installation procedure will query you to learn if
DECnet-Plus should be installed. If you are upgrading
to V7.1 from an earlier release or are installing V7.1
from a distribution kit, simply answer "NO" to the
question asking you if you want DECnet-Plus. Then-after
the OpenVMS upgrade or installation completes - use
the PCSI PRODUCT INSTALL command to install the DECnet
Phase IV binaries from the kit provided on the OpenVMS
software distribution kit.
If you already have DECnet-Plus installed and wish
to revert, you must reconfigure OpenVMS. You cannot
reconfigure the "live" system, hence you must reboot
the system using the V7.1 distribution CD-ROM. Then
select the DCL ($$$ prompt) option. Then issue the
commands:
$$$ DEFINE/SYSTEM PCSI$SYSDEVICE DKA0:
$$$ DEFINE/SYSTEM PCSI$SPECIFIC DKA0:[SYS0.]
$$$ PRODUCT RECONFIGURE VMS /REMOTE/SOURCE=DKA0:[VMS$COMMON]
The above commands assume that the target system device
and system root are "DKA0:[SYS0.]". Replace this with
the actual target device and root, as appropriate.
The RECONFIGURE command will then issue a series of
prompts. You will want to reconfigure DECnet-Plus off
the system, obviously. You will then want to use the
PCSI command PRODUCT INSTALL to install the DECnet
Phase IV kit from the OpenVMS distribution media.
Information on DECnet support, and on the kit names, is
included in the OpenVMS V7.1 installation and upgrade
documentation.
Subsequent OpenVMS upgrade and installation procedures
can and do offer both DECnet Phase IV and DECnet-Plus
installations.
15-10
Information on Networks and Clusters
__________________________________________________________
15.5 How can I send (radio) pages from my OpenVMS system?
There are third-party products available to
send messages to radio paging devices (pagers),
communicating via various protocols such as TAP
(Telocator Alphanumeric Protocol); paging packages.
RamPage (Ergonomic Solutions) is one of the available
packages that can generate and transmit messages to
radio pagers. Target Alert (Target Systems; formerly
the DECalert product) is another. Networking Dynamics
Corp has a product called Pager Plus. The System
Watchdog package can also send pages. The Process
Software package PMDF can route specific email
addresses to a paging service, as well.
Many commercial paging services provide email contact
addresses for their paging customers-you can simply
send or forward email directly to the email address
assigned to the pager.
Some people implement the sending of pages to radio
pagers by sending commands to a modem to take the
"phone" off the "hook", and then the paging sequence,
followed by a delay, and then the same number that a
human would dial to send a numeric page. (This is not
entirely reliable, as the modem lacks "call progress
detection", and the program could simply send the
dial sequence when not really connected to the paging
company's telephone-based dial-up receiver.)
See Section 13.1 for information on the available
catalog of products.
__________________________________________________________
15.6 OpenVMS, Clusters, Volume Shadowing?
The following sections contain information on OpenVMS
and Clusters, Volume Shadowing, and Cluster-related
system parameters.
15-11
Information on Networks and Clusters
_____________________________
15.6.1 OpenVMS Cluster Communications Protocol Details?
The following sections contain information on the
OpenVMS System Communications Services (SCS) Protocol.
Cluster terminology is available in Section 15.6.1.2.1.
_____________________________
15.6.1.1 OpenVMS Cluster (SCS) over DECnet? Over IP?
The OpenVMS Cluster environment operates over various
network protocols, but the core of clustering uses
the System Communications Services (SCS) protocols,
and SCS-specific network datagrams. Direct (full)
connectivity is assumed.
An OpenVMS Cluster does not operate over DECnet, nor
over IP.
No SCS protocol routers are available.
Many folks have suggested operating SCS over DECnet
or IP over the years, but SCS is too far down in
the layers, and any such project would entail a
major or complete rewrite of SCS and of the DECnet
or IP drivers. Further, the current DECnet and IP
implementations have large tracts of code that operate
at the application level, while SCS must operate in
the rather more primitive contexts of the system and
particularly the bootstrap-to get SCS to operate over a
DECnet or IP connection would require relocating major
portions of the DECnet or IP stack into the kernel.
(And it is not clear that the result would even meet
the bandwidth and latency expectations.)
The usual approach for multi-site OpenVMS Cluster
configurations involves FDDI, Memory Channel (MC2), or
a point-to-point remote bridge, brouter, or switch. The
connection must be transparent, and it must operate at
10 megabits per second or better (Ethernet speed), with
latency characteristics similar to that of Ethernet or
better. Various sites use FDDI, MC2, ATM, or point-to-
point T3 link.
15-12
Information on Networks and Clusters
_____________________________
15.6.1.2 Configuring Cluster SCS for path load balancing?
This section discusses OpenVMS Cluster communications,
cluster terminology, related utilities, and command and
control interfaces.
_____________________________
15.6.1.2.1 Cluster Terminology?
SCS: Systems Communication Services. The protocol used
to communicate between VMSCluster systems and between
OpenVMS systems and SCS-based storage controllers.
(SCSI-based storage controllers do not use SCS.)
PORT: A communications device, such as DSSI, CI,
Ethernet or FDDI. Each CI or DSSI bus is a different
local port, named PAA0, PAB0, PAC0 etc. All Ethernet
and FDDI busses make up a single PEA0 port.
VIRTUAL CIRCUIT: A reliable communications path
established between a pair of ports. Each port in a
VMScluster establishes a virtual circuit with every
other port in that cluster.
All systems and storage controllers establish "Virtual
Circuits" to enable communications between all
available pairs of ports.
SYSAP: A "system application" that communicates using
SCS. Each SYSAP communicates with a particular remote
SYSAP. Example SYSAPs include:
VMS$DISK_CL_DRIVER connects to MSCP$DISK
The disk class driver is on every VMSCluster system.
MSCP$DISK is on all disk controllers and all VMSCluster
systems that have SYSGEN parameter MSCP_LOAD set to 1
VMS$TAPE_CL_DRIVER connects to MSCP$TAPE
The tape class driver is on every VMSCluster system.
MSCP$TAPE is on all tape controllers and all VMSCluster
systems that have SYSGEN parameter TMSCP_LOAD set to 1
VMS$VAXCLUSTER connects to VMS$VAXCLUSTER
This SYSAP contains the connection manager, which
manages cluster connectivity, runs the cluster state
transition algorithm, and implements the cluster quorum
15-13
Information on Networks and Clusters
algorithm. This SYSAP also handles lock traffic, and
various other cluster communications functions.
SCS$DIR_LOOKUP connects to SCS$DIRECTORY
This SYSAP is used to find SYSAPs on remote systems
MSCP and TMSCP
The Mass Storage Control Protocol and the Tape MSCP
servers are SYSAPs that provide access to disk and
tape storage, typically operating over SCS protocols.
MSCP and TMSCP SYSAPs exist within OpenVMS (for OpenVMS
hosts serving disks and tapes), within CI- and DSSI-
based storage controllers, and within host-based MSCP-
or TMSCP storage controllers. MSCP and TMSCP can be
used to serve MSCP and TMSCP storage devices, and can
also be used to serve SCSI and other non-MSCP/non-TMSCP
storage devices.
SCS CONNECTION: A SYSAP on one node establishes an SCS
connection to its counterpart on another node. This
connection will be on ONE AND ONLY ONE of the available
virtual circuits.
_____________________________
15.6.1.2.2 Cluster Communications Control?
When there are multiple virtual circuits between two
OpenVMS systems it is possible for the VMS$VAXCLUSTER
to VMS$VAXCLUSTER connection to use any one of these
circuits. All lock traffic between the two systems will
then travel on the selected virtual circuit.
Each port has a "LOAD CLASS" associated with it. This
load class helps to determine which virtual circuit
a connection will use. If one port has a higher load
class than all others then this port will be used. If
two or more ports have equally high load classes then
the connection will use the first of these that it
finds. Prior to enhancements found in V7.3-1 and later,
the load class is static and normally all CI and DSSI
ports have a load class of 14(hex), while the Ethernet
and FDDI ports will have a load class of A(hex). With
V7.3-1 and later, the load class values are dynamic.
15-14
Information on Networks and Clusters
For instance, if you have multiple DSSI busses and
an FDDI, the VMS$VAXCLUSTER connection will chose the
DSSI bus as this path has the system disk, and thus
will always be the first DSSI bus discovered when the
OpenVMS system boots.
To force all lock traffic off the DSSI and on to
the FDDI, for instance, an adjustment to the load
class value is required, or the DSSI SCS port must
be disabled.
In addition to the load class mechanisms, you can
also use the "preferred path" mechanisms of MSCP
and TMSCP services. This allows you to control the
SCS connections used for serving remote disk and tape
storage. The preferred path mechanism is most commonly
used to explicitly spread cluster I/O activity over
hosts and/or storage controllers serving disk or tape
storage in parallel. This can be particularly useful if
your hosts or storage controllers individually lack the
necessary I/O bandwidth for the current I/O load, and
must thus aggregate bandwidth to serve the cluster I/O
load.
For related tools, see various utilities including
LAVC$STOP_BUS and LAVC$START_BUS, and see DCL commands
including SET PREFERRED_PATH.
_____________________________
15.6.1.2.3 Cluster Communications Control Tools and Utilities?
In most OpenVMS versions, you can use the tools:
o SYS$EXAMPLES:LAVC$STOP_BUS
o SYS$EXAMPLES:LAVC$START_BUS
These tools permit you to disable or enable all SCS
traffic on the on the specified paths.
You can also use a preferred path mechanism that tells
the local MSCP disk class driver (DUDRIVER) which path
to a disk should be used. Generally, this is used with
dual-pathed disks, forcing I/O traffic through one of
the controllers instead of the other. This can be used
15-15
Information on Networks and Clusters
to implement a crude form of I/O load balancing at the
disk I/O level.
Prior to V7.2, the preferred path feature uses the
tool:
o SYS$EXAMPLES:PREFER.MAR
In OpenVMS V7.2 and later, you can use the following
DCL command:
$ SET PREFERRED_PATH
The preferred path mechanism does not disable nor
affect SCS operations on the non-preferred path.
With OpenVMS V7.3 and later, please see the SCACP
utility for control over cluster communications, SCS
virtual circuit control, port selection, and related.
_____________________________
15.6.2 Cluster System Parameter Settings?
The following sections contain details of configuring
cluster-related system parameters.
_____________________________
15.6.2.1 What is the correct value for EXPECTED_VOTES in a
VMScluster?
The VMScluster connection manager uses the concept
of votes and quorum to prevent disk and memory data
corruptions-when sufficient votes are present for
quorum, then access to resources is permitted. When
sufficient votes are not present, user activity will be
blocked. The act of blocking user activity is called
a "quorum hang", and is better thought of as a "user
data integrity interlock". This mechanism is designed
to prevent a partitioned VMScluster, and the resultant
massive disk data corruptions. The quorum mechanism is
expressly intended to prevent your data from becoming
severely corrupted.
15-16
Information on Networks and Clusters
On each OpenVMS node in a VMScluster, one sets two
values in SYSGEN: VOTES, and EXPECTED_VOTES. The
former is how many votes the node contributes to the
VMScluster. The latter is the total number of votes
expected when the full VMScluster is bootstrapped.
Some sites erroneously attempt to set EXPECTED_VOTES
too low, believing that this will allow when only a
subset of voting nodes are present in a VMScluster. It
does not. Further, an erroneous setting in EXPECTED_
VOTES is automatically corrected once VMScluster
connections to other nodes are established; user data
is at risk of severe corruptions during the earliest
and most vulnerable portion of the system bootstrap,
before the connections have been established.
One can operate a VMScluster with one, two, or many
voting nodes. With any but the two-node configuration,
keeping a subset of the nodes active when some nodes
fail can be easily configured. With the two-node
configuration, one must use a primary-secondary
configuration (where the primary has all the votes), a
peer configuration (where when either node is down, the
other hangs), or (preferable) a shared quorum disk.
Use of a quorum disk does slow down VMScluster
transitions somewhat - the addition of a third
voting node that contributes the vote(s) that would
be assigned to the quorum disk makes for faster
transitions-but the use of a quorum disk does mean
that either node in a two-node VMScluster configuration
can operate when the other node is down.
Note
The quorum disk must be on a non-host-based
shadowed disk, though it can be protected
with controller-based RAID. Because host-based
volume shadowing depends on the lock manager
and the lock manager depends on the connection
manager and the connection manager depends on
quorum, it is not technically feasible (nor
even particularly reliable) to permit host-based
volume shadowing to protect the quorum disk.
15-17
Information on Networks and Clusters
If you choose to use a quoum disk, a QUORUM.DAT file
will be automatically created when OpenVMS first
boots and when a quorum disk is specified - well, the
QUORUM.DAT file will be created when OpenVMS is booted
without also needing the votes from the quorum disk.
In a two-node VMScluster with a shared storage
interconnect, typically each node has one vote, and
the quorum disk also has one vote. EXPECTED_VOTES is
set to three.
Using a quorum disk on a non-shared interconnect is
unnecessary-the use of a quorum disk does not provide
any value, and the votes assigned to the quorum disk
should be assigned to the OpenVMS host serving access
to the disk.
For information on quorum hangs, see the OpenVMS
documentation. For information on changing the
EXPECTED_VOTES value on a running system, see the
SET CLUSTER/EXPECTED_VOTES command, and see the
documentation for the AMDS and Availability Manager
tools. Also of potential interest is the OpenVMS
system console documentation for the processor-specific
console commands used to trigger the IPC (Interrrupt
Priority Level %x0C; IPL C) handler. (IPC is not
available on OpenVMS I64 V8.2.) AMDS, Availability
Manager, and the IPC handler can each be used to
clear a quorum hang. Use of AMDS and Availability
Manager is generally recommended over IPC, particularly
because IPC can cause CLUEXIT bugchecks if the system
should remain halted beyond the cluster sanity timer
limits, and because some Alpha consoles and most (all?)
Integrity consoles do not permit a restart after a
halt.
The quorum scheme is a set of "blade guards"
deliberately implemented by OpenVMS Engineering to
provide data integrity-remove these blade guards at
your peril. OpenVMS Engineering did not implement
the quorum mechanism to make a system manager's life
more difficult- the quorum mechanism was specifically
implemented to keep your data from getting scrambled.
15-18
Information on Networks and Clusters
_____________________________
15.6.2.1.1 Why no shadowing for a Quorum Disk?
Stated simply, Host-Based Volume Shadowing uses the
Distributed Lock Manager (DLM) to coordinate changes to
membership of a shadowset (e.g. removing a member).
The DLM depends in turn on the Connection Manager
enforcing the Quorum Scheme and deciding which node(s)
(and quorum disk) are participating in the cluster, and
telling the DLM when it needs to do things like a lock
database rebuild operation. So you can't introduce a
dependency of the Connection Manager on Shadowing to
try to pick proper shadowset member(s) to use as the
Quorum Disk when Shadowing itself is using the DLM and
thus indirectly depending on the Connection Manager to
keep the cluster membership straight-it's a circular
dependency.
So in practice, folks simply depend on controller-
based mirroring (or controller-based RAID) to protect
the Quorum Disk against disk failures (and dual-
redundant controllers to protect against most cases
of controller and interconnect failures). Since this
disk unit appears to be a single disk up at the VMS
level, there's no chance of ambiguity.
_____________________________
15.6.2.2 Explain disk (or tape) allocation class settings?
The allocation class mechanism provides the system
manager with a way to configure and resolve served and
direct paths to storage devices within a cluster. Any
served device that provides multiple paths should be
configured using a non-zero allocation class, either
at the MSCP (or TMSCP) storage controllers, at the
port (for port allocation classes), or at the OpenVMS
MSCP (or TMSCP) server. All controllers or servers
providing a path to the same device should have the
same allocation class (at the port, controller, or
server level).
Each disk (or tape) unit number used within a non-
zero disk (or tape) allocation class must be unique,
regardless of the particular device prefix. For the
purposes of multi-path device path determination, any
disk (or tape) device with the same unit number and the
15-19
Information on Networks and Clusters
same disk (or tape) allocation class configuration is
assumed to be the same device.
If you are reconfiguring disk device allocation
classes, you will want to avoid the use of allocation
class one ($1$) until/unless you have Fibre Channel
storage configured. (Fibre Channel storage specifically
requires the use of allocation class $1$. eg:
$1$DGA0:.)
_____________________________
15.6.2.2.1 How to configure allocation classes and Multi-Path
SCSI?
The HSZ allocation class is applied to devices,
starting with OpenVMS V7.2. It is considered a port
allocation class (PAC), and all device names with a PAC
have their controller letter forced to "A". (You might
infer from the the text in the "Guidelines for OpenVMS
Cluster Configurations" that this is something you have
to do, though OpenVMS will thoughtfully handle this
renaming for you.)
You can force the device names back to DKB by setting
the HSZ allocation class to zero, and setting the PKB
PAC to -1. This will use the host allocation class, and
will leave the controller letter alone (that is, the
DK controller letter will be the same as the SCSI port
(PK) controller). Note that this won't work if the HSZ
is configured in multibus failover mode. In this case,
OpenVMS requires that you use an allocation class for
the HSZ.
When your configuration gets even moderately complex,
you must pay careful attention to how you assign
the three kinds of allocation class: node, port and
HSZ/HSJ, as otherwise you could wind up with device
naming conflicts that can be painful to resolve.
The display-able path information is for SCSI
multi-path, and permits the multi-path software to
distinguish between different paths to the same device.
If you have two paths to $1$DKA100, for example by
having two KZPBA controllers and two SCSI buses to the
HSZ, you would have two UCBs in a multi-path set. The
15-20
Information on Networks and Clusters
path information is used by the multi-path software to
distinguish between these two UCBs.
The displayable path information describes the path;
in this case, the SCSI port. If port is PKB, that's
the path name you get. The device name is no longer
completely tied to the port name; the device name now
depends on the various allocation class settings of the
controller, SCSI port or node.
The reason the device name's controller letter is
forced to "A" when you use PACs is because a shared
SCSI bus may be configured via different ports on the
various nodes connected to the bus. The port may be PKB
on one node, and PKC on the other. Rather obviously,
you will want to have the shared devices use the same
device names on all nodes. To establish this, you
will assign the same PAC on each node, and OpenVMS
will force the controller letter to be the same on
each node. Simply choosing "A" was easier and more
deterministic than negotiating the controller letter
between the nodes, and also parallels the solution used
for this situation when DSSI or SDI/STI storage was
used.
To enable port allocation classes, see the SYSBOOT
command SET/BOOT, and see the DEVICE_NAMING system
parameter.
This information is also described in the Cluster
Systems and Guidelines for OpenVMS Cluster
Configurations manuals.
_____________________________
15.6.3 Tell me about SET HOST/DUP and SET HOST/HSC
The OpenVMS DCL commands SET HOST/DUP and SET HOST/HSC
are used to connect to storage controllers via the
Diagnostics and Utility Protocol (DUP). These commands
require that the FYDRIVER device driver be connected.
This device driver connection is typically performed by
adding the following command(s) into the system startup
command procedure:
15-21
Information on Networks and Clusters
On OpenVMS Alpha:
$ RUN SYS$SYSTEM:SYSMAN
SYSMAN> IO CONNECT FYA0/NOADAPTER/DRIVER=SYS$FYDRIVER
On OpenVMS VAX:
$ RUN SYS$SYSTEM:SYSGEN
SYSGEN> CONNECT FYA0/NOADAPTER
Alternatives to the DCL SET HOST/DUP command include
the console SET HOST command available on various mid-
to recent-vintage VAX consoles:
Access to Parameters on an Embedded DSSI controller:
SET HOST/DUP/DSSI[/BUS:{0:1}] dssi_node_number PARAMS
Access to Directory of tools on an Embedded DSSI
controller:
SET HOST/DUP/DSSI[/BUS:{0:1}] dssi_node_number DIRECT
Access to Parameters on a KFQSA DSSI controller:
SHOW UQSSP ! to get port_controller_number PARAMS
SET HOST/DUP/UQSSP port_controller_number PARAMS
These console commands are available on most MicroVAX
and VAXstation 3xxx series systems, and most (all?) VAX
4xxx series systems. For further information, see the
system documentation and-on most VAX systems-see the
console HELP text.
EK-410AB-MG, _DSSI VAXcluster Installation and
Troubleshooting_, is a good resource for setting
up a DSSI VMScluster on OpenVMS VAX nodes. (This
manual predates coverage of OpenVMS Alpha systems,
but gives good coverage to all hardware and software
aspects of setting up a DSSI-based VMScluster-and most
of the concepts covered are directly applicable to
OpenVMS Alpha systems. This manual specifically covers
the hardware, which is something not covered by the
standard OpenVMS VMScluster documentation.)
Also see Section 15.3.3, and for the SCS name of the
OpenVMS host see Section 5.7.
15-22
Information on Networks and Clusters
_____________________________
15.6.4 How do I rename a DSSI disk (or tape?)
If you want to renumber or rename DSSI disks or DSSI
tapes, it's easy-if you know the secret incantation...
From OpenVMS:
$ RUN SYS$SYSTEM:SYSGEN
SYSGEN> CONNECT FYA0/NOADAPTER
SYSGEN> ^Z
$ SET HOST/DUP/SERV=MSCP$DUP/TASK=PARAMS <DSSI-NODE-NAME>
...
PARAMS> STAT CONF
<The software version is normally near the top of the display.>
PARAMS> EXIT
...
From the console on most 3000- and 4000-class VAX
system consoles... (Obviously, the system must be
halted for these commands...)
Integrated DSSI:
SET HOST/DUP/DSSI[/BUS:[0:1]] dssi_node_number PARAMS
KFQSA:
SET HOST/DUP/UQSSP port_controller_number PARAMS
For information on how to get out into the PARAMS
subsystem, also see the HELP at the console prompt
for the SET HOST syntax, or see the HELP on SET HOST
/DUP (once you've connected FYDRIVER under OpenVMS).
Once you are out into the PARAMS subsystem, you can
use the FORCEUNI option to force the use of the UNITNUM
value and then set a unique UNITNUM inside each DSSI
ISE-this causes each DSSI ISE to use the specfied unit
number and not use the DSSI node as the unit number.
Other parameters of interest are NODENAME and ALLCLASS,
the node name and the (disk or tape) cluster allocation
class.
Ensure that all disk unit numbers used within an
OpenVMS Cluster disk allocation class are unique, and
all tape unit numbers used within an OpenVMS Cluster
tape allocation class are also unique. For details on
15-23
---------------------------- #include <rtfaq.h> -----------------------------
For additional, please see the OpenVMS FAQ --
--------------------------- pure personal opinion ---------------------------
Hoff (Stephen) Hoffman OpenVMS Engineering hoff[at]hp.com
[ Usenet FAQs | Web FAQs | Documents | RFC Index ] | http://www.faqs.org/faqs/dec-faq/vms/part10/ | CC-MAIN-2017-26 | refinedweb | 9,077 | 53.21 |
Wählen Sie eine Sprache
Red Hat Blog
Blog menu
The concept to save (i.e. checkpoint / dump) the state of a process, at a certain point in time, so that it may later be used to restore / restart the process (to the exact same state) has existed for many years. One of the most prominent motivations to develop and support checkpoint/restore functionality was to provide improved fault tolerance. For example, checkpoint/restore allows for processes to be restored from previously created checkpoints if, for one reason or another, these processes had been aborted.
Over the years there have been several different implementations of checkpoint/restore for Linux. Existing implementations of checkpoint/restore differ in terms of “what level” (of the operating system) they are operating; the lowest level approaches focus on implementing checkpoint/restore directly in the kernel while other “higher level” approaches implement checkpoint/restore completely in user-space. While it would be difficult to unearth each and every approach / implementation - it is likely fair to
assume that the various permutations of checkpoint/restore have covered nearly all possible "levels" (i.e. from “completely in kernel” to “completely in user-space”).
Checkpoint/Restore in Linux
The closer to the kernel the checkpoint/restore is implemented - the more transparent it can be. What does “more transparent” mean? More transparent means that it has less requirements on the processes being checkpointed. For example, requirements can include things like: pre-loading special libraries (which could then be used to intercept system calls). It can also mean that an application has to be re-compiled to be able to be checkpointed. These kinds of pre-requisites make the usage of a checkpoint/restore implementation more difficult as it means that before starting some processes it must already be known if these processes will ever be checkpointed (...at some arbitrary point in “the future”).
Full transparency would likely be difficult to implement as it could require massive changes in the Linux kernel and such changes would have to be accepted by the Linux kernel community.
So... after many approaches to implement checkpoint/restore... a new approach started in 2011. This approach was named Checkpoint/Restore in Userspace (CRIU) and although it is named "in Userspace" it actually is both the user space and the kernel space. CRIU uses existing Linux kernel interfaces as far as possible; only extending existing interfaces / introducing new interfaces as needed. These required changes were (thankfully) all accepted by the Linux kernel community as most could also be used in other cases were more detailed information about a running process could be useful.
CRIU
When CRIU is used to checkpoint a process it uses the existing and extended interfaces to the Linux kernel to collect as much information about the process. Using the PTRACE interface CRIU takes control over the process (CRIU actually always operates on a process tree; one process and all its child processes) and pauses that process. In the next step code is injected via PTRACE in the paused process. CRIU calls this code parasite-code. The parasite-code then runs from within the process's address space and can access and dump/save/checkpoint the memory content of the process. Once all memory pages and all additional information have been collected (and possibly written to a directory) the process can either continue running or it can be aborted. Letting the process continue to run is something to expect in a fault tolerance scenario - to migrate a process to another system the process would be aborted.
To restore a process CRIU transforms the CRIU process doing the restore into the process to be restored. The is one of the places where CRIU uses a newly introduced Linux kernel interface. With CRIU a process can only be restored with the same process identifier (PID) the process had during checkpoint. To influence which PID the restored process gets, CRIU writes the PID of the to be restored process minus one to /proc/sys/kernel/ns_last_pid. CRIU then verifies if the newly created process actually has the desired PID. If not - the process restoration is aborted. Another example of steps performed during restore are file descriptors, which are re-opened with the same identifier as in the original process and then the file descriptors are repositioned to the same location. All extracted (dumped) memory pages are loaded from the checkpoint directory to the currently being restored process and mapped to the same location as in the original process.
During the last step to restore the process CRIU jumps into the restored process at the same location it was during checkpoint and from that point on the restored process continues to run (without ever “knowing” that it was migrated or restored).
CRIU Limitations
One of the most obvious and hardest requirements for using CRIU is that used libraries (on the source and destination system) of the checkpointed and restored process must be exactly the same. The libraries are not newly loaded on the destination system of the restore. The restored binary expects all library provided functions to be at the (exact) same memory address as before. If a used library function is at a different memory location - the restored process will crash. Although this sounds like a severe restriction... it is not as fatal as it sounds. For example, when using CRIU to migrate a container (i.e. a “fancy process”) the container will often include not only the actual application to be migrated - it will also include the required libraries.
Another limitation of note: CRIU cannot (currently) be used to migrate applications which are directly accessing hardware through ioctl(). If such an application needs to be checkpointed and restarted or migrated CRIU provides an interface to create plugins which can be used to extract the state of the hardware on the source system and then put the hardware back into the same state during restore.
It is also important to remember that it is not possible to checkpoint processes which are already being ptrace’d (e.g., gdb, strace).
Process Migration
Process migration in its simplest form is nothing more than to checkpoint a process, transfer the checkpoint image from the source to the destination system and restore the process (once it has been transferred. Red Hat Enterprise Linux 7.2 provides CRIU as a Technology Preview. To migrate a process the following steps could be performed:
On the source system -
mkdir /tmp/checkpoint criu dump -D /tmp/checkpoint -t `pidof <process>` rsync -a /tmp/checkpoint <destination system>:/tmp/
On the destination system -
criu restore -D /tmp/checkpoint
With these commands a process can be migrated from one system to another. Note that the aforementioned limitations (still) need to be taken into account. Examples for processes which can be successfully migrated with the above listed steps include:
- A webserver streaming a video
- A postgresql database
- A Java application server communicating with the postgresql database
Many other applications have been successfully migrated and an important feature is that any established TCP network connections are (also) migrated with CRIU.
Using a file system which is shared between the source and destination host (NFS for example) removes the necessity to also transfer the required files (the streamed video, the database files, the java application).
Container Migration
Migrating a container is not that different than migrating a process from the standpoint of CRIU. It is also important to know that CRIU was developed with the goal to migrate containers. As mentioned earlier, CRIU always operates on a process and all its child processes. In most (if not all) cases a container is also such a process tree. In fact, migrating a container might be even easier (than migration a “vanilla” process) as interaction from the container’s processes to the “outside world” is limited (e.g. with the help of namespaces).
In addition to transferring the images of all checkpointed processes the container file system also needs to be transferred if the hosts running the containers are not using a shared file system.
Outlook
Using CRIU it is possible to migrate running processes, process trees, and containers. Migration in its simplest form (checkpoint, transfer, restore) can, depending on the size of processes, require a downtime which might be longer than desired. Virtual machine migration has incorporated a number of optimizations to reduce the downtime during migration; these same techniques already exist for process migration based on CRIU. Interested in learning more about CRIU? Check out this white paper / kbase in the Red Hat Customer Portal. Alternatively, do feel free to reach out using the comments section (below). | https://www.redhat.com/de/blog/checkpointrestore-container-migration | CC-MAIN-2020-40 | refinedweb | 1,434 | 50.67 |
Memors come in either Windows Mobile 6.1 or Windows CE 5.0 flavors.
Are you sure your device uses CE and not Mobile?
A Windows Mobile device's desktop will look sort of like the screenshots
below - because I can't seem to get the CE SDK installed right now (I've
got too many other applications open). A Windows Mobile device can be
confirmed by clicking [Start] > [Settings]:
Go to the [System] tab and select [About]:
On mine, you can see I'm stuck with WM5.
By contrast, a typical Windows CE device would have a screen somewhat like
this image I found on Google:
ANOTHER UPDATE:
Is your project, perhaps, set to Windows Mobile, like shown below?
If this is a Windows CE Project, you'll need to target the Windows CE
platform.
I can't install the Windows CE SDK on my machine,
You won't be able to load and use the database without a server running
somewhere. Now, you could install that database on a remote server that is
provided during installation - but a server has to be running somewhere.
Even loading it via file requires SQL Express to be running.
For
With Visual Studio 2012 you will need a third party tool to create setups.
I would suggest WiX. There is good information on installing and starting
Windows Services using WiX here although you will probably need to read
some beginners tutorials first..
PCM audio streams are not compatible with the MP4 container, look at the
specs and your error message:
Stream #0:1: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 16000 Hz, mono, s16,
256 kb/s [mp4 @ 00000000024bc980] Tag [1][0][0][0]/0x00000001 incompatible
with output codec id '65536' ([0][0][0][0])
Please note: the MP4 video container format and the H.264 video stream
format are two different things. The MP4 video container may also
'contain' other video stream formats, eg. Xvid or even MJPEG.
You need to add the latest jar in the java build path. Check your projects
build path and make sure the jar is present there. Do a clean build and
clean publish and it should work. If not then you can even try to directly
paste the jar in your projects deployment location (LIB folder).
Not sure if you are running into the double-hop problem on not, but it
sounds like you are. So I though I'd give you a little more information
about it. The Bob Loblaw version.
What is a server and what is a client? A server, it accepts things, is the
computer you remote onto. A client, it gives things, is the computer you
use to do the remoting. So in the command Invoke-Command -computername
xxxxxxxxxxx.edu ..., "xxxxxxxxxxx.edu" is the server.
From your description, it looks like you already ran the command
Enable-PSRemoting on your server. With remoting enabled on the server you
should be able to do Enter-PSSession -ComputerName xxxxxxxxxxx.edu and have
an interactive command prompt on the client.
If you enter a remote session and do Get-ChildItem "\ComputerNameShare" the
command is
Just found the problem - my installation was executed from WinZip
self-extractor which deletes the extracted files once the setup ends.
Because one of the prerequisites required a restart, before the computer
was restarted, the files had been deleted by the self extractor...
Beware of self extractors folks! :)
There should be no need for a .bat file. Inno Setup creates a stand-alone
executable (by default named Setup.exe) that you can simply double-click
like any other Windows executable.
The executable it creates is nameable either by renaming the Setup.exe to a
different name (YourAppSetup.exe, for instance) manually, or by using the
OutputBaseName value in the [Setup] section. You can control where the
setup executable is created by using the [Setup] section value OutputDir.
Here's an example, from the CodeExample1.iss' sample provided in yourInno
Setup` installation:
[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={code:MyConst}My Program
DefaultGroupName=My Program
UninstallDisplayIcon={app}MyProg.exe
InfoBeforeFile=Readme.txt
OutputDir=userdocs:Inno Setup Examples Output
This
Have you tried OPeNDAP Hyrax server with hdf5_handler module?
For example, from the sample HDF5 file [1], you can get the following ASCII
data [2]:
Dataset: grid_1_2d.h5
temperature[0], 10, 10, 10, 10, 10, 10, 10, 10
temperature[1], 11, 11, 11, 11, 11, 11, 11, 11
temperature[2], 12, 12, 12, 12, 12, 12, 12, 12
temperature[3], 13, 13, 13, 13, 13, 13, 13, 13
...
OPeNDAP Hyrax server with hdf5_handler is a great tool/service because you
can select (and subset) a dataset from an HDF5 file easily using HTML form
as well [3]. You can find the detailed information about OPeNDAP
hdf5_handler from [4].
[1]
[2]
[3]
I asked in the Phonegap IRC and they say NO. Of course this could be a big
security threat.
I also asked if it would be possible to include internal JS scripts in my
external HTML file. And the answer is also NO. The best way is to turn the
web app into an native app, and have all the scripts locally.
How are you constructing the **dirPath** used on the new File() ?
If the hardcoded path is working but the other one is not, my guess is that
path maybe is wrong. Try putting an Log.d and verify what is on **dirPath**
Did you tried using the getAbsolutePath instead of getPath ?
See this thread, maybe can help you - What's the difference between
getPath(), getAbsolutePath(), and getCanonicalPath() in Java?
No, it's not possible. You can use the forcecors plugin for Firefox to have
FF ignore the same origin policy (because all responses have cors headers).
The other option would be JSONP but since you've already mentioned blob
data it isn't an option since JSONP only works with JS.
Looking at the source swipe.js supports a kill method that stops the timer
and removes any event listeners.
I use a tool called VectorMagic () it will take
any image and convert it to EPS, SVG, PDF, AI, DXF and EMF. Works
seamlessly with Illustrator, Corel, and others.
Download this file and add the
files to your visual studio project. To use the functions, you will need to
#include "BESSEL.h" to your source file.
I got it compile on Visual Studio by doing the following
Adding _USE_MATH_DEFINES to preprocessor definitions.
Changing #include <complex.h> to #include <complex>
Adding using namespace std; to BESSEL.H
Example of how to call a function:
#include "BESSEL.H"
#include <iostream>
int main() {
double x, i0, i1, k0, k1, i0p, i1p, k0p, k1p;
x = 5.0;
i0 = 1.0;
i1 = 2.0;
k0 = 3.0;
k1 = 4.0;
i0p = 5.0;
i1p = 6.0;
k0p = 7.0;
k1p = 8.0;
bessik01a(x, i0, i1, k0, k1, i0p, i1p, k0p, k1p);
// Results are stored in the variables i0..k1p
cout
If you are opening a aPub file it might work to use some ePub component.
Native iBook files are not support by iOS and there for
UIDocumentInterectionController will not be able to display the file and
open iBooks.
QuickLook only supports:
iWork documents
Microsoft Office documents (Office ‘97 and newer)
Rich Text Format (RTF) documents
PDF files
Images
Text files whose uniform type identifier (UTI) conforms to the public.text
type
Comma-separated value (csv) files
Write it to a buffer:
var buffer = new Buffer(base64Data, 'base64');
An alternative would be something like
You have binary data encoded using BASE64 encoding.
To decode it you can use android.util.Base64 class.
To learn how to write file to an external store read this article.
Well that depends on your server. If you have a linux machine you could use
ffmpeg for conversion:
ffmpeg -i input.3gp -acodec mp3 -ar 22050 -f wav output.mp3
Just upload the file and trigger this command. Otherwise your server
application itself would have to take care of that.
this may help?
<xsl:stylesheet version="1.0"
xmlns:
<xsl:template
"<xsl:value-of" = "<xsl:value-of"
</xsl:template>
</xsl:stylesheet>
save it as x.xslt
and do
xsltproc x.xslt file.xml
Um, maybe i'm missing something, but both of those files are xml. the
second is just "pretty printed". you don't need to "pretty print" xml in
order to parse it with a sax (or any other) xml parser.
Guess you want to track it as text files to see line changes instead of
binary changes.
To set mime type of file as "text/plain":
svn propset svn:mime-type text/plain <list_of_verilog_files>
Also you could try to set "text/x-verilog" instead of "text/plain" and see
if it works.
You can use a FormData object to upload a file via ajax
function display_message(link, form)
{
var formData = new FormData(form);
$.ajax(
{
url: link,
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
data: formData,
success: function(result)
{
//form not valid -> displays errors
if (result.form_errors)
{
//append current errors to the html form
errors=result.form_errors
for (var key in errors)
{
$("#"+key+"_errors").html('<ul
class="errorlist"><li>'+errors[key]+'</li></ul>');
//~ alert(key+': '+errors[key]);
}
Sub Tester()
Dim ObjOutFile
Set ObjOutFile = CreateObject("Scripting.FileSystemObject"). _
CreateTextFile("C:UsersUserDesktopoutcome")
ListFiles ObjOutFile, "C:UsersUserDesktopFolder A", "Outlook Item"
ListFiles ObjOutFile, "C:UsersUserDesktopFolder B", "Outlook Item"
ObjOutFile.Close
End Sub
Sub ListFiles(f, folderPath As String, fileType As String)
Dim ObjFiles, ObjFile, sz
fileType = UCase(fileType)
Set ObjFiles = CreateObject("Scripting.FileSystemObject") _
.getfolder(folderPath).Files
For Each ObjFile In ObjFiles
If UCase(ObjFile.Type) = fileType Then
sz = Round(ObjFile.Size / 1024, 2)
f.WriteLine sz & String(50 - Len(sz), " ") &
ObjFile.Path
End If
What you want to do is monitor for process creation notifications, and when
you see the specific process come into existence, you will want to get out
of its way.
IWbemServices::ExecNotificationQuery
Here are some some additional details off of MSDN.
Here is also a CodeProject: Process Information and Notifications using WMI
One possible solution could be is using Web Worker and run your JS code
inside it. After a while, if there is no any responce from it, call
worker.terminate() to "kill" it.
Pay attention that web workers has strong limitations: for example you can
not access UI element from within the code that runs in web worker scope,
and it's not supported on old browsers.
I don't know if web worker is suitable in your case, but this one is option
that may help.
Let your data be A.
A = 1:12;
B = reshape(A,4,[]);
B =
1 5 9
2 6 10
3 7 11
4 8 12
I = mat2gray(B); %converts the matrix A to the intensity image I
imwrite(I,filename,fmt)
Is .pts ASCII?
If so, you can easily write a parser for it and save it as a .pcd.
Or, if you are looking for a tool, meshlab can read in plain XYZ data and
save it to .ply format (remove all header content, if there is any). .ply
files are supported by the Point Cloud Library, you can either convert it
or just read in the .ply.
Does your version work? It looks like you only ever create one Peptide
object. Also, what is the "if(row[5])" statement doing? In your example
data there are always 5 elements. Also, mod_indeces is always supposed to
be a list, correct? Because in your example output file mod_indeces isn't a
list in the first peptide. Anyway, here is what I came up with in python:
import csv
import json
data = {}
with open('proteins.csv','rb') as f:
reader = csv.reader(f)
for row in reader:
name = row[0]
sequence = row[1]
mod_sequence = row[2]
mod_indeces = map(int,row[3].split(', '))
spectral_count = int(row[4])
peptide = {'sequence':sequence,'mod_sequence':mod_sequence,
'mod_indeces':mod_indeces,'spectral_count':spectral_count}
You are not replacing the line.lower() back into the list.
Try:
lines = [line.lower() for line in lines]
with open('listTogether.txt', 'w') as out:
out.writelines(sorted(lines))
Hi If you are trying to remove carriage returns after converting the file
add the below procedure to code
sub RemoveCarriage(FileN)
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(FileN, ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, chr(013) & chr(010), "")
' chr(010) = line feed chr(013) = carriage return
Set objFile = objFSO.OpenTextFile(FileN, ForWriting)
objFile.WriteLine strNewText
objFile.Close
End sub
Call the module inside forloop of your procedure just after closing the
workbook
objWorkbook.close
RemoveCarriage(file.Name & ".txt")
take a look into . It
describe main scenarios and capabilities of Microsoft Azure Media Services.
Developer portal for Azure Media Services located at. It has getting
starting articles covering following scenarios:
Upload
Encode
Deliver
Consume
I kind of remember, when you work with paths in DOS, you can either do it
this way
"c:Dir1Dir1.1File.ext"
or this way
c:"Dir One""Dir One.One""File X.ext"
Im not entirely sure what you mean but try this, it will execute the
command once for each file in the current directory and (all
subdirectories, but this exact snipets not ideal for subdirectories) ending
with the extension .prn:
for /r %%a in (*) do (
if %%~xa == .prn (
copy %%~na%%~xa /B \\{$PC}\{$PRINTER}
)
)
Tell me if this doesn't work or you want to do this for subdirectories as
well.
Yours, Mona
You can conditionally create the folder with:
if not exist moviesshowname mkdir moviesshowname
To move a file into it:
move ShowName.Episode.Title.mkv moviesshowname
To get more information about these commands, open a command prompt and
type:
help if
and
help move
Try this: and then examine renfile.bat in notepad to see if it is right for
you.
Add more filetypes if you need them.
@echo off
echo.@echo off> renfile.bat
for /f "delims=" %%a in ('dir *.jpg *.png *.gif /b /s /a-d ') do call :next
"%%a"
echo renfile.bat created
pause
goto :eof
set "var=%~1"
call set "var=%%var:%cd%=%%"
set "var=%var:=_%"
>>renfile.bat echo ren "%~1" "%var:~1%"
and another batch file to move all the files once they are renamed:
@echo off
md "c: arget folder"
for /f "delims=" %%a in ('dir *.jpg *.png *.gif /b /s /a-d ') do (
move "%%a" "c: arget folder"
)
Getting the file size into a variable is simple - for %%F in (filePath) do
set "size=%%~zF".
But I believe I can give you a much better solution.
Unlike Unix, most Windows processes get an exclusive lock on a file when
they are writing to it. Assuming your conversion process continuously locks
the output file during processing, then you can simply use the following to
test if the file is locked (still being processed) or not locked (finished
processing):
( (call ) >>outputFile.ext ) 2>nul && (
echo The file is unlocked and ready for transfer
) || (
echo The file is still being created
)
The (call ) syntax is simply a very fast command that does nothing -
effectively a null op. This command is guaranteed not to have any output,
so when you append the results of the | http://www.w3hello.com/questions/How-do-I-convert-a-setup-py-file-to-an-egg-file-for-Deulge-3rd-party-plugins-in-Windows- | CC-MAIN-2018-17 | refinedweb | 2,532 | 66.44 |
documentation changes introduced <IS> fixed TO in comp.fs
1: \ A less simple implementation of the blocks wordset. ( -- ) \ gforth 59: 60: : open-blocks ( c-addr u -- ) \ gforth 61: \g Use the file, whose name is given by @i{c-addr u}, as the blocks file. 62: 2dup open-fpath-file 0<> 63: if 64: @i{file} as the blocks file. 74: name open-blocks ; 75: 76: \ the file is opened as binary file, since it either will contain text 77: \ without newlines or binary data 78: : get-block-fid ( -- wfileid ) \ gforth 79: \G Return the file-id of the current blocks file. If no blocks 80: \G file has been opened, use @file{blocks.fb} as the default 81: \G blocks file. 82: block-fid @ 0= 83: if 84: s" blocks.fb" open-blocks 85: then 86: block-fid @ ; 87: 88: : block-position ( u -- ) \ block 89: \G Position the block file to the start of block @i{u}. 90: 1- chars/block chars um* get-block-fid reposition-file throw ; 91: 92: : update ( -- ) \ block 93: \G Mark the current block buffer as dirty. 94: last-block @ ?dup IF buffer-dirty on THEN ; 95: 96: : save-buffer ( buffer -- ) \ gforth 97: >r 98: r@ buffer-dirty @ r@ buffer-block @ 0<> and 99: if 100: r@ buffer-block @ block-position 101: r@ block-buffer chars/block r@ buffer-fid @ write-file throw 102: r@ buffer-dirty off 103: endif 104: rdrop ; 105: 106: : empty-buffer ( buffer -- ) \ gforth 107: buffer-block off ; 108: 109: : save-buffers ( -- ) \ block 110: \G Transfer the contents of each @code{update}d block buffer to 111: \G mass storage, then mark all block buffers as unassigned. 112: block-buffers @ 113: buffers 0 ?DO dup save-buffer next-buffer LOOP drop ; 114: 115: : empty-buffers ( -- ) \ block-ext 116: \G Mark all block buffers as unassigned; if any had been marked as 117: \G assigned-dirty (by @code{update}), the changes to those blocks 118: \G will be lost. 119: block-buffers @ 120: buffers 0 ?DO dup empty-buffer next-buffer LOOP drop ; 121: 122: : flush ( -- ) \ block 123: \G Perform the functions of @code{save-buffers} then 124: \G @code{empty-buffers}. 125: save-buffers 126: empty-buffers ; 127: 128: ' flush IS flush-blocks 129: 130: : get-buffer ( n -- a-addr ) \ gforth 131: buffers mod buffer-struct %size * block-buffers @ + ; 132: 133: : block ( u -- a-addr ) \ block- block 134: \G If a block buffer is assigned for block @i{u}, return its 135: \G start address, @i{a-addr}. Otherwise, assign a block buffer 136: \G for block @i{u} (if the assigned block buffer has been 137: \G @code{update}d, transfer the contents to mass storage), read 138: \G the block into the block buffer and return its start address, 139: \G @i{a-addr}. 140: dup 0= -35 and throw 141: dup get-buffer >r 142: dup r@ buffer-block @ <> 143: r@ buffer-fid @ block-fid @ <> or 144: if 145: r@ save-buffer 146: dup block-position 147: r@ block-buffer chars/block get-block-fid read-file throw 148: \ clear the rest of the buffer if the file is too short 149: r@ block-buffer over chars + chars/block rot chars - blank 150: r@ buffer-block ! 151: get-block-fid r@ buffer-fid ! 152: else 153: drop 154: then 155: r> dup last-block ! block-buffer ; 156: 157: : buffer ( u -- a-addr ) \ block 158: \G If a block buffer is assigned for block @i{u}, return its 159: \G start address, @i{a-addr}. Otherwise, assign a block buffer 160: \G for block @i{u} (if the assigned block buffer has been 161: \G @code{update}d, transfer the contents to mass storage) and 162: \G return its start address, @i{a-addr}. The subtle difference 163: \G between @code{buffer} and @code{block} mean that you should 164: \G only use @code{buffer} if you don't care about the previous 165: \G contents of block @i{u}. In Gforth, this simply calls 166: \G @code{block}. 167: \ reading in the block is unnecessary, but simpler 168: block ; 169: 170: User scr ( -- a-addr ) \ block-ext 171: \G USER VARIABLE: @i{a-addr} is the address of a cell containing 172: \G the block number of the block most recently processed by 173: \G @code{list}. 174: 0 scr ! 175: 176: \ nac31Mar1999 moved "scr @" to list to make the stack comment correct 177: : updated? ( n -- f ) \ gforth 178: \G Return true if block @i{n} has been marked as dirty. 179: buffer 180: [ 0 buffer-dirty 0 block-buffer - ] Literal + @ ; 181: 182: : list ( u -- ) \ block-ext 183: \G Display block @i{u}. In Gforth, the block is displayed as 16 184: \G numbered lines, each of 64 characters. 185: \ calling block again and again looks inefficient but is necessary 186: \ in a multitasking environment 187: dup scr ! 188: ." Screen " u. 189: scr @ updated? 0= IF ." not " THEN ." modified " cr 190: 16 0 191: ?do 192: i 2 .r space scr @ block i 64 * chars + 64 type cr 193: loop ; 194: 195: : (source) ( -- c-addr u ) 196: blk @ ?dup 197: IF block chars/block 198: ELSE tib #tib @ 199: THEN ; 200: 201: ' (source) IS source ( -- c-addr u ) \ core 202: \G @i{c-addr} is the address of the input buffer and @i{u} is the 203: \G number of characters in it. 204: 205: : load ( i*x n -- j*x ) \ block 206: \G Save the current input source specification. Store @i{n} in 207: \G @code{BLK}, set @code{>IN} to 0 and interpret. When the parse 208: \G area is exhausted, restore the input source specification. 209: push-file 210: dup loadline ! blk ! >in off ['] interpret catch 211: pop-file throw ; 212: 213: : thru ( i*x n1 n2 -- j*x ) \ block-ext 214: \G @code{load} the blocks @i{n1} through @i{n2} in sequence. 215: 1+ swap ?DO I load LOOP ; 216: 217: : +load ( i*x n -- j*x ) \ gforth 218: \G Used within a block to load the block specified as the 219: \G current block + @i{n}. 220: blk @ + load ; 221: 222: : +thru ( i*x n1 n2 -- j*x ) \ gforth 223: \G Used within a block to load the range of blocks specified as the 224: \G current block + @i{n1} thru the current block + @i{n2}. 225: 1+ swap ?DO I +load LOOP ; 226: 227: : --> ( -- ) \ gforth- gforth chain 228: \G If this symbol is encountered whilst loading block @i{n}, 229: \G discard the remainder of the block and load block @i{n+1}. Used 230: \G for chaining multiple blocks together as a single loadable 231: \G unit. Not recommended, because it destroys the independence of 232: \G loading. Use @code{thru} (which is standard) or @code{+thru} 233: \G instead. 234: refill drop ; immediate 235: 236: : block-included ( a-addr u -- ) \ gforth 237: \G Use within a block that is to be processed by @code{load}. Save 238: \G the current blocks file specification, open the blocks file 239: \G specified by @i{a-addr u} and @code{load} block 1 from that 240: \G file (which may in turn chain or load other blocks). Finally, 241: \G close the blocks file and restore the original blocks file. 242: block-fid @ >r block-fid off open-blocks 243: 1 load block-fid @ close-file throw flush 244: r> block-fid ! ; 245: 246: \ thrown out because it may provide unpleasant surprises - anton 247: \ : include ( "name" -- ) 248: \ name 2dup dup 3 - /string s" .fb" compare 249: \ 0= IF block-included ELSE included THEN ; 250: 251: get-current environment-wordlist set-current 252: true constant block 253: true constant block-ext 254: set-current 255: 256: : bye ( -- ) \ tools-ext 257: \G Return control to the host operating system (if any). 258: ['] flush catch drop bye ; | http://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/blocks.fs?f=h;only_with_tag=MAIN;content-type=text%2Fx-cvsweb-markup;ln=1;rev=1.25 | CC-MAIN-2020-24 | refinedweb | 1,303 | 76.25 |
FAQs
Search
Recent Topics
Flagged Topics
Hot Topics
Best Topics
Register / Login
This week's book giveaway is in the
General Computing
forum.
We're giving away four copies of
Emmy in the Key of Code
and have Aimee Lucido on-line!
See
this thread
for details.
Win a copy of
Emmy in the Key of Code
this week in the
General Computing:
I/O and Streams
Save a String to a Text File,
david foley
Ranch Hand
Posts: 85
posted 6 years ago
I am Trying to Save a
String
to a Text File..
import java.io.Console; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; public void holidays() { double amount; int basic = 21; for (int i = 0; i < StaffList.length; i++) { try { // Create file FileWriter out = new FileWriter("EmployeeRecords.txt"); System.out.println(StaffList[i]); amount = StaffList[i].holidays(); amount += basic; out.write(); out.write ("Total Holidays: " + amount); out.write("\n"); out.write ("-----------------------------------"); //Close the output stream out.close(); }//End Try Write //Catch exception if any catch (Exception e) { //Out Put Error Message if Any Exception is Found. System.err.println("Error: Can Not Create File! " + e.getMessage()); } //end Catch //Reading a file File file = new File("EmployeeRecords.txt"); int ch; StringBuffer strContent = new StringBuffer(""); FileInputStream fin = null; try { fin = new FileInputStream(file); while ((ch = fin.read()) != -1) strContent.append((char) ch); fin.close(); } // Try Read catch (Exception e) { System.out.println(e); } //End Catch //Out Print the File Content to Console. System.out.println(strContent.toString()); }// End If Read / Write Method } //Ends Main Method }
Kemal Sokolovic
Bartender
Posts: 825
5
I like...
posted 6 years ago
And the question is...?
The quieter you are, the more you are able to hear.
david foley
Ranch Hand
Posts: 85
posted 6 years ago
How can i get my toString into a Text file,
Kemal Sokolovic
Bartender
Posts: 825
5
I like...
posted 6 years ago
Well, the code you provided cannot be compiled as is. First of all, FileWriter class has no
write()
method, so
out.write();
will prevent you from compiling the code. Also I think there is one closing brace more than it should be, but I will suppose you made a mistake when pasting the code.
There is also something that looks wrong with the logic. You are trying to write to file inside the for loop. So what the output file would contain is the
amount
returned
only
from the last element of your
StaffList
array increased by value of
basic
. However, if you wanted to save the data for each element of your
StuffList
array, you would have to initialize FileWriter before you enter the for loop, write the data inside the for loop, and close the output after it. Basically, it should look like this:
... FileWriter out = new FileWriter("EmployeeRecords.txt"); for(int i = 0; i < staffList.length; ++i) { // Calculate the amount for the current stuff member // and write it to file out.write("whatever you want to write"); } out.close(); ...
And what's the purpose of the code marked as
Reading a file
? If you need to read the file too, than
you should
put that in separate method. Also, naming a method
holidays()
for this task doesn't seem like a very good choice to me.
The quieter you are, the more you are able to hear.
david foley
Ranch Hand
Posts: 85
posted 6 years ago
OK, I Fixed up the Loop,
but my main problem doesnt seem to want to fix itself,
Here is my String
public String toString() { String result ="\n"; result += "Name: " + Name + "\n"; result += "Address: " + Address + "\n"; result += "Phone: " + phone + "\n"; result += "Start Date: " + StartDate + "\n"; result += "End Date: " + EndDate + "\n"; result += "Position: " + position + "\n"; result += "Salary: " + Salary + "\n"; result += "Sex: " + Sex + "\n"; result += "Personal Public Service Number: " + PPSNumber + "\n"; return result; }
for (int i = 0; i < StaffList.length; i++) { // Create file System.out.println(StaffList[i]); amount = StaffList[i].holidays(); amount += basic; out.write(StaffList[i]); out.write ("Total Holidays: " + amount); out.write("\n"); out.write ("-----------------------------------"); } //End the Loop
I Used a ArrayList and got the String to Print to text file, but i cant seem to get it to work on an Array
for(int i = 0; i < CIT.MemberList.size(); i++) { EmployeeMember temp = (EmployeeMember)CIT.MemberList.get(i); try { // Create file FileWriter out1 = new FileWriter("EmployeeRecords.txt"); /* * Takes the EmployeeMember Temp * and Writes the Object of the ArrayList * To a Text file using the Following Code. */ out1.write(temp.toString()); //Close the output stream out1.close(); }//End Try Write
Kemal Sokolovic
Bartender
Posts: 825
5
I like...
posted 6 years ago
Did you try this?
out.write(StaffList[i].toString());
The quieter you are, the more you are able to hear.
You don't like waffles? Well, do you like this tiny ad?
Java file APIs (DOC, XLS, PDF, and many more)
Post Reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
compile time errors, why?
write() function not writing in the file
A small error relating with return
creating files in directory
Alignment is working only sometimes in editor made in java.
More... | https://coderanch.com/t/599293/java/Save-String-Text-File | CC-MAIN-2019-47 | refinedweb | 858 | 75.1 |
Dear Reader,
As part of some long-overdue maintenance, I have changed the way image URLs are namespaced, since I wanted to make it easier to handle some corner cases (and also make it easier to manage future static generation).
The underlying server OS and Python runtime have also changed to Ubuntu 20.04 and Python 3.8, respectively (which brings it up to my regular standards these days, it was becoming a bit long in the tooth).
Since image URLs are also signed with an HMAC (which I rotate periodically to avoid getting my content ripped off wholesale), there might be some temporarily missing images until Cloudflare catches up.
Again, kindly remember that the
RSS/
Atom feed URL for this site has changed – the old URL will likely stop working after the holiday season. | https://taoofmac.com/space/notices/2020/12/18/1930 | CC-MAIN-2021-04 | refinedweb | 135 | 57.61 |
Search:
Forum
Lounge
Someday....
Page 3
Someday....
Pages:
1
2
3
Mar 19, 2013 at 3:41pm UTC
devonrevenge
(2408)
@Zereo: your quote only partly true, a tiny part
EDIT: the link also has the evidence
Last edited on
Mar 19, 2013 at 3:43pm UTC
Mar 19, 2013 at 4:03pm UTC
closed account (
3qX21hU5
)
How is my quote untrue? I was not talking about the Congo or any other third world country I was talking about the US and EU where we live which is where them statistics come from.
But you are right there is kids being forces in labor against there will, but that isn't in the US or the EU (At least not as bad) which is where we were talking about. Really there is nothing you can do to stop that in third world countries unless you launch a ground invasion and try and start a democracy (Which didn't turn out so well the last couple of times we have tried that).
Mar 19, 2013 at 6:07pm UTC
devonrevenge
(2408)
but im talking about the entire global economy, so what yu say is only true in the US not the world so it only covers a small portion of what i mean, when we talk about socialism and capitalism i feel the namespace should cover every nation that is part of the world economy, if it was socialism versus the american system (republic/aristocracy) I then the working class still look like they get a crap deal but the true human cost of our consumerism isn't really a fair view of the whole picture.
Its not the fault of third world countries that these things get so bad, especialy if theres no desire to halp the congo out, BECAUSE IT WOULD BE BAD FOR THE TECH SECTOR AND OUR ECONOMY!! that's what is happening., its totaly real and is a very interesting (extremely interesting) field to study.
Last edited on
Mar 19, 2013 at 6:11pm UTC
Mar 19, 2013 at 6:32pm UTC
closed account (
3qX21hU5
)
if it was socialism versus the american system (republic/aristocracy)
What America are you talking about... I don't think you even know what is going on in America or what it even is...
when we talk about socialism and capitalism i feel the namespace should cover every nation that is part of the world economy
It doesn't work like that, to think that the world will someday consider itself all just friends and have a global government. Different countries have different agenda's. There is almost nothing that other countries like the US or the UK can do really do help the Congo and other 3rd world countries other then send in food, water, and other relief missions.
I mean really what do you expect them to do? Just go up to the Congo's government and say hey stop doing that or else? Most likely that won't stop them and they could care less. The only way to actually put a stop to it would be to start a military war against the country. Then even if they did succeed by giving them a democracy there would still be 50+ other counties that are in poverty.
Its not the fault of third world countries that these things get so bad, especialy if theres no desire to halp the congo out, BECAUSE IT WOULD BE BAD FOR THE TECH SECTOR AND OUR ECONOMY!! that's what is happening.
Yes its sad, and it shouldn't be happening, but like I said before there is no way to stop it other then starting a war and killing even more people. It's all right to want to help them people, but how bout instead of blaming American's for something we aren't doing you can actually look at the Congo's government who IS DOING IT. I really don't understand the argument that its not that countries fault if they turned their country into crap, its some other country because they won't help them..
Personally it seems like a conspiracy theory to me. And I have now figured out what you hate America so much, because you read stuff like this ;p
Time to hack your computer and take revenge for America ;p Joking.... Kinda.... Not Really..... Ok Ya I Am......
Last edited on
Mar 19, 2013 at 7:03pm UTC
Mar 19, 2013 at 7:08pm UTC
devonrevenge
(2408)
simple though, dont allow people to buy crap made by slaves, problem solved-ish
nah its real :P
I dont hate america at all, i love americans and their crazy generous portions and alchohol measures, its just that its economic/foriegn policy is an international joke americans don't get to see, it really is a destabilizing force in this world and a lot of americans won't believe that thanks to americas incredible propaganda machine ( :P :P :P )
EDIT: hack away fool, maybe you might find out what library book I took out once, exciting :P (won't sue you if you hack me but I will reserve the right to hack you back one day when i know how, and I it wont be a conventsional kind of hacking i promise :P oh ya and don't get me deprorted please...less its too hawai)
EDIT::
doesnt appear to be the ravings of a foaming conspiracy theorist (foamy conspiracy theorists deserve more cridibility though, its not that odd to wonder why a long stumpy building called wt7 came down symetricaly due to unsymetrical and very local structural damage)
Last edited on
Mar 19, 2013 at 7:20pm UTC
Mar 19, 2013 at 10:43pm UTC
DeXecipher
(458)
Classism needs to stop, people should stop dividing themselves based upon things such as money, race, or social standing, and ideology. When people do divide themself into one group they box themselves in, and suddenly what you say will be held against you because thats all that people will ever think you are when your name is mentioned.
But to do this humanity would have to evolve out of its contrite ways. A democratic socialism would be ideal (with a free market) as well, so it would be impossible for the cost of things to go up. However, thats not really possible with the free market, because people would end up stockpiling their wealth, like the 1 percent of america right now. Its cool to value art, but I think humans are fairly stupid to value entertainment over necessity. Socialism is not really possible under a non-goverment controlled free market, because peoples values will change. It would take a disastrous event or incentive, to change the overall population like scarcity of natural resources. The base problem stems from money in the first place. Some people value money more than morals and family and it is sad.
Last edited on
Mar 19, 2013 at 10:49pm UTC
Mar 19, 2013 at 11:04pm UTC
Oria
(382)
Personally it seems like a conspiracy theory to me.
Many are based on truth and many are lies, However, If you pay close attention to details and look at the past 5000 years of our history. I would sooner believe in many of them. History repeats itself and humans are a specie that does conspire, lie, deceive and whatnot. And because a government body denies something, does not mean it never happened.
I heard this too often: "well it would be on the news". when actually the media is paid and told what to put in the news and do people really think the government would allow people to know their real agenda?
Mar 20, 2013 at 12:18am UTC
devonrevenge
(2408)
I really don't hate america though guys, well americans always manage to be as individual as they are amazing, its just become a symbol of the first world not being what it wants to come across as.
Topic archived. No new replies allowed.
Pages:
1
2
3
C++
Information
Tutorials
Reference
Articles
Forum
Forum
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Lounge
Jobs
|
v3.1
Spotted an error? contact us | http://www.cplusplus.com/forum/lounge/95628/3/ | CC-MAIN-2015-40 | refinedweb | 1,373 | 61.4 |
SparkFunPhant (community library)
Summary
A simple library for the Particle Photon that generates Phant posts, gets, deletes and more.
Example Build Testing
Device OS Version:
This table is generated from an automated build. Success only indicates that the code compiled successfully.
Library Read Me
This content is provided by the library maintainer and has not been validated or approved.
SparkFun Phant Particle Library
A Phant library for the Particle Core and Photon.
About
This is a firmware library SparkFun's Phant data storage/stream service, implemented on data.sparkfun.com
Repository Contents
- /firmware - Source files for the library (.cpp, .h).
- /firmware/examples - Example sketches for the library (.cpp). Run these from the Particle IDE.
- spark.json - General library properties for the Particle library manager.
Example Usage
Create a Phant Stream
Visit data.sparkfun.com to create a Phant stream of your own. You'll be given public and private keys, don't lose them!
If you want to set up Phant on a server of your own, visit phant.io.
Include & Constructor
Make sure you include "SparkFun-Spark-Phant/SparkFun-Spark-Phant.h":
// Include the Phant library:
#include "SparkFun-Spark-Phant/SparkFun-Spark-Phant.h":
Then create a Phant object, which requires a server, public key and private key:
const char server[] = "data.sparkfun.com"; // Phant destination server const char publicKey[] = "DJjNowwjgxFR9ogvr45Q"; // Phant public key const char privateKey[] = "P4eKwGGek5tJVz9Ar84n"; // Phant private key Phant phant(server, publicKey, privateKey); // Create a Phant object
Adding Fields/Data
Before posting, update every field in the stream using the
add([field], [value]) function. The
[field] variable will always be a String (or const char array),
[value] can be just about any basic data type --
int,
byte,
long,
float,
double,
String,
const char, etc.
For example:
phant.add("myByte", 127); phant.add("myInt", -42); phant.add("myString", "Hello, world"); phant.add("myFloat", 3.1415);
POSTing
After you've phant.add()'ed, you can call
phant.post() to create a Phant POST string.
phant.post() returns a string, which you can send straight to a print function.
Most of the time, you'll want to send your
phant.post() string straight out of a TCPClient print. For example:
TCPClient client; if (client.connect(server, 80)) // Connect to the server { client.print(phant.post()); }
After calling
phant.post() all of the field/value parameters are erased. You'll need to make all of your phant.add() calls before calling post again.
Recommended Components
- Particle Photon
- A Photon Shield or sensor to interface with your Photon and post data to Phant.
License Information
This product is open source!
Please review the LICENSE.md file for license information.
If you have any questions or concerns on licensing, please contact techsupport@sparkfun.com.
Distributed as-is; no warranty is given.
- Your friends at SparkFun.
Browse Library Files | https://docs.particle.io/cards/libraries/s/SparkFunPhant/ | CC-MAIN-2021-21 | refinedweb | 466 | 61.83 |
- Event Dispatching
- Event Dispatching
Everything in Flex occurs based on an event. This means that simply clicking a button or key to moving the mouse or receiving a response from a web service provides developers with the ability to trigger a custom event in their Flex applications. That’s a lot of control, and since Flex is not based on.
On the Web a Flex app is completely loaded upfront, which allows the functionality within to respond faster than a standard web request model. This will initially cause the user to wait until the app is fully loaded, but will save time when it counts, which is during usage.
Not having to wait for a page refresh also prevents the user from having problems maintaining context because the screen reacts instantaneously. With these additional benefits you would expect some new issues to arise, but the capabilities of Flex are not limited in any way when comparing them with a standard web app.
In this article you will learn how to leverage the power of events by dispatching them in your own custom classes. The source code for this project can be downloaded here.
If you feel you need some background on Flex development before diving into events, take a look at the previous articles in the From Flash to Flex series.
Event Dispatching
Dispatching your own events starts by extending the UIComponent. In the last article of the Flash to Flex series, "Creating ActionScript Components for Flex," I explained how to create a Flex component by extending the UIComponent.
This article will pick up where that article left off by adding the additional functionality to dispatch your own custom events when a headline is selected. As a quick recap, the headline component that we built ran from XML, which defined a URL and display text for different headlines. When the app loaded, the component would cycle through each of the headlines for a predetermined interval that we passed to the constructor. Each headline would display at the top of the page waiting for someone to click it and visit the corresponding URL.
Since the UIComponent extends the EventDispatcher, all subclasses of the UIComponent have access to the dispatchEvent() method.
Relying on the href to link us to the URL of a headline works great, but if we wanted to add some additional functionality each time a headline is selected, such as logging what headlines were selected and at what time, this functionality would not allow it.
Therefore we will use events to inform a custom handler of the selection and then we will dispatch an event and delegate it to the appropriate class, which will log the data that we define.
First of all, we need to change the way that our headlines are constructed to trigger an event in the href (see Listing 1) instead of just linking to the URL as we did before (see Listing 2).
Listing 1: Triggering an event
this.headlines.push("<a href=’event:"+ _headlines[i].attribute("action") +"’>"+ _headlines[i].text() +"</a>");
Listing 2: Simply linking to the URL
this.headlines.push(’<a href="’+ _headlines[i].attribute("action") +’" target="_blank">’+ _headlines[i].text() +’</a>’);
If you have developed with Flash, the first thing that you’ll probably notice in Listing 1 is that we are not using asfunction any more; there is now a way to trigger an event from an href.
Now that we have our event in place we need to add a listener to the textfield that we are creating to display the headlines.
To do this I have added the event listener to the createTextField method from our previous headline class and modified it a bit to handle the text directly as a parameter rather than assigning it after the field has been created (see Listing 3).
Listing 3: Adding an event listener
private function cycle(index:Number):void { if(this.currentTextField != null) removeChild(this.currentTextField); this.currentTextField = this.createTextField(0, 0, 200, 100, this.headlines[index]); if(index == (this.headlines.length-1)) index = 0; else index++; if(this.__cycleTimeout != 0) clearTimeout(this.__cycleTimeout); this.__cycleTimeout = setTimeout(cycle, (this.delay*1000), index); } private function createTextField(x:Number, y:Number, width:Number, height:Number, text:String):TextField { var format:TextFormat = new TextFormat(); format.font = "Arial"; format.color = 0x333333; format.size = 21; format.underline = true; var txtField:TextField = new TextField(); txtField.x = x; txtField.y = y; txtField.width = width; txtField.height = height; txtField.autoSize = "left"; txtField.defaultTextFormat = format; txtField.htmlText = text; txtField.addEventListener(TextEvent.LINK, onHeadlineSelected); addChild(txtField); return txtField; }
In the createTextField method we added the event listener after the field has been created and assigned the value of the headline. Let’s not forget to include the appropriate class (see Listing 4).
Listing 4: Importing the TextEvent
import flash.events.TextEvent;
Now that our event is being listened to, the next step is to handle it. We will need to create an onHeadlineSelected method to correspond to the event that we defined previously (see Listing 5).
Listing 5: Handling the event
private function onHeadlineSelected(e:TextEvent):void { var u:URLRequest = new URLRequest(e.text); navigateToURL(u, "_blank"); e.currentTarget.addEventListener("textlink", Logger.GetInstance().Log); var tev:TextEvent = new TextEvent("textlink", false, false); var date:Date = new Date(); tev.text = date.toString() +"::"+ e.text; e.currentTarget.dispatchEvent(tev); }
If you are transitioning from Flash you’ll notice that there is no longer a getURL method. Instead we need to create a new URLRequest from our URL and then use it in the navigateToURL method, which allows us to target the browser window just as getURL did.
The next line assigns an event listener to a method called Log in a new class called Logger, which we will create in a moment (see Listing 6).
You’ll also notice that we are providing the listener with a custom type called textlink, which will prevent any recursion issues when our other events are fired.
Once we have the listener in place we need to create a new event, which in this case is a TextEvent, set the values that we want to pass the new method and finally dispatch the event to whomever is listening.
Now that we are finally dispatching events, let’s take a look at how to handle them from other classes. | http://www.peachpit.com/articles/article.aspx?p=1019620 | CC-MAIN-2016-40 | refinedweb | 1,052 | 55.03 |
Node:Opening a file, Next:Closing a file, Previous:High-level file routines, Up:High-level file routines
Opening a file
The main high-level function for opening files is
fopen. When
you open a file with the
fopen function, the GNU C Library
creates a new stream and creates a connection between the stream and a
file. If you pass this function the name of a file that does not exist,
that file will be created. The
fopen function normally returns a
stream. A stream is a flow of data from a source to a destination
within a GNU system. Programs can read characters from or write
characters to a stream without knowing either the source or destination
of the data, which may be a file on disk, a device such as a terminal
meant as a human interface, or something entirely different. Streams
are represented by variables of type
FILE * --
fopen will
return a null pointer if it fails to open the file.
The first parameter to this function is a string containing the filename
of the file to open. The filename string can be either a constant or a
variable, as in the following two equivalent examples:
FILE *my_stream; my_stream = fopen ("foo", "r"); FILE *my_stream; char my_filename = "foo"; my_stream2 = fopen (my_filename, "r");
The second parameter is a string containing one of the following sets of characters:
r
- Open the file for reading only. The file must already exist.
w
- Open the file for writing only. If the file already exists, its current contents are deleted. If the file does not already exist, it is created.
r+
- Open the file for reading and writing. The file must already exist. The contents of the file are initially unchanged, but the file position is set to the beginning of the file.
w+
- Open the file for both writing and reading. If the file already exists, its current contents are deleted. If the file does not already exist, it is created.
a
- Open the file for appending only. Appending to a file is the same as writing to it, except that data is only written to the current end of the file. If the file does not already exist, it is created.
a+
- Open the file for both appending and reading. If the file exists, its contents are unchanged until appended to. If the file does not exist, it is created. The initial file position for reading is at the beginning of the file, but the file position for appending is at the end of the file.
See File position, for more information on the concept of file position.
You can also append the character
x after any of the strings in the
table above. This character causes
fopen to fail rather than opening
the file if the file already exists. If you append
x to any of the arguments
above, you are guaranteed not to clobber (that is, accidentally destroy)
any file you attempt to open. (Any other characters in this parameter are ignored
on a GNU system, but may be meaningful on other systems.)
The following example illustrates the proper use of
fopen to open
a text file for reading (as well as highlighting the fact that you
should clean up after yourself by closing files after you are done with
them). Try running it once, then running it a second time after
creating the text file
snazzyjazz.txt in the current directory
with a GNU command such as
touch snazzyjazz.txt.
#include <stdio.h> int main() { FILE *my_stream; my_stream = fopen ("snazzyjazz.txt", "r"); if (my_stream == NULL) { printf ("File could not be opened\n"); } else { printf ("File opened! Closing it now...\n"); /* Close stream; skip error-checking for brevity of example */ fclose (my_stream); } return 0; }
See Closing a file, for more information on the function
fclose. | http://crasseux.com/books/ctutorial/Opening-a-file.html | CC-MAIN-2017-43 | refinedweb | 637 | 71.75 |
How can I flip the origin of a matplotlib plot to be in the upper-left corner - as opposed to the default lower-left? I'm using matplotlib.pylab.plot to produce the plot (though if there is another plotting routine that is more flexible, please let me know).
I'm looking for the equivalent of the matlab command: axis ij;
Also, I've spent a couple hours surfing matplotlib help and google but haven't come up with an answer. Some info on where I could have looked up the answer would be helpful as well.
For an image or contour plot, you can use the keyword
origin = None | 'lower' | 'upper' and for a line plot, you can set the ylimits high to low.
from pylab import * A = arange(25)/25. A = A.reshape((5,5)) figure() imshow(A, interpolation='nearest', origin='lower') figure() imshow(A, interpolation='nearest') d = arange(5) figure() plot(d) ylim(5, 0) show() | https://codedump.io/share/Rrcjks288LFF/1/matplotlib-coord-sys-origin-to-top-left | CC-MAIN-2017-09 | refinedweb | 159 | 62.38 |
There are lots of reason you may need to customize the access to given fields within an entity. For example, HIPPA compliance requires that some data not be exposed to only employees with a need to know. It is often not sufficient to just NOT show the data in the Silverlight client, you need to not even send it over the wire.
This example works with Silverlight 4\RIA Services Beta and Visual Studio 2010 Beta2
I built a very simple RIA Services + Silverlight 4 example to show how this could be done. First, let’s run the app, then we can look at how we built it.
The first thing to notice is when we run it, no users are logged in, so we get no access to the data at all.
First, let’s log in as a Rocky, who is a jr. employee at our company. He should NOT have access to the social security numbers of employees, but the other information is good for him to be able to access.
As you can see, no SSNs are displayed.
Now, let’s log in as Billy, who is our HR Manager… As you can see, Billy has a need to know what the SSN is for most employees, so those are visible to him. But notice, even he can not see VP level personal information.
OK, now let’s look at how we implemented this. Really the key code is the domain service on which runs on the server:
1: [RequiresAuthentication]2: [EnableClientAccess()]3: public class EmployeesDomainService : LinqToEntitiesDomainService<NORTHWNDEntities>4: {5:6: public IQueryable<Employee> GetEmployees()7: {8: foreach (var e in this.ObjectContext.Employees)9: {10: if (!this.ServiceContext.User.IsInRole("HRManagers"))11: {12: e.SSN = null;13: }14: else if (e.Title.Contains("Vice President"))15: {16: e.SSN = null;17: }18: }19: return this.ObjectContext.Employees;20: }21:22:
In line 1, we mark this services are only accessible to users that are logged in.
In line 10, we are making sure that only the user making the request is in the role that enables them to have access to the SSN, if not, we null it out.
In line 14, we have a (lame) example to show accessing data on the entity to decide if the user should have access. In this case, even the HRManager can’t access the VP’s SSN.
Some notes on running the app:
- Download the source code
- Billy and Rocky’s passwords are “password1!”
- Be sure the refresh the page after logging in or out
- You can customize the roles by using the IIS Admin tool or the ASP.NET configuration properties on the Web solution
Enjoy!
Do you have an example of how you would handle an update?
Using this technique, what happens when Rocky updates an entity? Since the server sent null for the SSN will his update of Address, City, Birth Date cause the SSN field to be set to null in the database?
I’ve always wanted a way to do this in a declarative or programmatic fashion. After all, what you coded is a blacklist/whitelist pattern but as a functional programmatic piece tied into the data access layer. I’ve been waiting for a declarative, programmatic ACL solution for Data Entities because I have various ideas that require it.
Still, thanks for the code. I’m sure it’s a very common request.
Doesn’t this break for queries? Suppose the Silverlight client would ask for
from e in context.GetEmployees() select e.SSN
Wouldn’t that cause the service to enumerate all Employee entities, clearing the SSN, and then secondly execute a SELECT SSN FROM Employees on the database? Isn’t that the point of returning an IQueryable?
Thats nice and all, but it feels like a half-baked hack. The SSN *COLUMN* should be hidden to the user. No sense in telling them "oh btw you can’t see this data". Not to mention, they’ll go report to someone "Hey, the database deleted everyones SSN’s its all blank!"
I don’t consider this an elegant solution if it leaves the column visible to Rocky
good workaround, will be nice if can use attribute to specified and remove the properties during runtime.
This should be handled through Presentation Model, not directly through entities.
To hide column we can have additional IsSSNVisible property in presentation model and bind DataGridTextColumn.Visible to it.
Maybe their should be a feature in RIA like in SYNC framework ‘DataColumns.AddRange’ where the columns can be filtered at the server. Use this with IsInRole to return only columns required as we do in SYNC now. A better option would be to declaritavely add a [roles(role1,role2)] to the Metadata DomainService class. Either way the client side grid etc would need the ability to not display a column if the column data is missing from the ria data.
Is there any way to do this in a base class? My existing ancient C++ BOL/DAL allows for per table / per user (or user group) security customization which is stored in the db itself.
In other words, a sys admin can configure all CRUD operations of a table and all read/read-write/no-access privs on a per column basis based on a user’s name or domain group.
I would like to move to entity framework / RIA and am having trouble figuring out how to do this.
I believe in real world DBA or HR system won’t let query fields like SSN and salary. System should have views and not need to worry about application level hard coding. This could lead to big issue when adding or changing role would cause fields like ssn visible to unintended users
Alex, if you leave this sort of thing to the Presentation Model, then all the info still goes across the wire and is still available to the user with little effort.
How about implementing RequiresRole in entity metadata for property-level access? That way, the domain service could serialize only the properties that the user has access. I think thats very straight forward.
I’ve done this using a bit of AOP magic where a WCF Channel intercepts this and decides based on role/claim if the access to some data should be ommited and in this case, it would simply set this property to it’s default value.
That solution isn’t complete as some of you stated. Also when the user send the data back the DAL needs to avoid updating those fields. This proves to be a bit tricky as some ORMs don’t have the proper hooks. We were using a "hacked" version of Linq2SQL where we were manually doing all data modifications (yes it sounds ugly and you better not do it, don’t use L2S for big apps, we hit some road block and there was no way back)
The other missing part is the UI. This isn’t really for security just to provide a better user experience. We have some attached behaviors that allow us to hide any UIElement based on role/claims. It looks something like
<dg:Colum Security:Visible.
It was really easy to implement. The namespace can be confused, this isn’t about security, this is just for UserExperience.
The only way to secure your data is not sending it as Brad mentioned, which was the actual point of the blog post.
here is a solution that won’t require any changes to the domain service’s query and update methods:
[EnableClientAccess]
public class DemographicService : LinqToEntitiesDomainService<DemographicEntities>
{
protected override DemographicEntities CreateObjectContext()
{
var context = base.CreateObjectContext();
context.ObjectMaterialized +=
(s, e) =>
{
if (this.ServiceContext.User.IsInRole("Administrator"))
return; //user is Admin… no need to secure fields
Client client = e.Entity as Client;
if (client == null)
return; //not an entity we care about securing…
//suppress client ssn and medical policy number
client.Ssn = string.Empty;
client.MedicalPolicyID = string.Empty;
//reset change tracking
this.ObjectContext.ObjectStateManager
.ChangeObjectState(e.Entity, EntityState.Unchanged);
};
return context;
}
. . .
. . .
. . .
}
Excellent Jeremy, I’ll keep that in mind, it’s still a lot more work than what I would expect, but it’s a step int he right direction. I think this could be extended to provide set of strategies that knows how to deal with different types.
I’m think in something like
public class ClientSecurityProvider : SecureEntityStrategy<Client> {
public void Secure(Client entity){
client.Ssn = string.Empty;
client.MedicalPolicyID = string.Empty;
}
}
Then the framework will take care of determining which strategies to call and do set the state to UnChanged. | https://blogs.msdn.microsoft.com/brada/2009/12/08/field-level-access-with-ria-services/ | CC-MAIN-2016-44 | refinedweb | 1,437 | 63.59 |
What is a static method and when should I use one?
# staticmethod() and classmethod()
# make it easier to call one class method
class ClassA(object):
def test(this):
print this
test = staticmethod(test)
ClassA.test(4) # 4
class ClassB(object):
@classmethod
def test(self, this):
print this
ClassB.test(4) # 4
See:
Edited 8 Years Ago
by bumsfeld: n/a
That wasn't very clear to me... I thing a worded explanation would be much more useful
Edited 8 Years Ago
by mahela007: n/a
A static method is one that can be called without instantiating the class
so
>>> class T(object):
def test():
print "HI"
>>> T.test()
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
T.test()
TypeError: unbound method test() must be called with T instance as first argument (got nothing instead)
>>>
See how that doesnt work? Well we can make it work by making it into a static method
>>> class T(object):
@staticmethod
def test():
print "HI"
>>> T.test()
HI
>>>
So, hopefully that shows what it does :)
A possible use of static methods is to add constructors to a class, like in this example
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "Person({name}, {age})".format(name=self.name, age=self.age)
@staticmethod
def from_sequence(seq):
name, age = list(seq)
return Person(name, age)
@staticmethod
def from_dict(dic):
return Person(dic["name"], dic["age"])
if __name__ == "__main__":
my_tuple = ("John", 32)
my_dict = {"name":"Fred", "age":55}
anna = Person("anna", 15)
john = Person.from_sequence(my_tuple)
fred = Person.from_dict(my_dict)
for person in (anna, john, fred):
print(person)
Edited 8 Years Ago
by Gribouillis: n/a
Thanks a lot Paul T and Gribouillis.. I think this is the ideal type of answer for a forum like ... | https://www.daniweb.com/programming/software-development/threads/231308/what-is-a-static-method | CC-MAIN-2018-43 | refinedweb | 300 | 62.78 |
Creating JSON Structure (Part-2):
In our previous tutorial, we discussed creating a simple JSON file using sample data sets.
We also came to know the details about the usage of a json.Net framework for serializing data into JSON format. We leveraged C# and Visual Studio to create a simple console application to use data and key values provided by us and then serialized those key values into JSON structure. Now, let’s see what this tutorial will cover as we move ahead.
In this tutorial, we will discuss the ways to create more complex JSON structure. We will create arrays with multiple sets of data and also look into the ways to create nested structure in JSON.
Most of the JSON files used for data transmission between various systems contain more complex data structures. Thereby, learning about the complex JSON structure will help you in creating test data based on the JSON schema requirements.
What You Will Learn:
Writing the Code
We will be referencing our previous post in this tutorial. Hence I would suggest everyone to go through the earlier tutorial first, before proceeding onto this one.
We will use the same JSON data that we used in our previous tutorial. We will also follow-up on the same set of code that we wrote for our previous JSON example.
Let’s start now.!!
Adding Array with Multiple Data into JSON
To add an array to the JSON, let us add an array key to our previous data set.
Our data set will become as shown below:
Adding an array object to the JSON is similar to that of adding any other key values. Values can be assigned directly at the time of declaration of the array itself. Once the values have been assigned to an array, then the JSON newtonsoft will serialize the objects into key-value pairs.
To add the Array in the JSON, we will declare it in the “Employee” class itself. (Please refer to our previous tutorial for details)
namespace jsonCreate { class Employee { public string FirstName = "Sam"; public string LastName = "Jackson"; public int employeeID = 5698523; public string Designation = "Manager"; public string[] KnownLanguages = { "C#", "Java", "Perl" }; } }
As you can see we have directly declared the Array in the Employee class. Do not make any changes in the main method. Creating a different class for JSON object will help us in keeping objects organized.
Whenever there are changes in the JSON structure or when you want to add another set of data, all you need to do is to make the changes in that particular class file only rather than making changes all over the project. This means that your Main method will remain the same most of the time and the changes will only happen inside the classes.
Let’s execute the program and create our JSON file with the array.
Now copy the content and paste here to validate if the created JSON is valid or not.
Click on the Validate JSON button to validate it. The JSON key-value pairs will be arranged and validation will be performed on the given data set.
Performing Operations on Data before Assigning it to JSON keys
Let’s assume that we have some data and we want to perform some operation on that data before assigning it as values to the JSON keys.
In such a case, how will we do that?
For Example: Let’s say that the employee ID that we passed into the JSON is made of two parts, first three letters denote the location code and the last 4 digits denote the employee number. Concatenating both will give us the employee ID of an employee.
In case if we receive the Location code and Employee Number separately, then we will have to concatenate them together to form an employee ID. Only then we can pass it through the JSON.
In order to overcome these type of scenarios, we need to perform operations on the data before we assign it to a key.
Let’s have a look at how this can be done.
Let’s go back to our employee class and create another class, inside which we will perform all the operations.
Here we will create another class to contain and perform the operations on the employee data.
Let’s create a new class “EmployeeData”.
The class has been created, and now let’s create a method with public access specifier and return type as our class “Employee”. We have provided the method name as “EmployeeDataOps”. However, you can provide your own name. In order to make this more simpler, I am not passing any parameter within this method.
As we described the return type as a class, we will have to return an instance of the Employee class. To do that we will create a class object inside the method.
Here, we have created an object for the Employee class with the name EmpObj and at the end of the method, we have returned the object.
Let’s define two integers inside the EmployeeData class representing the Full location code and the employee number. Once declared we will use it to perform operations and then assign values to the respective keys.
int locationCode = 569; int employeeNumber = 8523;
Now, as we have the location code and the employee number, we can perform operations on them to find the employee ID. To do this we will write a simple code to concatenate both the integers.
int empID = int.Parse(locationCode.ToString() + employeeNumber.ToString());
This will simply concatenate both the integers forming the employee ID. We have stored the employee ID under the variable “empID”, and now we will pass this variable to “employeeID” in EmpObj.
Employee EmpObj = new Employee(); EmpObj.employeeID = empID; return EmpObj;
The whole sample code will look as shown below:
Did you notice that we have removed the value that we earlier assigned to the employeeID variable in the Employee class? We did this as we are returning the value from EmployeeDataOps() method. Hence, the data to the variables will be fed from this method itself. This removes the necessity of directly declaring values.
As we are done with the method now, we will need to add an instance of this method to the main method so that this method can be called.
To do this we will create another class object in the main method for “EmployeeData” class.
EmployeeData empData = new EmployeeData();
Once we have created a class object, we will now assign the method inside this class to the Emp object that we created earlier for the employee class.
emp = empData.EmployeeDataOps();
Finally, the code inside the main method will resemble like this:
Let’s put some test data:
Location Code = 123
Employee Number = 9874
We will put this data into the code and with the final changes in the main method. We have now completed our code. Now, let us run the code and validate our JSON.
This is the JSON that was created:
As you can see, the new concatenated value for the employee ID has been entered into the JSON value.
Let’s copy and paste this JSON here to validate its structure. Put the text into the JSON lint site.
Use the validate button to validate the structure as shown below:
Creating a Nested JSON Structure
The example that we discussed until now uses mainly string and numeric values inside an array or object. But JSON can also be used to express an entire JSON object by using the same notion as an array element. The object members inside the list can use their own objects and array keys.
In Introduction to JSON which is one of our earlier tutorials, we had a first look at how a nested JSON looks like. In that tutorial, we assume that the employee also has a Car and the JSON should contain all the details about the employee car also.
So the JSON structure that we get at the end will be similar to this:
Here, we have the employee JSON with all the data, then we also have a Car JSON object nested inside the employee JSON. Car object has its own set of keys and values.
Let’s try to create this JSON programmatically.
For this, we will start with the same JSON that we created in our previous tutorial. To make it easier we will create the new JSON object (i.e. Car JSON) in a new class. We will add a new class car and will add all the objects inside this class with a public access specifier.
Now, we can either add the value directly over here or we can write a new class and create a custom method with a class object return type to assign the values similar to what we did in the previous tutorial. For the sake of convenience, we will assign the value directly to the key variables.
Now we have created a new class with the objects and values. In the next step, we will add this to the Employee JSON structure, so that when the JSON serialization happens, the key-values from the Car class should also get serialized along with the employee class as nested JSON.
In order to do that, first, we will need to add a class type object car in the Employee class. This object will be used to store the values present in the Car class.
As shown above, we have assigned the new variable with data type as Car class. Now let’s go to the EmployeeDataOps() method that we created inside the EmployeeData class. We will write the code to call the variables and values from the Car class.
First, let’s create a class object for car class:
Car carObj = new Car();
This object will contain all the data from the car class. Once we have declared all the data from the car class into this object the next step will be to assign this data (data contained inside the car object) to the car variable that we created for holding this data.
In order to do this, we will simply use the Employee object that we created to access the car variable. And then we can directly assign the car object with the data to the to the car variable.
EmpObj.car = carObj;
That’s it. We have created a variable in one class then created another object to access the value from another class, then we assigned the value to the first variable.
Now, let us run our program and see if it can create the desired JSON.
As shown above, we see that a car json key has been created and it contains all the data that we entered in the Car class as the key and values. Now, we will again copy the JSON content and navigate here to validate the JSON.
Just copy all the JSON content into the text area and click on the “Validate JSON” button.
So, the JSONlint site has arranged our data and validated it perfectly. We can see that the “car” object has been arranged in the JSON structure as we required. Using the same process, you can create multiple levels of nested JSON. Just keep on adding the JSON object to the class and assign its value to a class variable.
As you can see we don’t even have to change any code in our main method.
Using an Excel Sheet as Data Source for JSON
In our previous tutorials, we discussed several ways to create different structures of JSON. But there was a big issue with all our structures, we were always hard coding the values for the keys.
In this tutorial, we will discuss the ways through which we can use an excel sheet to feed the data to the JSON keys. I would recommend you to go through all the tutorials that we discussed earlier before proceeding with this one as we will be discussing the same code that we wrote in the previous tutorials.
Going on a step by step basis will help you in understanding the whole concept in a better way.
I hope you guys have understood the basic code to create a JSON, in this part we will take forward the same code structure.
First, let’s create an excel file with JSON data.
We have created an employeeData.xlsx file with the following details.
Before we start writing the code for extracting values from the excel, we will need to add an assembly reference to our project. To access office object, C# offers us the Microsoft Office Interop. These are quite helpful in providing easy access to the office objects.
As we are using excel in this project, we will use Microsoft Office Interop Excel assembly reference.
To install it, right click on the References in your solution explorer and then select Manage NuGet Packages. Write Microsoft Office Interop Excel in the search bar and the search result will display the required package.
Once you get Microsoft Office Interop Excel click on the Install button to install it.
Once the installation is complete, you can see that the Microsoft Office Interop Excel has been added to the list of assembly references in the project.
To start with, let’s first assign the different excel elements.
Microsoft.Office.Interop.Excel.Application xlApp; Microsoft.Office.Interop.Excel.Workbook xlWorkBook; Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
Here, we have assigned values to the Excel application, excel workbook and excel worksheet. Once these are defined, we will be using these in our next steps to access the values in the excel sheet.
What are the steps that we generally follow, if we want to fetch a value from an excel sheet?
First, we access the excel application, then we open the excel workbook and the excel worksheet and later we locate the element based on its row and column values. We are going to do something similar here.
This code will access the excel application.
xlApp = new Microsoft.Office.Interop.Excel.Application();
This code will open up the workbook with the given name present at the given location.
xlWorkBook = xlApp.Workbooks.Open(@"D:\json\ employeeData.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Now, we will write a code to access the particular worksheet inside the workbook. We have a worksheet named “Sheet1” ( the default name in the excel sheet)
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets["Sheet1"];
As we have accessed the WorkSheet, now the next step will be to find the correct column and the correct data. First, we will search for a column with the “Key”.
For Example, First, let’s search for the column with value as “FirstName”. Once we find the value, we will extract the column number. Then as we know the first row contains the heading and the second row contains our data, so, we will use the column number and the row number to extract the exact data.
This will store the column number for the FirstName in the variable.
var colmnVal = xlWorkSheet.Columns.Find("FirstName").Cells.Column;
Now, we will use the column number of the FirstName to extract the value from the cell below it. As the know, the value method will only return string type, so we will store this in a string variable.
string frstName = xlWorkSheet.Cells[2, colmnVal].Text.ToString();
Now, we have the value of the First Name stored in the variable. So, we will use the employee object that we defined in our method to assign the value.
Please remove all the values that you have assigned/hardcoded in the Employee class as we will be returning the values using our method.
But there is one issue with this, the “.Text” function always returns a string value. So, if we want to extract the value of an employee ID which is an integer, it will also be extracted as a string. So, we will have to convert this string into an integer before assigning it to the JSON object. To do that we will directly parse the value to an integer.
So, the code for employeeID will look as shown below:
var colmnEmpID = xlWorkSheet.Columns.Find("employeeID").Cells.Column; string emplyID = xlWorkSheet.Cells[2, colmnEmpID].Text.ToString(); int emplyIDint = Int32.Parse(emplyID);
At the end, we will parse the string value to an integer as our JSON recognizes employeeID as an integer value.
So, the overall code for fetching data for all 4columns will look as shown below:
Now, all we need to do is to assign the variables that we created with the data from the excel sheet to the employee objects.
Everything is set, we will now build the project. Once the build is complete we will execute the program to generate the JSON.
Following JSON will be generated:
Now, let’s compare the data from the JSON with that in the excel sheet.
As shown above, the JSON data matches the data in all 4 columns of the excel sheet. Let’s validate the JSON that our program has generated. To do that we will again visit here. Just copy all the JSON content into the text area and click on the “Validate JSON” button.
Hurray! We have created a valid JSON using the data from the excel.
Exercise for you:
Create a three-level nested JSON. Create a parent JSON Company and nest the employee JSON that we created earlier along with the car JSON.
Conclusion
We have now reached the end of our tutorial. It has been a long tutorial but we learned several things. We learned how to create a simple JSON using c# programming and the benefits of categorizing different sets of JSON data into a different class. We also used our programming skills to add arrays and even another JSON structure inside a parent JSON.
Lastly, we worked on the ways to fetch data from another data source to feed the values to the JSON keys.
Hope you all enjoyed the whole series of JSON tutorials so far.
Tutorial #4: Using JSON for Interface Testing | https://www.softwaretestinghelp.com/create-json-structure-using-c/ | CC-MAIN-2021-17 | refinedweb | 3,040 | 62.78 |
I have a great VBscript which will list all my Exchange 2003 mailboxes with a size under a given size.
I have another great VBscript which accepts a list of users and sets the quotas for each of those users.
Can anyone fill in the gap, and point me in the direction of a method (VBscript or otherwise) by which I can set the quota for all users who have a mailbox under a certain limit?
I'm trying to reduce my mailbox limits, and want to start by enforcing that limit for users who are already below it. That way the bigger problem of getting people below the new limit doesn't get any bigger!
Update: Thanks to Evan Anderson I found that I need to convert my GUID to another format for use in an LDAP lookup. Microsoft have a knowledge base article that explains how to do this, but I don't have GUIDs in the required format. There is another kb article that describes "how to convert a string formatted GUID to a hexadecimal string form for use when querying the active directory", but the script throws an error.
Update 2: Ok - forget the VB script. I found a more succinct way to get my data using PowerShell.
$computers = "vexch01","vexch02"
foreach ($computer in $computers) {
Get-Wmiobject -namespace root\MicrosoftExchangeV2 -class Exchange_Mailbox -computer $computer | sort-object -desc Size | select-object MailboxDisplayName,StoreName,@{Name="Size/Mb";Expression={[math]::round(($_.Size / 1024),2)}}, MailboxGUID | Export-Csv -notype -Path $computer.csv
}
Currently this outputs the MailboxGUID as a string type GUID (e.g. {21EC2020-3AEA-1069-A2DD-08002B30309D}). I want to look up users in AD by this, but AD stores them in octetBytes format.
I have found some powershell functions which will do the conversion but only when the curly braces are removed. The Guid.ToString method should supply this, but I can't get it to work in the above.
However, if I could figure out how to do that, the Guid.ToByteArray method might get me even closer.
Has anyone cracked this?
Without seeing your scripts it's difficult to give you a "turn key" solution. You'll probably be able to match up user accounts to mailboxes by doing an LDAP search against the msExchMailboxGuid attribute, depending on whether or not your mailbox size script can return that. That GUID will disambiguously pair a mailbox and AD user account across your entire Exchange organization.
msExchMailboxGuid
By posting your answer, you agree to the privacy policy and terms of service.
asked
2 years ago
viewed
1045 times
active | http://serverfault.com/questions/304202/how-to-get-ad-users-from-a-list-of-exchange-2003-mailboxes/304213 | CC-MAIN-2014-23 | refinedweb | 433 | 62.88 |
The API
Getting an Auth Key
To generate an authentication key, you have to go to autocompeter.com and sign in using GitHub.
Once you've done that you get access to a form where you can type in your domain name and generate a key. Copy-n-paste that somewhere secure and use when you access private API endpoints.
Every Auth Key belongs to one single domain.
E.g.
yoursecurekey->.
Submitting titles
You have to submit one title at a time. (This might change in the near future)
You'll need an Auth Key, a title, a URL, optionally a popularity number and optionally a group for access control..
The URL you need to do a HTTP POST to is:
The Auth Key needs to be set as a HTTP header called
Auth-Key.
The parameters need to be sent as
application/x-www-form-urlencoded.
The keys you need to send are:
Here's an example using
curl:
curl -X POST -H "Auth-Key: yoursecurekey" -d url= \ -d title="A blog post example" \ -d group="loggedin" \ -d popularity="105" \
Here's the same example using Python requests:
response = requests.post( '', data={ 'title': 'A blog post example', 'url': '', 'group': 'loggedin', 'popularity': 105 }, headers={ 'Auth-Key': 'yoursecurekey' } ) assert response.status_code == 201
The response code will always be
201 and the response content will be
application/json that simple looks like this:
{"message": "OK"}
Uniqueness of the URL
You can submit two "documents" that have the same title but you can not submit two documents that have the same URL. If you submit:
curl -X POST -H "Auth-Key: yoursecurekey" \ -d url= \ -d title="This is the first title" \ # now the same URL, different title curl -X POST -H "Auth-Key: yoursecurekey" \ -d url= \ -d title="A different title the second time" \
Then, the first title will be overwritten and replaced with the second title.
About the popularity
If you omit the
popularity key, it's the same as sending it as
0.
The search will always be sorted by the
popularity and the higher the number
the higher the document title will appear in the search results.
If you don't really have the concept of ranking your titles by a popularity or hits or score or anything like that, then use the titles "date" so that the most recent ones have higher priority. That way more fresh titles appear first.
About the groups and access control and privacy
Suppose your site visitors should see different things depending how they're signed in. Well, first of all you can't do it on per-user basis.
However, suppose you have a set of titles for all visitors of the site
and some extra just for people who are signed in, then you can use
group
as a parameter per title.
Note: There is no way to securely protect this information. You can make it so that restricted titles don't appear to people who shouldn't see it but it's impossible to prevent people from manually querying by a specific group on the command line for example.
Note that you can have multiple groups. For example, the titles that is
publically available you submit with no
group set (or leave it as
an empty string) and then you submit some as
group="private" and some
as
group="admins".
How to delete a title/URL
If a URL hasn't changed by the title has, you can simply submit it again. Or if neither the title or the URL has changed but the popularity has changed you can simply submit it again.
However, suppose a title needs to be remove you send a HTTP DELETE. Send it to the same URL you use to submit a title. E.g.
curl -X DELETE -H "Auth-Key: yoursecurekey" \
Note that you can't use
application/x-www-form-urlencoded with HTTP DELETE.
So you have to put the
?url=... into the URL.
Note also that in this example the
url is URL encoded. The
: becomes
%3A.
How to remove all your documents
You can start over and flush all the documents you have sent it by doing
a HTTP DELETE request to the url
/v1/flush. Like this:
curl -X DELETE -H "Auth-Key: yoursecurekey" \
This will reset the counts all related to your domain. The only thing that isn't removed is your auth key.
Bulk upload
Instead of submitting one "document" at a time you can instead send in a whole big JSON blob. The struct needs to be like this example:
{ "documents": [ { "url": "", "title": "Page One" }, { "url": "", "title": "Other page", "popularity": 123 }, { "url": "", "title": "Last page", "group": "admins" }, ] }
Note that the
popularity and the
group keys are optional. Each
dictionary in the array called
documents needs to have a
url and
title.
The endpoint to use and you need to do a
HTTP POST or a HTTP PUT.
Here's an example using curl:
curl -X POST -H "Auth-Key: 3b14d7c280bf525b779d0a01c601fe44" \ -d '{"documents": [{"url":"/url", "title":"My Title", "popularity":1001}]}' \
And here's an example using Python requests:
import json import requests documents = [ { 'url': '/some/page', 'title': 'Some title', 'popularity': 10 }, { 'url': '/other/page', 'title': 'Other title', }, { 'url': '/private/page', 'title': 'Other private page', 'group': 'private' }, ] print requests.post( '', data=json.dumps({'documents': documents}), headers={ 'Auth-Key': '3b14d7c280bf525b779d0a01c601fe44', } ) | https://autocompeter.readthedocs.io/en/latest/api/ | CC-MAIN-2020-10 | refinedweb | 889 | 59.94 |
Well here's a pretty simple problem, how do you go from a
i) classification problem with a single output from your model, and a
output
loss = nn.CrossEntropyLoss(output, labels)
loss = nn.CrossEntropyLoss(output, labels)
ii) to a regression problem with a mu, and sigma2 (mean & variance) output from your model, which then goes through
mu
sigma2
y_pred = torch.normal( mu, sigma2.sqrt() )
y_pred = torch.normal( mu, sigma2.sqrt() )
and
loss = F.smooth_l1_loss(y_pred, labels)
loss = F.smooth_l1_loss(y_pred, labels)
Basically I want to change a MNIST classifier into regression exercise which outputs a Gaussian distribution. The bit that's tripping me up is that the output y_pred is now is now stochastic, so I guess I need a .reinforce() on it, but I still don't not get how to do this?
y_pred
.reinforce()
Here's the relevant bit of my code,
def forward(self, x):
# Set initial states
h0 = Variable(torch.zeros(self.num_layers*2, x.size(0), self.hidden_size)) # 2 for bidirection
c0 = Variable(torch.zeros(self.num_layers*2, x.size(0), self.hidden_size))
# Forward propagate RNN
out, _ = self.lstm(x, (h0, c0))
# Decode hidden state of last time step
mu = self.mu( out[:, -1, :] )
sigma2 = self.sigma2( out[:, -1, :] )
return mu, sigma2
rnn = BiRNN(input_size, hidden_size, num_layers, num_classes)
# Loss and Optimizer
optimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate)
# Train the Model
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = Variable(images.view(-1, sequence_length, input_size))
labels = Variable( labels.float() )
# Forward + Backward + Optimize
optimizer.zero_grad()
#outputs = rnn(images)
mu, sigma2 = rnn(images)
sigma2 = (1 + sigma2.exp()).log() # ensure positivity
y_pred = torch.normal( mu, sigma2.sqrt() )
y_pred = y_pred.float()
#y_pred = Variable( torch.normal(mu, sigma2.sqrt()).data.float() )
loss = F.smooth_l1_loss( y_pred , labels )
loss.backward()
optimizer.step()
and the compile error,
File "main_v1.py", line 90, in <module>
loss.backward()
File "/home/ajay/anaconda3/envs/pyphi/lib/python3.6/site-packages/torch/autograd/variable.py", line 158, in backward
self._execution_engine.run_backward((self,), (gradient,), retain_variables)
File "/home/ajay/anaconda3/envs/pyphi/lib/python3.6/site-packages/torch/autograd/stochastic_function.py", line 13, in _do_backward
raise RuntimeError("differentiating stochastic functions requires "
RuntimeError: differentiating stochastic functions requires providing a reward
It's modified from
yunjey/pytorch-tutorial/blob/master/tutorials/07%20-%20Bidirectional%20Recurrent%20Neural%20Network/main.py
OR, perhaps I'm making it more complicated than it needs to be with the Gaussian thing? Should I just stick an encoder on the output of the LSTM ???
Thanks a lot
I'm not sure I understand exactly what you want to do, but would the same reparametrisation trick as in the VAE paper and implementations (e.g. pytorch/examples) work with the "usual" procedure?You would convert standard normal randoms to a variable and then transform them with mu and sigma2. That way, the randoms are fixed w.r.t. the differentiation.
Hi @tom that's what I think too!
I'll give it a try
I'm fed up of all this .reinforce stuff !!!
.reinforce
Just to be a bit more clear, what I want to learn is a mapping from images to single real numbers y_pred, and those real number should be as close to the labels/class indices labels of the images as possible, as measured by loss = F.smooth_l1_loss(y_pred, labels)
labels
Cheers
Well the error should be quite self-explanatory, you haven't provided the reward to the stochastic output. Cal .reinforce(reward) on y_pred, but before you cast it! Casts return a new Variable and it's no longer a stochastic output!
.reinforce(reward)
Thanks @apaszke !!! That's helpful.
My confusions, actually conceptual/the way I setup the problem - I haven't figured out what the reward should be in this context!
reward
It's nothing to do with PyTorch, I just haven't thought carefully enough about what I'm actually trying to do here - I was carrying over an idea from continuous action reinforcement learning, and it doesn't seem to make sense in the context of regression? | https://discuss.pytorch.org/t/how-to-transform-classification-into-regression/1218 | CC-MAIN-2017-39 | refinedweb | 674 | 51.65 |
Sunday 28 October 2012
Multiple): pass
The method resolution order of RealTestCase is:
Since:
The question remaining in my mind: would class hierarchies be better if the
top-most classes (derived from object) used the defensive super style? Or
is that overkill that defers rather than removes the pain? Would something
else bite me later?
Can you elaborate about why listing the mixin before the base class "looks odd"? (I don't have the same experience.) It seems like the entire problem you've described here hinges on that.
@Michael, when I think of my RealTestCase class, it is mostly a TestCase, with MyMixin mixed in. To me, it's most natural to talk about TestCase first.
Multiple implementation inheritance is indicative of poor design. Even more generally speaking, inheritance should never be the construct of choice for re-use. Inheritance imposes extremely tight coupling between parent and child, as you indicated by saying "details about base classes that you thought were abstracted away from you can suddenly be critical to understand".
Inheritance should model a true, intensional generalization relationship. In your case, the discriminator between various subclasses of TestCase is only extensional, i.e. a minor detail about coincidental setup/teardown implementation.
Remember the heuristic "favor association over inheritance". For example, you could pass a setup/teardown implementor into your various test case classes (something like a Strategy pattern).
I guess I'm in the minority but I disagree that multiple inheritance is "so difficult" or "indicative of poor design."
I just keep in mind that python searches for methods and attributes left-to-right through the list of inherited classes (obviously a simplification of the MRO algorithm, but it's good enough,) so the most-base class goes on the right. Call super() when overriding methods, and everything tends to Just Work. It's a bit hand-wavey I know, but Python hasn't let me down yet.
@Eric, thanks for reminding me of the "composition over inheritance" maxim, I need to keep that in mind more. In this case, I can't pass an implementor into the test classes, because I don't own the code that constructs them, but I could certainly reference an implementor instead.
What prevented you from making MyMixin a subclass of BaseTestCase and inheriting singly from MyMixin?
@Russell: in this case I could have, but I've wanted a way to separate the setUp and tearDown details from the main line of inheritance. Probably I should go all the way to composition instead, as Eric suggests.
@eric: I'm glad I'm not the only one that feels composition over inheritance is a better reu-use model.
Just putting my vote in for "multiple inheritance is just fine". The "multiple inheritance is a design flaw" meme IMHO is one of those rules people created under the justification of "if practice X confuses anyone, is poorly implemented in language Q, or generally can ever be mis-used by anyone anywhere, then it is always bad for everyone, all the time, in all languages" - and it has its roots within C++ where it developed a bad reputation. That's not an architectural straightjacket I'm willing to accept.
I use multiple inheritance usually for mixins (where I find it quite natural to apply them first, as I typically want their methods to take precedence), and more often than not in test code also (funny how it finds itself there quite a bit, as in this blog post). In *extremely rare* cases I do have some cases (well just one I can think of) where a particular subclass is truly an amalgam of two distinct parent hierarchies. I certainly don't do that lightly.
I had the exact same problem and did exactly this, swap the order in which the base classes were introduced.
I've never fully understood MRO and how metaclasses affect it, it's supposed to be useful in this cases.
I also wonder if this changes in some way in Python3 with the new super().
To echo Michael Lamb, there's a fundamental misunderstanding here about the ordering of the superclass list: it's not accidental, or freely alterable.
In Python (and any C3 class system), every class declaration should be read as a single partial order: class A(B, C) should be understood to mean that A < B < C, without putting special weight on A. (It can help to mentally ignore the parentheses and actually read the syntax as "class A < B < C: ...", when in doubt.)
In other words, the implication that B becomes a subclass of C is just as important and meaningful as the implication that A becomes a subclass of B. In particular, the question of swapping B and C around is no different in general than the question of swapping A and B around, and can have equally large repercussions.
Looking back at the example:
class RealTestCase(BaseTestCase, MyMixin):
class MyMixin(object):
def setUp(self):
super(MyMixin, self).setUp()
class MyMixin(unittest.TestCase, object) # MyMixin < TestCase < object
class MyMixin(unittest.TestCase) # equivalent shorthand
class Foo(MyMixin, unittest.TestCase) # MyMixin < TestCase
class Bar(MyMixin, BaseTestCase) # MyMixin < BaseTestCase (< TestCase)
Regarding the use of super() in TestCase.setUp(), it should never be sensical to attempt a super-call in a base method implementation.
super() only exists to allow subclasses to call and extend methods that already exist in their superclasses: there may be any number of super-calls, but by definition, the super-calls must eventually stop at a base class that first introduces the method, without using any super-calls.
In this example, TestCase is the class that actually introduces setUp() and tearDown(): all its subclasses (and only its subclasses) can use super() to extend those methods, but TestCase itself provides them from scratch.
Samus: None of this changed in Python 3, except that super() no longer requires any arguments in the default case.
Thanks all for the thoughtful comments. As usual, half of what I learned was before I wrote the post, and half after. The idea that Mixin must derive from TestCase is an interesting one. On the one hand, I see how that solves problems, ironically by introducing a dreaded diamond to the hierarchy. On the other hand a Mixin is not itself a TestCase, and isn't meant to be used as one. I invoke super.setUp because I know the class is only ever meant to be mixed into an actual TestCase.
I wanted to thank Ned for introducing the topic and Piet for explaining it so greatfully.
Best wishes.
Deriving Mixin from (TestCase,object) doesn't introduce a diamond, because new-style classes don't have diamonds: they have linearized MROs.
When Python creates a new style class, it "sorts" the diamonds into a linear ordering, such that the resulting list has the same ordering relationships found in every multiple inheritance declaration in the entire tree.
Thus, by making the mixin derive from (TestCase,object), you are telling Python that TestCase must always come before object and *after* the mixin in every subclass of Mixin. Thus, TestCase will never shadow the mixin's methods.
It is basically a rule in Python (because of the MRO) that you list mixin classes *first*. So doing it the other way round always looks odd to me. Composition is fine, but it's generally *more work* than inheritance because you have to explicitly delegate rather than have Python do it for you.
"""when I think of my RealTestCase class, it is mostly a TestCase, with MyMixin mixed in. To me, it's most natural to talk about TestCase first"""
It seems to make sense to me that the last parent is the "most fundamental," and that minor contributions to behavior should precede them, thus modifying the behaviors of the "principal" parent. But that's just me.
Hey Ned,
If you decide to go down the "association instead of inheritance" route, could you make sure to post the final product? I'm JUST BARELY starting to scratch the surface of that paradigm and seeing a real world example would be tremendously helpful.
Also, thank you so much for all you do for the python community. I can't tell you how much I've appreciated coverage.py alone!
When I write mixin classes I try to avoid make them change the original workflow of the class.
In this case, I would add the common code in a method, say "prepare_something()", on the mixin class, and call it from TestCase setUp(). I like to think of mixins as away to offer more features to the class, and not change the class original features. This is a different use case than Piet Delport explained above.
class MyMixin(object):
def prepare_something(self):
#.. do something here ..
def restore_something(self):
#.. do something here ..
class BaseTestCase(unittest.TestCase, MyMixin):
def setUp(self):
super(BaseTestCase, self).setUp()
self.prepare_something()
def tearDown(self):
self.restore_something()
super(BaseTestCase, self).tearDown()
class RealTestCase(BaseTestCase):
def test_foo(self):
#.. etc ..
Thanks Ned,
I ran into this *exact* issue earlier this year. Having the mixin first does look weird, but it works.
Thanks for publishing this and hopefully saving some others a bit of time.
2012,
Ned Batchelder | http://nedbatchelder.com/blog/201210/multiple_inheritance_is_hard.html | CC-MAIN-2015-32 | refinedweb | 1,538 | 54.42 |
Hi all,
We are having a bit of trouble with sending triggers to the EEG recorder. We are using psychopy 1.83.4
On each trial we show 5 images, the first 2 are pre-masks and the last 2 are post-masks which are followed by the participant response
We want to send the trigger during the presentation of the 3rd image (which is the target) and also during the response. The problem is that were are missing a lot of triggers for the target image.
Please find the script attached. Could you please take a look? Below I put some notes to localise the relevant bits of code, Any comments would be much appreciated.
Note that regarding the trigger for the target image onset, we use this function in line 421
def sendCode(code,dur):
parallel.setData(code)
core.wait(dur)
parallel.setData(0)
in combination with: win.callOnFlip(sendCode, int(temp_correctAns),0.001) # in line 431
Later in line 671 we send the triggers for the response
if response.keys == "1": trigger_code = 3 elif response.keys == "2": trigger_code = 4 parallel.setData( int(trigger_code)) win.logOnFlip(level=logging.EXP,msg="rep trigger {}".format(int(trigger_code))) core.wait(0.01) parallel.setData(int(0))
Many thanks
DavidExpEEG_pilot.py (38.7 KB) | https://discourse.psychopy.org/t/eeg-missing-triggers/7072 | CC-MAIN-2021-39 | refinedweb | 212 | 50.33 |
Last edited: March 15th 2018Last edited: March 15th 2018
Newton's law of gravitation states that the force between two point masses is proportional to the product of their masses and inversely proportional to the square of the distance between them. This can be written as\begin{equation} F= G\frac{m_1m_2}{r^2}, \label{eq:newton_grav} \end{equation}
where $m_1$ and $m_2$ is the masses of the particles, $r$ is the distance between them and $G$ is some constant known as the gravitational constant. The force is directed along the line intersecting the point masses. It can be shown that this law holds for all spherically symmetric mass distributions, such as solid balls. The equation above can even be applied to the gravitational pull between stars and other celestial bodies with high accuracy! The current recommended value by CODATA for the gravitational constant is $(6.674 08 \pm 0.000 31)\cdot 10^{-11} \text{Nm$^2$/kg$^2$}$ [1]. This is a small number, and measuring the gravitational constant thus requires extremely precise equipment.
The first direct laboratory measurement of the gravitational constant was performed in 1798 by Henry Cavendish [2]. The apparatus in the original experiment consisted of a 1.8 meter long wooden arm with two lead balls about 5 cm in diameter attached on either side. The wooden arm was suspended in a horizontal position from a 1 meter long wire. This is known as a torsion pendulum. Two large lead balls was used to exert a gravitational pull on the torsion pendulum, making it rotate. Due to the torque in the wire, the pendulum began to oscillate around its new equilibrium position.
A similar experiment is performed by all first year physics students at NTNU. In this notebook we will discuss the Cavendish experiment. We will create a model that describes the oscillation of the torsion pendulum and by using curve fitting on a set of measurements, we will estimate the period of the oscillation and its equilibrium position. This will in turn be used to estimate the gravitational constant. The theory section is to a large extent based on the laboratory manual used in the course FY1001 Mechanical Physics at NTNU (see ref. [3]). We start by briefly discussing experimental setup (we refer to the Laboratory Manual for a more complete review of the experiment).
The apparatus used at NTNU is similar to the one used by Cavendish. The experiment is in principle performed in the following way. The two large lead balls of mass $M$ are set in position 1, as shown in figure 1. The torsion pendulum will begin to oscillate around some equilibrium angle $\theta_1$. A laser beam is reflected on a mirror attached to the torsion pendulum, and hits a ruler at a position $S(t)$. The position on the ruler is recorded every 30 seconds. When the system is at rest, the lead spheres are set in position 2, making the pendulum oscillate around $\theta_2$.
Figure 1. The figure to the left is a schematic diagram of the torsion pendulum used in the experiment, directed along the torsion wire. (1) Torsion wire, (2) mirror, (3) large lead balls, (4) small lead balls, (5) laser beam. The entire setup can be seen in the figure to the right. Position 1 is shown in solid lines and position 2 is shown in dashed lines. The equilibrium position in the absence of the large lead balls is along the horizontal dotted line. The figures are taken from the Laboratory Manual in the course F1001 Mechanical Physics at NTNU (ref. [2]).
Let's import needed packages and set common figure parameters before we proceed to derive a model that describes the damped oscillation of the pendulum.
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit %matplotlib inline # Set some figure parameters newparams = {'figure.figsize': (18, 9), 'axes.grid': False, 'lines.markersize': 6, 'lines.linewidth': 2, 'font.size': 15, 'mathtext.fontset': 'stix', 'font.family': 'STIXGeneral'} plt.rcParams.update(newparams)
As mentioned in the introduction, Cavendish used a torsion pendulum (also called a torsion balance) in his measurements. When the rotational angle (the torsion angle) $\theta$ is small, its torque $\vec \tau = \vec F\cdot\vec r$ is approximately proportional to $\theta$. That is,\begin{equation} \label{eq:torsion_pendulum} \tau_1 =-D\theta, \end{equation}
for some constant $D$, called the torsion constant. This is analogous to Hooke's law for a spring.
The air resistance of an object is approximately proportional to the velocity at small velocities. This relation is called Stoke's law. The torque due to air resistance is thus proportional to the angular velocity $\dot \theta$. That is,\begin{equation} \tau_2 = -b\dot\theta. \label{eq:air_resistance} \end{equation}
We neglect friction in the torsion wire.
Newton's second law for rotation reads,\begin{equation} \sum \tau_i = I\ddot\theta, \label{eq:N2_rotation} \end{equation}
where $I$ is the moment of inertia, in our case given by $I=2mr^2$ (two spherically symmetric masses $m$ at a distance $r$ from the reference point). By combining the equations \eqref{eq:torsion_pendulum}, \eqref{eq:air_resistance} and \eqref{eq:N2_rotation}, we obtain the differential equation\begin{equation} I\ddot\theta + b\dot\theta+D\theta = 0, \label{eq:diff_eq} \end{equation}
which describes the oscillation of the torsion pendulum. The general solution can in this case be written as\begin{equation} \theta(t) = \theta_0 e^{-\alpha t}\sin\left(\omega t+\phi\right), \label{eq:model_theta} \end{equation}
where $\theta_0$ is the initial amplitude, $\phi$ is some phase factor, $\omega\equiv\sqrt{\omega_0^2-\alpha^2}$, $\alpha \equiv b/2I$ and $\omega_0 \equiv\sqrt{D/I}$. The oscillation is in our case underdamped (see e.g. [4] for more information), which means that $\omega^2 = \omega_0^2-\alpha^2>0$. This is confirmed by the measured data.
In the actual experiment we do not measure $\theta$, but $S$ as a position of the laser beam on a ruler (see figure 1). The position $S$ is given by\begin{equation} S/L=\tan\theta\approx \theta \label{eq:S_approx} \end{equation}
when $L\ll S$ (see exercise 1). We therefore obtain\begin{equation} S(t) = S_0 + A e^{-\alpha t}\sin\left(\omega t + \phi\right). \label{eq:model_S} \end{equation}
def osc(t, S_0, A, alpha, omega, phi): # Model for harmonic oscillations return S_0 + A*np.exp(-alpha*t)*np.sin(omega*t + phi)
The period of the oscillation is $T=2\pi/\omega$. The parameters $\phi$, $\omega$, $\alpha$, $A$ and $S_0$ can be estimated using curve fitting of the model on the measured data. There are several ways to perform curve fitting in Python. In this notebook we will be using optimize.curve_fit from SciPy, which uses non-linear least squares to fit a function to data. The function has three input parameters: the model function (osc), the measured $x$-data (t) and the measured $y$-data (S). In addition, we will use the optional argument p0, which is the initial guess for the parameters. The function returns an array of the optimal values for the parameters (params) and a corresponding covariance matrix (cov). The diagonals of the covariance matrix provide the variance of the parameter estimates. The standard deviation is in turn given by the square root of the variances.
def fit(S, t, params_init=[1,1,1,1,1]): """ Performs curve fitting of the function osc() on the data points stored in S. Parameters: S: array-like vector, len(N). The measured displacement as a function of time. t: array-like vector, len(N). Time corresponding to the measurements in S. params_init: Initial guess for the parameters. Returns: params: Parameters which minimizes the quadratic error (best fit). cov: Covariance matrix for the parameters. """ try: params, cov = curve_fit(osc, t, S, p0=params_init) return params, cov # curve_fit will return a RuntimeError if it can't estimate the parameters. except RuntimeError as err: print("Fit failed.") return params_init, np.zeros(len(params_init), len(params_init))
# Read data from file with time in minutes in first column, time in # seconds in second column and swing in third column # Position 1 data = np.loadtxt('S1data.txt') t1data = data[:, 0]*60 + data[:, 1] S1data = data[:, 2]*0.001 # m # Position 2 data = np.loadtxt('S2data.txt') t2data = data[:, 0]*60 + data[:, 1] S2data = data[:, 2]*0.001 # m
We are now ready to perform the curve fit!
# Initial values for fit (educated guesses) S0_0 = 3.50e+00 # Equilibrium line A0 = 0.3 # Amplitude, swing Alpha0 = 0.001 # Exponential damping coefficient for the amplitude T0 = 600 # Swing period phi0 = 0 # Phase angle params_init = [S0_0, A0, Alpha0, 2*np.pi/T0, phi0] # Fit model parameters to data params1, cov1 = fit(S1data, t1data, params_init) # POSITION 1 err1 = np.sqrt(np.diag(cov1)) params2, cov2 = fit(S2data, t2data, params_init) # POSITION 2 err2 = np.sqrt(np.diag(cov2))
Let's make a plot!
# Position 1 t = np.linspace(t1data[0], t1data[-1], 200) plt.plot(t, params1[0]*np.ones(len(t)), '--', color='0.6') plt.plot(t, osc(t, *params1), '-', color=(.5,.5,1), label='Fit position 1') plt.plot(t1data, S1data, 'o', color=(0,0,1), label='Position 1 data') # Position 2 t = np.linspace(t2data[0], t2data[-1], 200) plt.plot(t, params2[0]*np.ones(len(t)), '--', color='0.6') plt.plot(t, osc(t, *params2), '-', color=(1,.5,.5), label='Fit position 2') plt.plot(t2data, S2data, 'o', color=(1,0,0), label='Position 1 data') plt.xlabel('Time, (s)') plt.ylabel('Displacement, (mm)') plt.legend(loc='best') plt.show()
Consider for the moment only the gravitational force $F_0$ between the large lead balls and the nearest small balls (that is, neglect $f$ in figure 2). From figure 2 it is clear that the torque on the pendulum due to the gravitational force $F_0$ must be equal to the torque due to the torsion wire (equation \eqref{eq:torsion_pendulum}) at equilibrium (when the system is at rest). That is $2F_0r=D\theta_1=D\theta_2$. By making use of equation \eqref{eq:S_approx}, we obtain\begin{equation} F_0 = \frac{D}{r}\cdot\frac{\theta_1+\theta_2}{4}\approx \frac{D}{r}\cdot\frac{S}{4L}. \label{eq:F0} \end{equation}
Figure 2. The large ball acts on the nearest small ball with a gravitational force $F_0$. There is also a gravitational pull $F_0'$ from the opposite large ball with a component $f$ that reduces the total torque on the pendulum. The figure is taken from the Laboratory Manual in the course F1001 Mechanical Physics at NTNU (ref. [2]).
We assume for simplicity that $\sqrt{\omega_0^2-\alpha^2}\approx \omega_0=\sqrt{D/I}$ in equation \eqref{eq:model_theta} (see exercise 2 and 3). The torsion constant can in this case be written as\begin{equation} D = \frac{4\pi^2 I}{T^2}. \label{eq:torsion_const} \end{equation}
If we insert equation \eqref{eq:F0} and \eqref{eq:torsion_const} and $I=2mr^2$ into Newton's law of Gravitation \eqref{eq:newton_grav} and solve for $G$, we obtain\begin{equation} G = \frac{r^2}{F_0mM}=\frac{\pi^2b^2rS}{T^2LM}, \label{eq:grav_const} \end{equation}
where $m$ is the mass of the small lead balls, $M$ is the mass of the large lead balls and $b$ is the distance between the masses $m$ and $M$. Note that $m$ is canceled in the final expression.
The component $\vec f$ of $\vec F_0'$ parallel to $\vec F_0$ lowers the total torque on the pendulum and gives a small correction to equation \eqref{eq:grav_const}. From figure 2 is is clear that$$f = F_0'\cdot\frac{b}{r'},$$
where $r'=\sqrt{b^2+4r^2}$ is the distance between the balls. If we insert this into the Newton's law of Gravitation \eqref{eq:newton_grav}, we obtain$$f = G\frac{mM}{b^2+4r^2}\cdot\frac{b}{\sqrt{b^2+4r^2}}= G\frac{mM}{b^2}\cdot\frac{b^3}{(b^2+4r^2)^{3/2}}=F_0\cdot \beta,$$
where $\beta\equiv b^3/(b^2+4r^2)^{3/2}$. The total force on each of the small balls are thus $F' = F_0-f = F_0(1-\beta)$. By comparing with equation \eqref{eq:grav_const}, we a corrected expression for the gravitational constant,\begin{equation} G = \frac{1}{1-\beta}\cdot\frac{\pi^2b^2rS}{T^2LM}. \label{eq:grav_const_corr} \end{equation}
$L$, $M$, $b$ and $r$ is found by measuring on the apparatus used in the experiment. The measured quantities corresponding to the data used in this notebook are defined in the following code snippet.
We store these quantities as arrays of length 2, with the first position being the value and the second position being the uncertainty.
b = [0.042, 0.001 ] # m r = [0.050, 0.0001] # m L = [2.265, 0.01 ] # m M = [1.493, 0.002 ] # kg
In addition, we need to extract the difference in equilibrium positions $S=|S_{01}-S_{02}|$ and the period $T$ from the curve fit performed earlier.
We can extract $T_1$, $T_2$, $S_{01}$ and $S_{02}$ and their standard deviations (uncertainties) from params1, err1, params2 and err2. The period is given by $T_i=2\pi/\omega_i$, and their uncertainties are related by $\Delta T/T = \delta \omega/\omega\Rightarrow \Delta T = \Delta\omega\cdot2\pi/\omega^2$.
S01 = (params1[0], err1[0]) S02 = (params2[0], err2[0]) print("S01 = ( %.4f ± %.5f ) mm"%(S01)) print("S02 = ( %.4f ± %.5f ) mm"%(S02)) T1 = (2*np.pi/params1[3], 2*np.pi/params1[3]**2*err1[3]) T2 = (2*np.pi/params2[3], 2*np.pi/params2[3]**2*err1[3]) print("T1 = ( %.2f ± %.2f ) s"%(T1)) print("T2 = ( %.2f ± %.2f ) s"%(T2))
S01 = ( 0.3587 ± 0.00025 ) mm S02 = ( 0.4471 ± 0.00020 ) mm T1 = ( 651.53 ± 3.02 ) s T2 = ( 636.84 ± 2.88 ) s
The physical setup is the same in position 1 and position 2, and we would therefore expect that $T_1\approx T_2$. Note however that the estimated values of $T_1$ and $T_2$ differs by almost 15 seconds. This indicates that the uncertainty in the period is larger than the standard deviation in the fit. We will therefore use $$T = (T_1+T_2)/2, \qquad\Delta T = |T_2-T_1|/2,$$ as the period of the oscillations and its uncertainty.
The only error estimate we have for the equilibrium positions $S_{01}$ and $S_{02}$ are the standard deviation from the fit. We will therefore use $$S = |S_{02} - S_{01}|,\qquad \Delta S = \sqrt{\Delta S_{01}^2 + \Delta S_{01}^2}.$$
Note that we have not taken errors in the measurements into count. Better results for the uncertainties is obtained if the experiment is repeated.
S = (abs(S01[0] - S02[0]), (S01[1]**2 + S02[1]**2)**.5) print("S = ( %.2e ± %.1e ) mm"%(S)) T = ((T1[0] + T2[0])/2, abs(T1[0] - T2[0])/2) print("T = ( %.2f ± %.2f ) s"%(T))
S = ( 8.84e-02 ± 3.2e-04 ) mm T = ( 644.19 ± 7.34 ) s
We now insert these quantaties into equation \eqref{eq:grav_const_corr} in order to estimate the gravitational constant $G$.
beta = b[0]**3*(b[0]**2+4*r[0]**2)**(-3/2.) G = 1/(1 - beta)*np.pi**2*b[0]**2*r[0]*S[0]/(T[0]**2*L[0]*M[0]) print("G = %.2e m^3/(kg s^2)"%(G))
G = 5.82e-11 m^3/(kg s^2)
This is in the same order of magnitude as the recommended value from CODATA $(6.674 08 \pm 0.000 31)\cdot 10^{-11} \text{Nm$^2$/kg$^2$}$. The gravitational constant is quite difficult to measure and the experiment is influenced by many systematic errors [5]. Moreover, the measurement was conducted during a laboratory session in a room full of people. This is not ideal conditions!
Since we have acquired the uncertainty in all the quantities used in equation \eqref{eq:grav_const_corr}, we can also compute the uncertainty in $G$. This is left as an exercise for the reader (exercise 4 and 5).
There are several exercises in the Laboratory Manual (ref. [3]). Check them out!
[1] Mohr, Peter J., Newell, David B. & Taylor, Barry N. (2016). CODATA recommended values of the fundamental physical constants: 2014. Rev. Mod. Phys., 88, 035009. See.
[2] Cavendish, Henry. Philosophical Transactions 17, 469 (1798). Note that the goal of the original experiment was to measure the density of the Earth. However, one can express his result in terms of the gravitational constant.
[3] Herland, Egil V., Sperstad, Iver B., Gjerden, Knut, et al.: Laboratorium i emne FY1001 mekanisk fysikk. NTNU 2016. URL:
[4] Hyperphysics.phy-astr.gsu.edu: Damped Harmonic Oscillator [Online]. [retrieved Sep. 2017]
[5] Cross, William D. Systematic Error Sources in a Measurement of G using a Cryogenic Torsion Pendulum. University of California 2009. URL: | https://nbviewer.jupyter.org/urls/www.numfys.net/media/notebooks/cavendish.ipynb | CC-MAIN-2019-43 | refinedweb | 2,809 | 50.73 |
I am having a problem with a Python assignment. I have a working program for an auto inventory using a nested dictionary for my inventory.
auto_inv = {0:{‘year’: 0, ‘make’:’’,‘model’:’’,‘color’: ‘’, ‘mileage’: 0}} where the zero key is the inventory number. I can add to it, delete from it, modify inventory, print the inventory or save it to a text file. It works great!
There is a problem though, the assignment wants me to use a class with a main function and an init. I cannot seem to get from the working program into a class Automobile. I have tried different things and get different errors when I try different things. I guess I am saying that I don’t understand the passing of variables to a class, and returning the dictionary key I need to add to my inventory dictionary. Here is the class as I have it written:
class Automobile: # This stuff doesn’t work… and I don’t know how to make it work.
def init(self): #initialize private variables
self._make = " "
self._model = " "
self._color = " "
self._year = 0
self._mileage = 0
def add_auto(self, year, make, model, color, mileage):#collects information about the car try: self._make = input('Enter make of auto: ')# My code gets to here and spits out a typeError. self._model = input('Enter model of auto: ') self._year = int(input('Enter year of auto: ')) self._color = input('Enter color of auto: ') self._mileage = int(input('Enter mileage of auto: ')) count = count +1 new_auto= '' auto_inv[count] = {} auto_inv[count] ['year']= self._year auto_inv[count] ['make']= self._make auto_inv[count] ['model']= self._model auto_inv[count] ['color']= self._color auto_inv[count] ['mileage']= self._mileage print(' ') auto_inv.pop(0, None) print(auto_inv) return auto_inv[count] except ValueError: print('You entered an incorrect type, please try again') count = count-1 def __str__(self): #Formats the output for printing of inventory return(self.year, self.make, self.model, self.color, self.mileage)
Now I am not sure I understand the str thing yet, but I am trying to return these variables in this iteration. I did have it returning a dictionary key, but I couldn’t get as far as entering the model name without an error. I am passing the count as an argument, as I need count to be the key so that it is the correct inventory number.
I’m not even sure the proper way to call the add_auto() method. I have watched videos on lyndadotcom, i’ve re-read the textbook chapter. I just don’t understand it. I feel like some key element to calling a class is not sinking in. | https://www.freecodecamp.org/forum/t/problem-with-python-class-usage/257451/4 | CC-MAIN-2019-22 | refinedweb | 438 | 58.89 |
MySQL 8.0 Release Notes
For general information about upgrades, downgrades, platform support, etc., please visit.
Deprecation and Removal Notes
Functionality Added or Changed
Lock handling for statements involving the grant tables was improved. (Bug #31291237, Bug #31576185)
Modifying the
mysql.infoschema and
mysql.sys reserved accounts now requires the
SYSTEM_USER privilege.
(Bug #31255458)
For the
CREATE USER,
DROP USER, and
RENAME USER account-management
statements, the server now performs additional security checks
designed to prevent operations that (perhaps inadvertently)
cause stored objects to become orphaned or that cause adoption
of stored objects that are currently orphaned. Such operations
now fail with an error. If you have the
SET_USER_ID privilege, it
overrides the checks and those operations produce a warning
rather than an error; this enables administrators to perform the
operations when they are deliberately intended. See
Orphan Stored Objects.
For JSON-format log files, MySQL Enterprise Audit supports log-reading
operations using the
audit_log_read() user-defined
function. Previously, specifying the position at which to begin
reading was possible only by passing to
audit_log_read() an argument
containing a bookmark indicating the exact timestamp and event
ID of a particular event. For greater flexibility, the argument
now can be a start specifier that names any timestamp, to read
starting from the first event that occurs on or after that
timestamp. See Reading Audit Log Files.
The MySQL client library now includes a
mysql_real_connect_dns_srv() C
API function that is similar to
mysql_real_connect() but uses a
DNS SRV record to determine the candidate hosts for establishing
a connection to a MySQL server, rather than explicit host, port,
and socket arguments.
Applications that use the C API can call the new function
directly. In addition, the mysql client
program is modified to use DNS SRV capability; it now supports a
--dns-srv-name option that takes
precedence over
--host and causes
the connection to be based on a DNS SRV record. See
mysql_real_connect_dns_srv().
Connection establishment in other contexts is unaffected,
including connections made by replicas, the
FEDERATED storage engine, and client programs
other than mysql.
Visual Studio 16.4 is now the minimum version for MySQL compilation. (Bug #31655401)
The minimum version of the Boost library for server builds is now 1.73.0. (Bug #31309800)
The new
WITH_TCMALLOC
CMake option indicates whether to link with
-ltcmalloc. If enabled, built-in
malloc(),
calloc(),
realloc(), and
free()
routines are disabled. The default is
OFF.
WITH_TCMALLOC and
WITH_JEMALLOC are mutually
exclusive.
(Bug #31785166)
The new
COMPRESS_DEBUG_SECTIONS
CMake option indicates whether to compress
the debug sections of binary executables (Linux only).
Compressing executable debug sections saves space at the cost of
extra CPU time during the build process. The default is
OFF. If this option is not set explicitly but
the
COMPRESS_DEBUG_SECTIONS environment
variable is set, the option takes its value from that variable.
(Bug #31498296)
The
WITH_DEFAULT_FEATURE_SET
CMake option was removed.
(Bug #31122507)
On platforms that implement network namespace support (such as Linux), MySQL now enables configuring the network namespace for TCP/IP connections from client programs to the MySQL server or X Plugin:
On the server side, the
bind_address,
admin_address, and
mysqlx_bind_address system
variables have extended syntax for specifying the network
namespace to use for a given IP address or host name on
which to listen for incoming connections.
For client connections, the mysql client
and the mysqlxtest test suite client
support a
--network-namespace
option for specifying the network namespace.
For replication connections from replica servers to source
servers, the
CHANGE MASTER TO
statement supports a
NETWORK_NAMESPACE
option for specifying the network namespace.
For replication monitoring purposes, the Performance Schema
replication_connection_configuration table,
the replica server connection metadata repository (see
Replication Metadata Repositories), and the
SHOW
REPLICA | SLAVE STATUS statement have a new column
that displays the applicable network namespace for connections.
For more information, including the host system prerequisites that must be satisfied to use this feature, see Network Namespace Support.
The InnoDB memcached plugin is deprecated and support for it will be removed in a future MySQL version.
The
INFORMATION_SCHEMA.TABLESPACES
table is unused. It is now deprecated and will be removed in a
future MySQL version. Other
INFORMATION_SCHEMA tables may provide related
information, as described in
The INFORMATION_SCHEMA TABLESPACES Table.
MySQL Enterprise Edition now includes a
keyring_oci plugin that
uses Oracle Cloud Infrastructure Vault as a back end for keyring storage. No key
information is permanently stored in MySQL server local storage.
All keys are stored in Oracle Cloud Infrastructure Vault, making this plugin well
suited for Oracle Cloud Infrastructure MySQL customers for management of their MySQL Enterprise Edition
keys. For more information, see The MySQL Keyring.
Important Change:
A prepared statement is now prepared only once, when executing
PREPARE, rather than once each
time it is executed. In addition, a statement inside a stored
procedure is also now prepared only once, when the stored
procedure is first executed. This change enhances performance of
such statements, since it avoids the added cost of repeated
preparation and rollback of preparation structures, the latter
being the source of several bugs.
As part of this work, the manner in which dynamic parameters used in prepared statements are resolved is changed, with the resulting changes in prepared statement use cases listed here:
A parameter used in a prepared statement has its data type determined when the statement is prepared, and the type persists for each subsequent execution of the statement, unless the statement is reprepared (see PREPARE Statement, for information about when this may occur).
For a prepared statement of the form
,
passing an integer value
expr1,
expr2, ... FROM
table ORDER BY ?
N for
the parameter no longer causes ordering of the results by
the
Nth
expression in the select list; the results are no longer
ordered, as is expected with
ORDER BY
.
constant
The window functions
NTILE(NULL),
NTH_VALUE(,
expr,
NULL)
LEAD(, and
expr,
nn)
LAG(, where
expr,
nn)
nn is a negative number, are now
disallowed, to comply with the SQL standard.
A user variable that is read by a prepared statement now has its type determined when the statement is prepared; the type persists for each subsequent execution of the statement.
A user variable that is read by a statement within a stored procedure now has its type determined the first time the statement is executed; the type persists for all subsequent invocations of the containing stored procedure.
For parameters for which no contextual information is
available to determine the parameter type, the server
assumes the parameter is a character string with the default
character set, not a binary string. Parameters for which
this is incorrect may be placed within a
CAST() expression.
See PREPARE Statement, for the rules governing how the effectiue data types of parameters and user variables used within prepared statements are determined.
In addition, the rows (
N) argument to
the window functions
LAG(),
LEAD(), and
NTILE() must now be an integer in
the range
1 to
263, inclusive, in
any of the following forms:
an unsigned integer constant literal
a positional parameter marker (
?)
a user-defined variable
a local variable in a stored routine
In addition, this argument no longer accepts
NULL as a value. See the descriptions of the
functions just referenced for more information.
(Bug #48612, Bug #99601, Bug #100150, Bug #11756670, Bug #23599127, Bug #31119132, Bug #31365678, Bug #31393719, Bug #31592822, Bug #31810577)
The
filesort algorithm now supports sorting a
join on multiple tables, and not just a single table.
(Bug #31310238, Bug #31559978, Bug #31563876)
When using a
RIGHT JOIN, some internal
objects, were not converted to those suitable for use with a
LEFT JOIN as intended. These included some
lists of tables built at parse time, but which did not have
their order reversed. This required maintaining code to handle
instances in which a
LEFT JOIN was originally
a
RIGHT JOIN as special cases, and was the
source of several bugs. Now the server performs any necessary
reversals at parse time, so that after parsing, a
RIGHT
JOIN is in fact, in all respects, a
LEFT
JOIN.
(Bug #30887665, Bug #30964002)
References: See also: Bug #12567331, Bug #21350125.
Added support for periodic synchronization when writing to files
with
SELECT INTO
DUMPFILE and
SELECT INTO OUTFILE
statements. This feature can be enabled by setting the
select_into_disk_sync system
variable to
ON; the size of the write buffer
cn be set using the server system variable
select_into_buffer_size; the
default buffer size is 131072 (217)
bytes. An optional delay following synchronization to disk can
also be set using the
select_into_disk_sync_delay
system variable; the default behaviour is not to allow any delay
(that is, a delay time of 0 milliseconds).
For more information, see the descriptions of the system variables referenced previously.
Our thanks to Facebook for this contribution to MySQL 8.0. (Bug #30284861)
MySQL now implements derived condition pushdown for eligible
queries. What this means is that, for a query such as
SELECT * FROM (SELECT i, j FROM t1) AS dt WHERE i >
, it is now
possible in many cases to push the outer
constant
WHERE condition down to the derived table, in
this case resulting in
SELECT * FROM (SELECT i, j FROM
t1 WHERE i > . Previously, if the derived table was materialized
and not merged, MySQL materialized the entire table—in
this case
constant) AS
dt
t1—then qualified the rows
with the
WHERE condition.
When the derived table cannot be merged into the outer query
(for example, if the derived table uses aggregation), pushing
the outer
WHERE condition down to the derived
table can reduce the number of rows that need to be processed,
which should improve the query's performance.
An outer
WHERE condition can be pushed down
directly to a materialized derived table when the derived table
uses no aggregate or window functions. In addition, when the
derived table has a
GROUP BY and uses no
window functions, the outer
WHERE condition
can be pushed down to the derived table as a
HAVING condition. If the derived table uses a
window function and the outer
WHERE
references columns used in the window function's
PARTITION clause, the
WHERE condition can also be pushed down.
This optimization cannot be employed for a derived table that
contains a
UNION or
LIMIT clause.
To enable derived condition pushdown, the
optimizer_switch system
variable's
derived_condition_pushdown
flag (added in this release) must be set to
on. This is the default setting. If this
optimization is disabled by the optimizer switch setting, you
can enable it for a specific query using the
DERIVED_CONDITION_PUSHDOWN
optimizer hint (also added in this release). Use the
NO_DERIVED_CONDITION_PUSHDOWN
optimizer hint to disable the optimization for a given query.
For further information and examples, see Derived Condition Pushdown Optimization. (Bug #59870, Bug #88381, Bug #11766303, Bug #27590273)
For RPM and Debian packages, client-side plugins were moved to their own client-plugins package. (Bug #31584093)
The
VERSION file in MySQL source
distributions is now named
MYSQL_VERSION
due to a naming conflict with Boost.
(Bug #31466846)
For platforms on which systemd is used to run MySQL, packages no
longer include legacy System V files: the
mysqld_multi.server and
mysql.server scripts, and the
mysql.server.1,
mysqld_multi.1, and
mysqld_safe.1 man pages.
(Bug #31450888)
The
SHOW PROCESSLIST statement
provides process information by collecting thread data from all
active threads. However, because the implementation iterates
across active threads from within the thread manager while
holding a global mutex, it has negative performance
consequences, particularly on busy systems.
An alternative
SHOW PROCESSLIST
implementation is now available based on the new Performance
Schema
processlist table. This
implementation queries active thread data from the Performance
Schema rather than the thread manager and does not require a
mutex:
To enable the alternative implementation, enable the
performance_schema_show_processlist
system variable.
The alternative implementation of
SHOW
PROCESSLIST also applies to the
mysqladmin processlist command.
The alternative implementation does not apply to the
INFORMATION_SCHEMA
PROCESSLIST table or the
COM_PROCESS_INFO command of the MySQL
client/server protocol.
To ensure that the default and alternative implementations yield the same information, certain configuration requirements must be met; see The processlist Table.
An SQL interface to the most recent events written to the MySQL
server error log is now available by means of queries on the new
Performance Schema
error_log table.
This table has a fixed size, with old events automatically
discarded as necessary to make room for new ones. The table is
populated if error log configuration includes a log sink
component that supports this capability (currently the
traditional-format
log_sink_internal and
JSON-format
log_sink_json sinks). Several new
status variables provide information about
error_log table operation. See
The error_log Table.
These changes were made for the LDAP authentication plugins:
For the SASL LDAP authentication plugin, the
SCRAM-SHA-1 authentication method is not
supported on On SLES 12 and 15 and EL6 systems. The default
method on those systems is now
GSSAPI.
If the LDAP host is not set, the LDAP connection pool will not be initialized, which enables successful authentication plugin installation in cases when previously it would fail. (This might be the case when a site installs a plugin first, then configures it later.)
If an LDAP connection parameter is changed at runtime, the LDAP connection pool is reinitialized for the first subsequent authentication attempt.
If the LDAP server is restarted, existing connections in the connection pool become invalid. The LDAP authentication plugin detects this case and reinitializes the connection pool and (for the SASL LDAP plugin) the SASL challenge is resent.
(Bug #31664270, Bug #31219323)
The parser now supports parenthesized query expressions using this syntax:
(
query_expression) [
order_by_clause] [
limit_clause] [
into_clause]
Other variations are possible; see Parenthesized Query Expressions (Bug #30592703)
It is now possible to cast values of other types to
YEAR, using either the
CAST() function or the
CONVERT() function. These
functions now support
YEAR values of one or
two digits in the range 0-99, and four-digit values in the range
1901-2155. Integer 0 is converted to Year 0; a string consisting
of one or more zeroes (following possible truncation) is
converted to the year 2000. Casting adds 2000 to values in the
range 1-69 inclusive, and 1900 to values in the range 70-99
inclusive.
Strings beginning with one, two, or four digits followed by at
least one non-digit character (and possibly other digit or
non-digit characters) are truncated prior to conversion to
YEAR; in such cases, the server emits a
truncation warning. Floating-point values are rounded prior to
conversion;
CAST(1944.5 AS YEAR) returns 1945
due to rounding, and
CAST("1944.5" AS YEAR)
returns 1944 (with a warning) due to truncation.
DATE,
DATETIME, and
TIMESTAMP are cast to the
YEAR portion of the value. A
TIME value is cast to the current
year. Not specifying the value to be cast as a
TIME value may yield a different result from
what is expected;
CAST("13:47" AS YEAR)
returns 2013 due to truncation of the string value, and
CAST(TIME "13:47" AS YEAR) returns 2020 as of
the year of this release.
Casting of
GEOMETRY values to
YEAR is not supported. A cast of an
incompatible type or an out-of-range or illegal value returns
NULL.
YEAR can also be used as the return type for
the
JSON_VALUE() function. This
function supports four-digit years only, and otherwise follows
the same rules as apply to
CAST() and
CONVERT() when performing casts to
YEAR.
For more information, see the description of the
CONVERT() function.
When selecting a
TIMESTAMP column
value, it is now possible to convert it from the system time
zone to a UTC
DATETIME when
retrieving it, using the
AT TIME ZONE
operator which is implemented for the
CAST()
function in this release.
The syntax is
CAST(,
where the
value AT
TIME ZONE
specifier AS
DATETIME[(
precision)])
value is a
TIMESTAMP, and the
specifier is one of
[INTERVAL] '+00:00' or
'UTC'. (
INTERVAL is
optional with the first form of the specifier, and cannot be
used with
'UTC'.) The
precision of the
DATETIME value returned by the cast can
optionally be specified up to 6 decimal places.
Values that were inserted into the table using a timezone offset are also supported.
AT TIME ZONE cannot be used with
CONVERT(), or in any other
context other than as part of a
CAST()
function call. The
ARRAY keyword and creation
of multi-valued indexes are also not supported when using
AT TIME ZONE.
A brief example is shown here:
mysql>
SELECT @@system_time_zone;+--------------------+ | @@system_time_zone | +--------------------+ | EDT | +--------------------+ 1 row in set (0.00 sec) mysql>
CREATE TABLE ex (ts TIMESTAMP);Query OK, 0 rows affected (0.81 sec) mysql>
INSERT INTO ex VALUES>
ROW(CURRENT_TIMESTAMP),>
ROW('2020-07-31 21:44:30-08:00');Query OK, 2 rows affected (0.09 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql>
TABLE ex;+---------------------+ | ts | +---------------------+ | 2020-07-28 21:39:31 | | 2020-08-01 01:44:30 | +---------------------+ 2 rows in set (0.00 sec) mysql>
SELECT ts, CAST(ts AT TIME ZONE 'UTC' AS DATETIME) AS ut FROM ex;+---------------------+---------------------+ | ts | ut | +---------------------+---------------------+ | 2020-07-28 21:39:31 | 2020-07-29 01:39:31 | | 2020-08-01 01:44:30 | 2020-08-01 05:44:30 | +---------------------+---------------------+ 2 rows in set (0.00 sec)
For more information and examples, see the description of the
CAST() function in the
MySQL Manual.
In specific conditions, terminating an X Protocol connection could cause MySQL Server to stop unexpectedly. (Bug #31671503)
LOCK TABLES privilege checking
for views was improved.
(Bug #31304432)
You can use MySQL Server's new asynchronous connection failover
mechanism to automatically establish an asynchronous (source to
replica) replication connection to a new source after the
existing connection from a replica to its source fails. The
connection fails over if the replication I/O thread stops due to
the source stopping or due to a network failure. The
asynchronous connection failover mechanism can be used to keep a
replica synchronized with multiple MySQL servers or groups of
servers that share data, including asynchronous replication from
servers where Group Replication is in use. To activate
asynchronous connection failover for a replication channel set
SOURCE_CONNECTION_AUTO_FAILOVER=1 on the
CHANGE MASTER TO statement for the channel,
and set up a source list for the channel using the
asynchronous_connection_failover_add_source
and
asynchronous_connection_failover_delete_source
UDFs.
The new
innodb_extend_and_initialize
variable permits configuring how
InnoDB
allocates space to file-per-table and general tablespaces on
Linux. By default, when an operation requires additional space
in a tablespace,
InnoDB allocates pages to
the tablespace and physically writes NULLs to those pages. This
behavior affects performance if new pages are allocated
frequently. As of MySQL 8.0.22, you can disable
innodb_extend_and_initialize on
Linux systems to avoid physically writing NULLs to newly
allocated tablespace pages. When
innodb_extend_and_initialize is
disabled, space is allocated using
posix_fallocate() calls, which reserve space
without physically writing NULLs.
A
posix_fallocate() operation is not atomic,
which makes it possible for a failure to occur between
allocating space to a tablespace file and updating the file
metadata. Such a failure can leave newly allocated pages in an
uninitialized state, resulting in a failure when
InnoDB attempts to access those pages. To
prevent this scenario,
InnoDB writes a redo
log record before allocating a new tablespace page. If a page
allocation operation is interrupted, the operation is replayed
from the redo log record during recovery.
To permit concurrent DML and DDL operations on MySQL grant tables, read operations that previously acquired row locks on MySQL grant tables are now executed as non-locking reads. The operations that are now performed as non-locking reads on MySQL grant tables include:
SELECT statements and other
read-only statements that read data from grant tables
through join lists and subqueries, including
... FOR SHARE statements, using any transaction
isolation level.
DML operations that read data from grant tables (through join lists or subqueries) but do not modify them, using any transaction isolation level.
Statements that no longer acquire row locks when reading data from grant tables report a warning if executed while using statement-based replication.
When using
-
binlog_format=mixed, DML
operations that read data from grant tables are now written to
the binary log as row events to make the operations safe for
mixed-mode replication.
FOR SHARE statements that read data from grant tables
now report a warning. With the
FOR SHARE
clause, read locks are not supported on grant tables.
DML operations that read data from grant tables and are executed
using the
SERIALIZABLE
isolation level now report a warning. Read locks that would
normally be acquired when using the
SERIALIZABLE isolation level
are not supported on grant tables.
From MySQL 8.0.22, the
group_replication_ip_whitelist system
variable is deprecated, and the system variable
group_replication_ip_allowlist has been added
to replace it. The system variable works in the same way as
before, only the terminology has changed.
For both system variables, the default value is
AUTOMATIC. If either one of the system
variables has been set to a user-defined value and the other has
not, the changed value is used. If both of the system variables
have been set to a user-defined value, the value of
group_replication_ip_allowlist is used.
From MySQL 8.0.22, the statements
START
SLAVE,
STOP SLAVE,
SHOW
SLAVE STATUS,
SHOW SLAVE HOSTS and
RESET SLAVE are deprecated. The following
aliases should be used instead:
Instead of
START SLAVE use
START
REPLICA
Instead of
STOP SLAVE use
STOP
REPLICA
Instead of
SHOW SLAVE STATUS use
SHOW REPLICA STATUS
Instead of
SHOW SLAVE HOSTS use
SHOW REPLICAS
Instead of
RESET SLAVE use
RESET
REPLICA
The statements work in the same way as before, only the terminology used for each statement and its output has changed.
New status variables have been added as aliases for the related status variables. Both the old and new versions of the statements update both the old and new versions of these status variables:
Com_slave_start is equivalent to
Com_replica_start
Com_slave_stop is equivalent to
Com_replica_stop
Com_show_slave_status is equivalent to
Com_show_replica_status
Com_show_slave_hosts is equivalent to
Com_show_replicas
The
ALTER DATABASE statement now
supports a
READ ONLY option that controls
whether to permit modification of a database and objects within
it. This option is useful for database migration because a
database for which
READ ONLY is enabled can
be migrated to another MySQL instance without concern that the
database might be changed during the operation. See
ALTER DATABASE Statement.
A new
INFORMATION_SCHEMA table named
SCHEMATA_EXTENSIONS displays
database options. Currently, it displays
READ
ONLY=1 for read-only databases. See
The INFORMATION_SCHEMA SCHEMATA_EXTENSIONS Table.)
InnoDB: A query that updated the clustered index of an internal temporary table returned an incorrect result. The modified pages of the clustered index were not added to the flush list resulting in lost changes when the modified pages were evicted from the buffer pool. (Bug #31560679)
References: This issue is a regression of: Bug #29207450.
InnoDB:)
InnoDB:
An
ALTER TABLE ...
IMPORT TABLESPACE operation on a large encrypted and
compressed table failed with a Page decompress failed
after reading from disk error. The decryption
operation did not use the encryption block size used during
encryption. Also, the encryption process did not consider
compressed length, while the decryption process decrypts data by
compressed length only.
(Bug #31313533)
InnoDB: A failure occurred during a concurrent update operation. The failure was due to an invalid previous record value. (Bug #31205266, Bug #99286)
InnoDB:)
InnoDB:
The buffer control block structure
(
buf_block_t) was freed while reducing the
size of the buffer pool, causing an assertion failure. The fix
for this bug also backports important aspects of the fix for Bug
#20735882 / Bug #76343, and replaces the internal
buf_block_is_uncompressed() function with the
buf_pointer_is_block_field_instance()
function. The
buf_block_is_uncompressed()
function returned false in too many cases, affecting OLTP query
throughput.
(Bug #31036301, Bug #31389823)
InnoDB: Parallel read threads failed to respond to an explicit transaction interruption. (Bug #31016076)
InnoDB:
In session started with
START TRANSACTION WITH
CONSISTENT SNAPSHOT, a range query returned a
truncated result. The end range flag was not reset at the
beginning of the index read resulting in an aborted read and
missing rows.
(Bug #30950714, Bug #98642)
References: This issue is a regression of: Bug #23481444.
InnoDB: A full-text phrase search raised an assertion failure. Thanks to TXSQL (Tencent MySQL) for the contribution. (Bug #30933728, Bug #31228694)
References: This issue is a regression of: Bug #22709692.
InnoDB:
A: A long running statistics calculation operation on a large table blocked other operations requiring access to the table's statistics, causing those operations to fail. A new statistics calculation mutex was introduced, which permits concurrent access table statistics. Thanks to Kamil Holubicki for the contribution. (Bug #30607708)
InnoDB: Two connections attempted to use the same transaction handler object resulting in a stalled query. (Bug #30594501), after the remote cloning operation completes, wait two minutes to allow a round of garbage collection to take place to reduce the size of the group's certification information. Then issue the following statement on the joining member, so that it stops trying to apply the previous set of certification information:
RESET SLAVE FOR CHANNEL group_replication_recovery;
statement to the binary log
to that effect. Previously, this was a
DELETE statement, but it is now a
TRUNCATE TABLE statement. A
replica server also writes this statement to its own binary log
when it shuts down and restarts. The statement is always logged
in statement format, even if the binary logging format is set to
ROW, and it is written even if
read_only or
super_read_only mode is set on the server.
(Bug #29848785, Bug #95496)
Replication:
When the system variable
session_track_gtids was set to
OWN_GTID on a multithreaded replica, the
replica’s performance would degrade over time and begin to lag
behind the master. The cause was the buildup of the GTIDs
recorded by the replica’s worker threads at each transaction
commit, which increased the time taken by the worker threads to
insert new ones. Session state tracking is now disabled for
worker threads on a multithreaded replica. Thanks to Facebook
for the contribution.
(Bug #29049207, Bug #92964) could sometimes trigger an
assertion in the range optimizer.
(Bug #31586906)
column
> (... IN (SELECT ...))
was simplified as
condition.
A coding problem introduced in MySQL 8.0.20 could cause client applications to exit unexpectedly during shutdown. (Bug #31515752)
References: This issue is a regression of: Bug #27045306.
was not handled correctly.
(Bug #31425664)
const FROM
table WHERE
column=FROM_UNIXTIME(
value))
After the fix for Bug #81009, privilege checks for truncating
Performance Schema tables were too restrictive when
read_only or
super_read_only were enabled,
causing truncation to fail even for users with appropriate table
privileges.
(Bug #31080309, Bug #99072)
References: This issue is a regression of: Bug #81009. and
max_sort_length were set to
values which caused the internal limit on the maximum number of
keys allowed per sort buffer to be set to 0.
(Bug #30175483)
A large number of nested arguments in full-text search query caused an error. (Bug #29929684)) | https://docs.oracle.com/cd/E17952_01/mysql-8.0-relnotes-en/news-8-0-22.html | CC-MAIN-2020-50 | refinedweb | 4,479 | 51.58 |
Minimal CloudStack Access Library and Utilities
Project description
Makes it easy to connect to Apache CloudStack. Tested with version 4.2 and later.
Includes helper scripts to work with zones and hosts and helps you get started with your own scripts.
Alternatives
This library makes it easy to create quick utilities for Operational and Development purposes. For an interactive shell you should try cloudmonkey or shell scripting you can try cs.
Installation
pip install minicloudstack
Quickstart
Export the following environment variables (alternatively arguments can be used):
export CS_API_URL="" export CS_API_KEY="1235..." export CS_SECRET_KEY="abcdef..."
Start your python shell (python or ipython).
import minicloudstack mcs = minicloudstack.MiniCloudStack() for template in mcs.list("templates", templatefilter="featured"): print template.id, template.name
Helper scripts
Also provided are the following scripts that can be useful:
mcs-createzone mcs-deletezone mcs-registertemplate mcs-addhost mcs-volume minicloudstack
Start them with –help for detailed instructions.
Background
These scripts were created by Greenqloud when developing Qstack.
We hope you find them useful!
Greenqloud Dev Team.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/minicloudstack/ | CC-MAIN-2018-30 | refinedweb | 195 | 52.26 |
NAME
carg, cargf, cargl - calculate the complex argument
SYNOPSIS
#include <complex.h>
double carg(double complex z); float cargf(float complex z); long double cargl(long double complex z);
Link with -lm.
DESCRIPTION
These in the range of [-pi,pi].
VERSIONS
These functions first appeared in glibc in version 2.1.
ATTRIBUTES
For an explanation of the terms used in this section, see attributes(7).
CONFORMING TO
C99, POSIX.1-2001, POSIX.1-2008.
SEE ALSO
COLOPHON
This page is part of release 5.13 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | https://man.archlinux.org/man/carg.3.en | CC-MAIN-2022-40 | refinedweb | 111 | 68.87 |
Here is the code i have written to accept string from the user.
Can you please modify the code so as it can even count the space as well as print the whole line with the spaces instead of the first word.
Thanks a lot.
#include <stdio.h> #include <assert.h> #include <malloc.h> #include <conio.h> int strlength (char input[]) { int count = 0; while (input[count++] != '\0'); return count; } main ( ) { char* s = 0; char inputBuffer; int index = 0; printf("\nEnter the name u want to enter : "); while ((inputBuffer = getchar()) != '#') // some termintaing cond. { s = malloc(sizeof(char)); s[index] = inputBuffer; } printf("The length of this string is %d", strlength(s)); printf("\n"); } | https://www.daniweb.com/programming/software-development/threads/48506/continuous-string | CC-MAIN-2017-17 | refinedweb | 112 | 78.25 |
Coding is only one half of programming. Unfortunately with most programming classes only that half is being taught and the other half of programming never gets mentioned. As a result there are lots of programs written that work but which are extremely inefficient.
I have recently been looking at the sorts of questions being asked as homework for JavaScript classes and writing articles that highlight the difference between the historical JavaScript code that the teacher expects to be used for the answer and alternative ways the question could be answered using modern JavaScript. In my search for such questions I came across the following one which, rather than indicating that the JavaScript course was teaching outdated coding techniques, clearly demonstrates how the creative problem solving half of programming is being completely overlooked in many programming courses.
The question: was "Write a JavaScript program that accepts two numbers as input from the user and computes the sum of all integers between those two numbers including the two inputs." and the person asking for help with that homework was asking what type of loop to use to do the calculation.
Of course a loop isn't required to answer that question as the answer can be derived directly from the numbers at either end of the sequence.
sumRange = function(x, y) {return (y-x+1)/2*(x+y);}
Now of course this solution requires that x be less than or equal to y but so would any solution involving a loop. This solution is also more efficient for any case where the end points of the range are not equal.
Why that the creative problem solving half of programming is omitted from so many programming courses? Is it because teaching the creative half of programming is too difficult and so the courses concentrate on the easier part where strict rules apply? Can the creative problem solving part of programming actually be taught or is it a talent that tsome people are born with?
From my point of view, I agree that teaching concepts are well out of date and I too have seen examples that hail back to the 80's.
With regards to teaching the creative side, this is something that IMHO has to evolve of its own accord, like teaching a dog new tricks, you have to have persistence in training and the same applies to programming where the student has to have persistence and to keep on learning.
The other side of the coin, some people are very adept at picking up new skills effortlessly and are more inclined to try things rather than ask if something is possible, they will try and then ask why something doesn't work as they thought.
Given the right environment, people can be creative with creations, it does rely on your interests in the subject like art and artists, you have people who are creative artists and with coding you have coders that are creative with coding.
You do have more commonly an element where individuals have neither an interest or creative spark in them, these are the consumers who are the audience who criticize how crap something is and that things could be better and no matter how creative you are and cater for their needs, its still crap. There's no pleasing some people.
I can't do math. I count on my fingers to add stuff, or do things the long way I was rote-taught in school to do on paper, and even after years of wearing an analog watch, still count minutes because I still, after 30 years of practice, suck at telling time.
There's creative thinking, and there's being able to do math. If the student asking about "which for loop?" had known and understood math, then that student might have asked about javascript syntax for doing that kind of math. I think there's a difference between the two because if the basic knowledge isn't there then the most creative student in the world will, indeed, come up with a very creative, though likely cumbersome, bizaare, hard to read/maintain and innefficient, solution.
You oughtta see some of the garbage I've creatively come up with over the years to do what was probably just simple math to people who know simple math.
I found your formula (y-x+1)/2*(x+y) very interesting, so I did some research to find that it is a special case of a more general summation formula (n=number of terms)/2 (2(x=first term)+((n=number of terms)-1)*(d=difference between terms))
In your formula d=difference between terms =1 and (y-x+1) is the number of terms. As expected, it fails when the difference between terms is other than 1.
The more general formula can be written as a javascript function with three inputs
function sumIt(n,x,d) { return n/2 *(2*x+(n-1)*d); }
These are the results wheren= number of terms to be summedx= the first term of the seriesd= the common difference between terms
Positive integers, difference of 1sumIt(3, 1, 1) = 6; or 1 + 2 + 3sumIt(4, 1, 1) = 10; or 1 + 2 + 3 + 4
Positive integers, difference of 2sumIt(3, 1, 2) = 9; or 1 + 3 + 5sumIt(4, 1, 2) = 16; or 1 + 3 + 5 + 7
Positive and negative integers, difference of 2sumIt(5, -1, 2) = 15; or -1 + 1 + 3 + 5 + 7
Positive and negative integers and npn-integers, difference of +0.5sumIt(5, 1, 0.5) = 10; or 1.0 + 1.5 + 2.0 + 2.5 + 3.0sumIt(6, -2.0, 0.5) = -4.5; or -2.0 + -1.5 + -1.0 + -0.5 + 0 + 0.5
I still think a loop is easier. | http://community.sitepoint.com/t/creative-problem-solving/39939 | CC-MAIN-2014-41 | refinedweb | 963 | 61.6 |
gxt 3.x + ios fullscreen -> stopped working
gxt 3.x + ios fullscreen -> stopped working
hi sencha team!
i am working on a gxt application which should run also on ios devices in fullscreen. this was no problem with the developer preview versions of gxt 3. but with the current gxt 3 beta 2 version, as soon as i inherit any of the gxt 3 stuff, like:
<inherits name='com.sencha.gxt.ui.GXT'/>
the application will run in browser mode on ios, but never ever again in fullscreen mode. you just need a very small test app to see it.
add following meta tag to your html:
<meta name="apple-mobile-web-app-capable" content="yes" />
and just this small app:
public class Test implements EntryPoint {
public void onModuleLoad() {
Window.alert("works");
}
}
never thought that gxt 3 really gets ready, but i have to congratulate you. it is really a great library!
suggestions for the final:
1) please make the default theme completely html5+css3 and only the ie fallback a separated theme/appearance. current browsers are html5+css3 more or less. and best very very easy to customize....
2) please replace all "private" inside the library with "protected". gxt develpers should be equally trusted as your javascript libraries developers. that java offers private should not mean it must be used. especially when it makes inheritance in other packages a pain. please think on it, that we completely have to rewrite from 2.x to 3.x, and often there are breaking changes in minor updates. so please trust us that we fix our own code.
regards, kht
beta 3 still has the same problem.
i am using just 1 class of gxt 3 as long as it does not near final. the XElement, but this already makes the app stop working properly.
as soon as gxt 3.x is included, the app cannot run fullscreen on ios devices. whatever happens here, but this is a showstopper.
are there any news on this topic?
regards kht | http://www.sencha.com/forum/showthread.php?180788-gxt-3.x-ios-fullscreen-gt-stopped-working | CC-MAIN-2014-15 | refinedweb | 336 | 76.93 |
Hi,
I?am trying to send a XML message to my SOAP client using the @WebService- and @WebMethod-annotation (on a Jboss4.0.4GA).
My client needs such a XML-Message like:
<employee id=?50? name=?peter? street=?backerstreet 5? city=?London? >
<employee id=?51? name=?alex? street=?lamestreet 18? city=?Dresden? >
I know that this is not the best XML-style! But my SOAP client asks for such a message and I have to implement it like that.
I have already implemented an EJB3-Entity-Bean for ?employees? with the above attributes.
All the examples about WebService-Endpoints in EJB3 under Jboss were implemented with an ordinary String- or int-returnvalue.
As I for sure need a complex type return value, now my idea was: to give to the client an array of employee-Entity-Beans within the WebService. But this appears to be not the right thing: the resulting WSDL-Document (created automatically by JbossWS) does not contain the private attributes but other stuff, which does not give me the possibility to get the XML-Message like shown above.
Another idea was to return a String[][] with the values of the attributes only. This results in such a XML Message as:
peterLondonalexDresden
I thought also to write for each Return-Value-Entry a class, to wrap the values:
public class myObject { public id; public name; public street; public city;}
and to return to the client an array of this class?s objects.
Resulting XML-Message:
50peterbackerstreet 5London
51alexlamestreet 18Dresden
After all I stuck here, because I don?t know how to write the EJB3-Session-Bean-Method with the use of the @WebMethod annotation, to get the wished XML-SOAP-Message.
Anybody has any ideas how to implement that or where to get ?docu? about EJB3-Session-Beans as WebService Endpoints and complex types? (I already have the O?reillys ?Enterprise JavaBeans 3.0? -> no information about that!)
Thx for your help, Michael | https://developer.jboss.org/thread/107963 | CC-MAIN-2018-17 | refinedweb | 325 | 64.51 |
For the moment, let’s assume that you would like to call into a Clojure library from Java, and that library does not define any types or classes.[304] To use that codebase, you’ll need to tap into the Clojure “native” functions and constant values it defines in namespaces. Thankfully, doing so from Java is straightforward:
Load the Clojure code you want to use. This means reusing the
standard
require,
use, or
load functions provided in Clojure’s
clojure.core namespace.
Obtain references to the vars corresponding with each function or value defined in the namespaces you care about.
Call the functions and use the values however your application requires.
All we need to demonstrate Java→Clojure interop are two vars, one providing a function, the other some value. The value will come from a simple Clojure namespace:
Example 9-20. Simple Clojure namespace
(ns com.clojurebook.histogram) (def keywords (map keyword '(a c a d b c a d c d k d a b b b c d e e e f a a a a)))
The function we’ll use is
frequencies from the
clojure.core namespace; it accepts any seqable
value, and returns a map of the seq’s elements and counts of their
frequency of occurrence in the seq.[305]
Here is a Java class that uses
frequencies with the
keywords value as well as many others.
Example 9-21. Using Clojure code in Example 9-20 from Java
package com.clojurebook; import java.util.ArrayList; import java.util.Map; import clojure.lang.IFn; import clojure.lang.Keyword; import clojure.lang.RT; import ... | https://www.safaribooksonline.com/library/view/clojure-programming/9781449310387/ch09s08.html | CC-MAIN-2016-50 | refinedweb | 269 | 66.23 |
1. Introduction
When you are working on Ado.net sometimes you need to get the table schema information like Column name and data type of that column. In this example article, I will show getting the table schema information. Have a look at the below screenshot:
Here, we are going to display the table schema marked as 2 for the table “discounts” which marked as 1.
2. About the example
The screenshot of the sample is shown below:
The item marked as 1 is a multiline textbox control used to display the table schema shown in section 1 of this article. The “Get Table Schema” button (Marked as 2) once clicked displays the schema information of the discount table in the multi-line textbox. Before using the sample, you should configure the connection string to the Pubs database. Setting the connection string for the “NorthWnd“ database is shown in the below video. The same procedure can be followed to set the connection string for the Pubs database (Name the connection string as PUBSDB) as the table DISCOUNTS resides in it.
Video 1: Forming the connection string
3. Code behind the form
1) First, the required namespace is used in the .cs file. Code is below:
//Sample 01: For accessing the required functionality using System.Data.SqlClient;
2) Next, connection to the Pubs database is established by making use of the connection string “PubsDB” formed in the previous section. The SqlConnection object is created using the connection string which is stored as the application property. Once the connection object is created, the Open method on the object is called to establish the connection to the Pubs database. Below is the code:
//Sample 2.1: Open Connection to SQL SqlConnection Con = new SqlConnection(Properties.Settings.Default.PubsDB); Con.Open();
When you are typing the above code, the intelli-sense displays the Connection string name when it is configured as the application property. The below screenshot shows the that:
3) After the successful connection, a SqlCommand object is created on the DISCOUNTS table of the PUBS database. Then, ExecuteReader method on the Cmd object is called by passing the parameter CommandBehavior.SchemaOnly. This informs the command object that we need only the schema information on the underlying command object in our case it is schema information of Discounts table. The code is given below:
//Sample 2.2: Create Command Object and get schema reader SqlCommand Cmd = new SqlCommand("Select * from Discounts", Con); SqlDataReader Schema_Reader = Cmd.ExecuteReader(CommandBehavior.SchemaOnly);
4) Now we have the Schema_Reader of SqlDataReader which we can to iterate through to get the column information of the DISCOUNTS table. Inside the iteration loop, the schema information is retrieved and displayed in the multiline textbox. The code for this is given below:
//Sample 2.3: Iterate through the Reader and get the Schema information int Total_Column = Schema_Reader.FieldCount; for (int i = 0; i < Total_Column; i++) { string schema_inormation = string.Format("Column Name: {0}, Column Type: {1}", Schema_Reader.GetName(i), Schema_Reader.GetDataTypeName(i)); txtSchemaInfo.AppendText(schema_inormation + Environment.NewLine); } //Sample 2.4 : Close all the objects Schema_Reader.Close(); Con.Close(); | http://www.mstecharticles.com/2015/10/ | CC-MAIN-2018-13 | refinedweb | 515 | 55.64 |
In this problem, we are given a binary tree and we have to print its ancestor of a node in a binary tree.
Binary Tree is a special tree whose every node has at max two child nodes. So, every node is either a leaf node or has one or two child nodes.
Example,
The ancestor of a node in a binary tree is a node that is at the upper level of the given node.
Let’s take an example of ancestor node −
Ancestors of a node with value 3 in this binary tree are 8,
For solving this problem, we will traverse from the root node to the target node. Step by step downwards in the binary tree. And in the path print all the nodes that come.
#include<iostream> #include<stdio.h> #include<stdlib.h> using namespace std; struct node{ int data; struct node* left; struct node* right; }; bool AncestorsNodes(struct node *root, int target){ if (root == NULL) return false; if (root->data == target) return true; if ( AncestorsNodes(root->left, target) || AncestorsNodes(root->right, target) ){ cout << root->data << " "; return true; } return false; } struct node* insertNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node); } int main(){ struct node *root = insertNode(10); root->left = insertNode(6); root->right = insertNode(13); root->left->left = insertNode(3); root->left->right = insertNode(8); root->right->left = insertNode(12); cout<<"Ancestor Nodes are " ; AncestorsNodes(root, 8); getchar(); return 0; }
Ancestor Nodes are 6 10 | https://www.tutorialspoint.com/print-ancestors-of-a-given-node-in-binary-tree-in-cplusplus | CC-MAIN-2022-05 | refinedweb | 255 | 52.12 |
I have been measuring frequency (via FreqMeasure lib) with Uno with no problems. I upgraded to Mega 2560 and cannot get the freq measure to work. I know my input signal (set with “tone” in the code below) is working as I have it hooked to an oscilloscope in real time when trying the FreqMeasure code.
References I have been using:
- My homework: FreqMeasure Library, for Measuring Frequencies in the 0.1 to 1000 Hz range, or RPM Tachometer Applications
- FreqMeas Lib: GitHub - PaulStoffregen/FreqMeasure: Measures the elapsed time during each cycle of an input frequency.
My basic program:
//trying to read oscillating signal through pins 47, 48, or 49 - none work for me.
#include <FreqMeasure.h> void setup() { tone(7, 1000); // set up oscillating signal on Digital I/O 7. Connect this pin to inputs 47 or 48 or 49 Serial.begin(9600); FreqMeasure.begin(); } void loop() { float freq = FreqMeasure.countToFrequency(FreqMeasure.read()); Serial.println(freq); // Always reads 0 delay(1000); }
Given the lack of success, I have been trying to read off of pins 47, 48, and 49. From my homework, I thought 49 was the correct one… but no luck. In addition, I have tried using either CAPTURE_USE_TIMER4 or CAPTURE_USE_TIMER5 in my \libraries\FreqMeasure-1.2.0\util\FreqMeasureCapture.h file, shown here:
// Arduino Mega #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) //#define CAPTURE_USE_TIMER4 // ICP4 is pin 49 #define CAPTURE_USE_TIMER5 // ICP5 is pin 48
I also tried the FreqCount (GitHub - PaulStoffregen/FreqCount: Measures the frequency of a signal by counting the number of pulses during a fixed time.) option, but get an error when calling it from my program via the #include <FreqCount.h> statement.
I am stuck… any suggestions?
Thank you! | https://forum.arduino.cc/t/arduino-mega-2560-frequency-measure-not-working-for-me/535781 | CC-MAIN-2022-21 | refinedweb | 283 | 54.02 |
REST.
Old Syntax
Imagine that a REST service located at returns the following JSON document in its body:
The code below shows how to execute a GET request and validate that it’s ok (status code is 200), assert that the JSON document located in the response body has lotto id equal to 5 and that winner id’s are 23 and 54 in version 1.9.0 and earlier:
While this is quite simple it felt a bit awkward to many users to specify the assertions (expect) before the request has been sent. This is why REST Assured now supports an updated syntax of given-when-then.
New Syntax
With version 2.0 you now do like this instead:
Which to most users feels more natural and familiar.
Extracting values
It’s also very easy to make requests and extract values out of the response with REST Assured. This is an example of how to return the
winning-numbers list from the lotto JSON document:
But what if you want to make some assertions and then return the winning numbers? This is also very easy and looks like this:
That’s it!
Conclusion
If you consider upgrading from an earlier version of REST Assured you can rest assured (!) that the old syntax will still work just as before. It’s just that the given-when-then syntax is as of 2.0 the recommended way of writing your tests. There are some benefits of using the older syntax though. The most prominent one is that REST Assured will present ALL failing assertions at the same time, something that is not possible with the updated syntax. If you’re interested in reading more about the new release refer to the release notes and usage guide.
Hello Johan,
Just wanna ask something. I want to automate the REST services at work. Since I am new to REST assured and even to automation I am keen to know is there any step-by-step explanations to start with it. I couldn’t find any useful info online.
I have tried with eclipse. Created a java project -> a package -> a class. Also included all the JAR files and here is my code. It’s failing and can you please help me? Thank you.
package test.rest.services;
import static com.jayway.restassured.RestAssured.*;
import org.junit.Test;
public class restSearchServices
{
@Test
public void searchServices()
{
expect().
statusCode(200).
when().
get(“..(MY REST URL)./searchservice.svc/search”);
}
}
I have a huge JSON file to be POST as payload of a rest api call for testing purposes. I tried something like :
public void RestTest() throws Exception {
File file = new File(“/Users/bmishra/Code_Center/stash/experiments/src/main/resources/Search.json”);
String content = null;
given().body(file).with().contentType(“application/json”).then().expect().
statusCode(200).
body(equalTo(“true”)).when().post(“”);
}
and get error as :
java.lang.UnsupportedOperationException: Internal error: Can’t encode /Users/bmishra/Code_Center/stash/experiments/src/main/resources/Search.json to JSON.
I can run by reading the file and passing the body as string and that works but I see i can directly pass the file object and this doesnt work.
I want to get the Status code of the site from Google Chrome via Selenium WebDriver using java. How can i accomplish my task..?
Hey,
We are exploring Restassure as a solution for our project, however I couldn’t find any solution for downloading CSV file using RestAssure api.
Can you please help me with information?
-Parveen
Hi,
I am evaluating “rest-assured” to implement in my project for API testing for BDD.
I have a scenario where before invoking any APIs (mostly we have CRUD Rest APIs written), I also need to set up some reference data.
– So, I need to ensure the reference data specific test files runs first
– Also, is it possible to define the sequence in which I would like to run the test cases.
Nice Article,
I have been working with rest assured for last few months. I have created some tutorial please check them out.
Thanks in advance | https://blog.jayway.com/2013/11/29/rest-assured-2-0-testing-your-rest-services-is-easier-than-ever/ | CC-MAIN-2017-17 | refinedweb | 681 | 65.42 |
Reply Me - Struts
Reply Me Hi Friends,
Please write the code using form element...because i got error in textbox null value Hi Soniya
Would you please explain, in which technology are you creating page?
I promise
Tell
struts - Struts
button it has to go to another page.. for that one i taken two form tags..
i...
Reply Me - Java Beginners
for many page requests. Struts provides the ActionForm and the Action classes... use this i don't know...
please tell me what is the use...
Model :
Tell me - Struts
Directory Structure with example program Execution Tell me the Directory Structure with example program Execution
database connection in struts - Struts
; in my project 4 table
1.user register
2.login page
3.forgot password
4.welcome page.
all in struts but i dont no how sql database connected in struts plz give me reply as fast
.
* JSP
* Servlets
* Struts 1
* Struts 2
or JSF?
Please tell me... be stored in datagrid with joining in main page
For page details
In main page which is related to data grid with the joining of two table
In the main Tell me good struts manual
problem:struts code - Struts
problem:struts code Hi,
Am using struts1.2.I wrote a form... forward to same page the form displayed with previous fields.if i press refresh,then its insert into db.how can i clear the fields?
please help please send me a program that clearly shows the use of struts with jsp 1)in struts server side validations u are using programmatically validations and declarative validations? tell me which one is better ?
2) How to enable the validator plug-in file
Admin Page
Admin Page Hi All,
I have to develop Java Web Application using Struts. Can someone please tell me how to code for administration login .i.e when admin login he should have full access whereas others login they should have
struts
struts and hibernate
struts and hibernate i am new in advanced java technology
and i am getting confuse myself
struts tags are used in the front face of the page... end or other.
plz tell me
java - Struts
java code for login page using struts without database ...but using... the form of jsp that we submit...plse help me.....i am in trouble... Hi... page
User Name
Struts + HTML:Button not workin - Struts
Struts + HTML:Button not workin Hi,
I am new to struts. So pls bare with me if my question is fundamental.
I am trying to add 2 Submit buttons in same JSP page.
As a start, i want to display a message when my actionclass
struts
struts how to handle exception handling in struts reatime projects?
can u plz send me one example how to deal with exception?
can u plz send me how to develop our own exception handling
Redirect page
me ,how to redirect page in Tiles With JSTL .
<%@ taglib prefix="tiles"uri="" %>
<%@ taglib prefix="c"uri.../jsp/jstl/sql" prefix="sql" %>
<%@page contentType="text/html" pageEncoding
Error - Struts
. If you can please send me a small Struts application developed using eclips.
My...Error Hi,
I downloaded the roseindia first struts example... create the url for that action then
"Struts Problem Report
Struts has detected
java - Struts
java Hi,
I want full code for login & new registration page in struts 2
please let me know as soon as possible.
thanks,. Hi friend,
I am sending you a link. This link will help you. Please visit for more how to make one jsp page with two actions..ie i need to provide two buttons in one jsp page with two different actions without redirecting to any other page
java - Struts
java This is my login jsp page::
function...:
Submit
struts.../Password is incurrect
Retry click here!
please revert me. Hi
Login - Struts
Struts Login page I want to page in which user must login to see that page. I can do that simple but he/she know that page URL,he/she can simplely... help me out Hi<%@ page language="java" %><
help me
help me HI. Please help me for doing project.
i want to send control from one jsp page to 2 jsp pages... is it possible? if possible how to do name... one have solution for this please help me.
AzAddNewCustomerAction .java
java - Struts
/loginpage.jsp
login page ::
function validate(objForm...!
struts-config.xml...="add";
}
}
please give me correct answer .
Hi friend wanted code for login page without datadase ..using flatfiles like excle,word etc...plse help me.... Hi
login form without... Saved
Next Page to view the session validation
struts validation I want to apply validation on my program.But i am... unable to solve the problem.
please kindly help me..
I describe my program below..
CreateGroup.jsp
<%@ page language="java" pageEncoding="ISO-8859-1"%>
< page error
this request."
please suggest me.
if your login page is prepared with struts supplied tags,then you should enable load on start up on ActionServlet...login page error How to configure in to config.xml .iam takin
java - Struts
java hi i m working on a project in which i have to create a page in which i have to give an feature in which one can create a add project template... give me idea how to start with Hi Friend,
Please clarify what do
Hello - Struts
carefully and let me know I want to create installation file........it is possible... use in swing and awt........please let me know how to create .exe file in java not using jsp & servlets
I want to make icon and click icon open fist page am retrieving data from the mysql database so the form bean will be null for that action.... if i give it in struts config it is asking me to have a form bean.... how to solve this problem
Help me
;jsp:forward
3)Login1.java:
import java.io.IOException
connecting to database - Struts
to MS SQL Server 2005 database.
My first is what do i write in struts-configuration.xml file
that enable me to use methods in the model class to display information via the database in my web page.
Thanks
Tayo Hi
Mozilla Stopped issue - Struts
Mozilla Stopped issue I have developed my project in struts. If I the same application through Mozilla fire fox some times getting blank page and showing "Stopped" in the status bar. Can any one tell me what is the problem
Struts - Struts
Struts hi
can anyone tell me how can i implement session tracking in struts?
please it,s urgent........... session tracking? you mean session management?
we can maintain using class HttpSession.
the code follows
Struts Validation - Struts
Struts Validation Hi friends.....will any one guide me to use the struts validator...
Hi Friend,
Please visit the following links:
http
Struts Tutorials
. how to build a simple Struts HTML page using taglibs
6. how to code...
Struts Tutorials
Struts Tutorials - Jakarta Struts Tutorial
This complete reference of Jakarta Struts shows you how to develop Struts | http://roseindia.net/tutorialhelp/comment/6928 | CC-MAIN-2014-42 | refinedweb | 1,170 | 76.62 |
I've compiled with success the first version
of NanoCPP (STDCXX for Nanodesktop).
So, when I enter this program:
#include <nanodesktop.h>
#include <iostream>
int main()
{
ndInitSystem ();
using namespace std;
ios_base::Init::Init ();
cout << "Hello World!";
return 0;
}
I obtain the "Hello world" on the
screen of the PSP.
But, if I remove the string:
ios_base::Init::Init ();
the system crashes at startup. Is it
a normal behaviour or there's some
option in config.h that I must enable
in order to autoinit any object ?
Thanks
Filippo Battaglia
--
View this message in context:
Sent from the stdcxx-dev mailing list archive at Nabble.com. | http://mail-archives.apache.org/mod_mbox/incubator-stdcxx-dev/200805.mbox/%3C17111782.post@talk.nabble.com%3E | CC-MAIN-2015-48 | refinedweb | 105 | 67.86 |
- 14 Feb, 2012 5 commits
since the url that changes the user session language was moved in webproject as an app wide url, the view that gets bind to the url should exist also in webproject.
- Skip entry points for python distributions names existing in ``SYNNEFO_EXCLUDE_PACKAGES`` environmental variable - Avoid duplicate entries in list setting objects
- 13 Feb, 2012 1 commit
- 07 Feb, 2012 10 commits
Update fabfile, add "dchall" command to produce Debian changelog entries for all Debian packages.
Refs #1986
- 06 Feb, 2012 8 commits
A DB migration is required.
So that glance image service can fallback to the old compute images api for missing image references.
fixed a bug that caused previous/next buttons of vm create view to disappear.
To override default SKIP_AUTH_URLS setting of cyclades-app so that intro and about pages can be served
- 04 Feb, 2012 1 commit
- 03 Feb, 2012 6 commits
Amend INSTALL_REQUIRES in */setup.py with explicit version numbers where not previously specified. Use '>=' comparisons, to avoid console scripts barfing if the exact same version specified in setup.py is not currently installed in the system. dh_python2 does not seem to pass version requirements in the final deb produced, this is an open bug in Debian:
Handle version files for projects that are not using the synnefo namespace
Method name was get_image, not get_meta
- 01 Feb, 2012 2 commits
Add skeleton for admin's quick install guide and developer's quick install guide in snf-docs
- 31 Jan, 2012 3 commits
- 30 Jan, 2012 4 commits
- Correct css selector for error overlay title header - Display vm create errors as critical | https://git.minedu.gov.gr/itminedu/synnefo/-/commits/c82b151c4b23aca3f5b0da1c4520198d528de1a2 | CC-MAIN-2022-27 | refinedweb | 269 | 53.34 |
On Wed, 11 Oct 2006 12:35:42 +0200, Fabio Forno <fabio.forno at gmail.com> wrote: >Hi, I've a problem with an athena widget and IE. > >I define a widget for a LiveFragment like this one: > > >var Widgets = {}; > Using a recent version of Nevow, you shouldn't need to define the Widgets namespace explicitly. Also, "Widgets" is a pretty vague name. I'd suggest picking something less likely to collide. >Widgets.ChatWidget = Nevow.Athena.Widget.subclass('Widgets.ChatWidget'); > >Widgets.ChatWidget.methods( > > function keyPressed (self, event) { > if(event.key()["string"] == "KEY_ENTER") { > text_area = window.document.getElementById("chat_area"); > d = self.callRemote('got_text', text_area.value); > d.addCallback(self.text_sent); > } > } >) It's better to not use getElementById. Instead, make the chat area node a child of the ChatWidget's node and find it either by class or using the new Widget.nodeById method. > >Then in the xml template I try to get a reference to the just defined >method in this way: > >widget = Nevow.Athena.Widget.get( > document.getElementById("athena:1"); > ); > >widget.keyPressed Likewise, "athena:1" is an implementation detail, and you can't rely on your widget getting id "1" all the time. Instead, try using the athena:handler feature: <div nevow: ... <textarea> <athena:handler </textarea> </div> > >In firefox everything is ok, while in explorer 6.0 I get undefined. >MOreover, in i.e. there is this oddity. if a loop on all the >attributes of widgetwith for(var i in widget) , I get also the >keyPressed method, but when I try to get it with widget[i], I keep >having undefined as result. > >Any idea? A difference here wouldn't surprise me. Iteration in JavaScript is extremely inconsistent, even within a single runtime. I don't know of the /specific/ problem which causes the behavior you're describing above, and it may be fixable, but it'd probably be better just to not rely on iteration. Jean-Paul | http://twistedmatrix.com/pipermail/twisted-web/2006-October/003083.html | CC-MAIN-2017-17 | refinedweb | 317 | 59.19 |
Home -> Community -> Usenet -> c.d.o.server -> Re: Oracle shadow process parent id of 1
On Sat, 22 Oct 2005 12:24:00 -0700, dbaplusplus wrote:
>.
NAME
setsid, setpgrp - create session and set process group ID
SYNOPSIS
#include <unistd.h>
pid_t setsid(void);
pid_t setpgrp(void);
DESCRIPTION
If the calling process is not a process group leader, setsid() or setprgp() creates a new session. The calling process becomes the session leader of this new session, becomes the process group leader of a new process group, and has no controlling terminal. The process group ID of the calling process is set equal to the process ID of the calling process. The calling process is the only process in the new process group, and the only process in the new session. setprgp() is provided for backward compatibility only. RETURN VALUE setprgp() returns the value of the process group ID of the calling process. Upon successful completion, setsid() returns the value of the new process group ID of the calling process. Otherwise, a value of -1 is returned, and errno is set to indicate the error. ERRORS No change occurs if any of the following conditions are encountered. In addition, setsid() fails when any of the following conditions occur: [EPERM] The calling process is already a process group leader. [EPERM] The process group ID of a process other than the calling process matches the process ID of the calling process. AUTHOR setprgp() and setsid() were developed by HP and AT&T. SEE ALSO exec(2), exit(2), fork(2), getpid(2), kill(2), setpgid(2), signal(2), termio(7). STANDARDS CONFORMANCE setsid(): AES, XPG3, XPG4, FIPS 151-2, POSIX.1 Hewlett-Packard Company - 1 - HP-UX Release 9.0: August 19
-- on Sat Oct 22 2005 - 16:26:05 CDT
Original text of this message | http://www.orafaq.com/usenet/comp.databases.oracle.server/2005/10/22/1288.htm | CC-MAIN-2016-40 | refinedweb | 302 | 73.58 |
27 December 2010 02:52 [Source: ICIS news]
By Prema Viswanathan
?xml:namespace>
A slew of turnarounds and outages is expected to keep regional supply tight in the first quarter of next year.
However, prospects for the second half of the year were less certain, as there were fears that an oversupply situation may emerge and exert downward pressure on prices, they added.
Prices of raffia grade PP had risen 17% to $1,370-1,400/tonne (€1,041-1,064/tonne) CFR (cost and freight) GCC (Gulf Cooperation Council) this year, while high density PE (HDPE) film prices had climbed back to December 2009 levels at $1,250-1,290/tonne CFR GCC after dipping in July this year, according to ICIS data.
“Several
A spate of outages and production cuts, coupled with firm demand has caused the spread between polyethylene (PE) and feedstock ethylene to widen to $70/tonne, from the negative spread seen in early 2010. The polypropylene (PP)-propylene spread, meanwhile, has increased from zero to $100/tonne.
End-users of PE and PP in the Middle East were reasonably confident they could pass on their high raw material costs to their customers in the early part of 2011, as exports of finished goods into Europe, Africa and the
“However, much will depend on how high PE prices rise and how the debt crisis in Europe pans out, and how soon the economic recovery in the
Demand for PE and PP, especially from the packaging segment, is set to grow by 7-8% in 2011 from the previous year, said another source at a Saudi producer.
“The Saudi Arabian economy, in particular, has been performing well this year, and we expect the trend to continue into 2011,” the source said.
Governments in the GCC (Gulf Cooperation Council) region have been offering special incentives to encourage the growth of the downstream sector in a bid to generate more employment.
Demand has also been growing at a robust 7-8% in the Iranian polymer market, but the sanctions imposed by the UN, US and EU have almost halted imports of grades such as copolymer PP and black pipe grade HDPE, which Iran does not produce.
But if prices rose too high in the
“This year,
Other producers were not too concerned about the persistently high PE and PP prices.
“Producers have no option but to raise prices when feedstock values are on the rise,” said a source close to a Qatari producer.
If crude, ethylene and propylene values remain high in 2011, that could help support PE and PP prices next year, said a Dubai-based trader.
Prices of crude were at $88-89/bbl this week, up 25% from the same time last year. Ethylene prices were largely unchanged from last year at $1,170-1,200/tonne CFR northeast
( | http://www.icis.com/Articles/2010/12/27/9421528/outlook-11-middle-east-pe-pp-players-to-see-strong-h1-margins.html | CC-MAIN-2014-35 | refinedweb | 473 | 58.25 |
Name | Synopsis | Description | Return Values | Errors | Environment Variables | Attributes | See Also | Warnings | Notes
cc [ flag ... ] file ... -lnsl [ library ... ] #include <rpcsvc/nis.h> nis_result *nis_list(nis_name name, uint_tflags, int (*callback)(nis_name table_name,nis_object *object, void *userdata), void *userdata);
nis_result *nis_add_entry(nis_name table_name, nis_object *object, uint_t flags);
nis_result *nis_remove_entry(nis_name name, nis_object *object, uint_t flags);
nis_result *nis_modify_entry(nis_name name, nis_object *object, uint_t flags);
nis_result *nis_first_entry(nis_name table_name);
nis_result *nis_next_entry(nis_name table_name, netobj *cookie);
void nis_freeresult(nis_result *result);
Use the NIS+ table functions to search and modify NIS+ tables. nis_list() is used to search a table in the NIS+ namespace. nis_first_entry() and nis_next_entry() are used to enumerate a table one entry at a time. nis_add_entry(), nis_remove_entry(), and nis_modify_entry() are used to change the information stored in a table. nis_freeresult() is used to free the memory associated with the nis_result:
[ colname=value, . . . ], tablename
The list function, nis_list(), takes an indexed name as the value for the name parameter. Here, the tablename should be a fully qualified NIS+ name unless the EXPAND_NAME flag (described below) is set. The second parameter, flags, defines how the function will respond to various conditions. The value for this parameter is created by logically ORing together one or more flags from the following list.
If the table specified in name resolves to be a LINK type object (see nis_objects(3NSL)), this flag specifies that the client library follow that link and do the search at that object. If this flag is not set and the name resolves to a link, the error NIS_NOTSEARCHABLE will be returned.
This flag specifies that if the entry is not found within this table, the list operation should follow the path specified in the table object. When used in conjunction with the ALL_RESULTS flag below, it specifies that the path should be followed regardless of the result of the search. When used in conjunction with the FOLLOW_LINKS flag above, named tables in the path that resolve to links will be followed.
This flag specifies that the operation should continue trying to contact a server of the named table until a definitive result is returned (such as NIS_NOTFOUND).
This flag can only be used in conjunction with FOLLOW_PATH and a callback function..
This flag specifies that the client library should bypass any client object caches and get its information directly from either the master server or a replica server for the named table.
This flag is even stronger than NO_CACHE in that it specifies that the client library should only get its information from the master server for a particular table. This guarantees that the information will be up to date. However, there may be severe performance penalties associated with contacting the master server directly on large networks. When used in conjunction with the HARD_LOOKUP flag, this will block the list operation until the master server is up and available.
When specified, the client library will attempt to expand a partially qualified name by calling nis_getnames(), which uses the environment variable NIS_PATH. See nis_local_names(3NSL).
This flag is used to specify that a copy of the returning object be returned in the nis_result structure if the operation was successful.
The third parameter to nis_list(), callback, is an optional pointer to a function that will process the ENTRY type objects that are returned from the search. If this pointer is NULL, then all entries that match the search criteria are returned in the nis_result structure, otherwise this function will be called once for each entry returned. When called, this function should return 0 when additional objects are desired and 1 when it no longer wishes to see any more objects. The fourth parameter, userdata, is simply passed to callback function along with the returned entry object. The client can use this pointer to pass state information or other relevant data that the callback function might need to process the entries.
The nis_list() function is not MT-Safe with callbacks.
nis_add_entry() will add the NIS+ object to the NIS+ table_name. The flags parameter is used to specify the failure semantics for the add operation. The default (flags equal 0) is to fail if the entry being added already exists in the table. The ADD_OVERWRITE flag may be used to specify that existing object is to be overwritten if it exists, (a modify operation) or added if it does not exist. With the ADD_OVERWRITE flag, this function will fail with the error NIS_PERMISSION if the existing object does not allow modify privileges to the client.
If the flag RETURN_RESULT has been specified, the server will return a copy of the resulting object if the operation was successful.
nis_remove_entry() removes the identified entry from the table or a set of entries identified by table_name._NOT_NOTUNIQUE error is returned and the operation is aborted. If the flag parameter REM_MULTIPLE is passed, and if remove permission is allowed for each of these objects, then all objects that match the search criteria will be removed. Note that a null search criteria and the REM_MULTIPLE flag will remove all entries in a table.
nis_modify_entry() modifies an object identified by name. The parameter object should point to an entry with the EN_MODIFIED flag set in each column that contains new information.
The owner, group, and access rights of an entry are modified by placing the modified information into the respective fields of the parameter, object: zo_owner, zo_group, and zo_access.
These columns will replace their counterparts in the entry that is stored in the table. The entry passed must have the same number of columns, same type, and valid data in the modified columns for this operation to succeed.
If the flags parameter contains the flag MOD_SAMEOBJ then the object pointed to by object is assumed to be a cached copy of the original object. If the OID of the object passed is different than the OID of the object the server fetches, then the operation fails with the NIS_NOTSAMEOBJ error. This can be used to implement a simple read-modify-write protocol which will fail if the object is modified before the client can write the object back.
If the flag RETURN_RESULT has been specified, the server will return a copy of the resulting object if the operation was successful.
nis_first_entry()_result structure must be copied by the caller into local storage and passed as an argument to nis_next_entry().
nis_next_entry() retrieves the “next” entry from a table specified by table_name. The order in which entries are returned is not guaranteed. Further, should an update occur in the table between client calls to nis_next_entry() there is no guarantee that an entry that is added or modified will be seen by the client. Should an entry be removed from the table that would have been the “next” entry returned, the error NIS_CHAINBROKEN is returned instead.
The path used when the flag FOLLOW_PATH is specified, is the one present in the first table searched. The path values in tables that are subsequently searched are ignored.
It is legal to call functions that would access the nameservice from within a list callback. However, calling a function that would itself use a callback, or calling nis_list() with a callback from within a list callback function is not currently supported.
There are currently no known methods for nis_first_entry() and nis_next_entry() to get their answers from only the master server.
The nis_list() function is not MT-Safe with callbacks. nis_list() callbacks are serialized. A call to nis_list() with a callback from within nis_list() will deadlock. nis_list() with a callback cannot be called from an rpc server. See rpc_svc_calls(3NSL). Otherwise, this function is MT-Safe. a call to nis_freeresult(). See nis_names(3NSL). If you need to keep a copy of one or more objects, they can be copied with the function nis_clone_object() and freed with the function nis_destroy_object(). See nis_server(3NSL).
The various ticks contain details of where the time, in microseconds, name of an attribute did not match up with a named column in the table, or the attribute did not have an associated value.
The name passed to the function is not a legal NIS+ name.
A problem was detected in the request structure passed to the client library.
The entry returned came from an object cache that has expired. This means that the time to live value has gone to zero and the entry may have changed. If the flag NO_CACHE was passed to the lookup function then the lookup function will retry the operation to get an unexpired copy of the object.
An RPC error occurred on the server while it was calling back to the client. The transaction was aborted at that time and any unsent data was discarded.
Even though the request was successful, all of the entries have been sent to your callback function and are thus not included in this result..
The object pointed to by object is not a valid NIS+ entry object for the given table. This could occur if it had a mismatched number of columns, or a different data type than the associated column in the table, for example, binary or text.
The name passed resolved to a LINK type object and the contents of the object pointed to an invalid name.
The attempted modification failed for some reason.
An attempt was made to add a name that already exists. To add the name, first remove the existing name and then add the new name or modify the existing named object.
This soft error indicates that a server for the desired directory of the named table object could not be reached. This can occur when there is a network partition or the server has crashed. Attempting the operation again may succeed. See the HARD_LOOKUP flag.
The server was unable to contact the callback service on your machine. This results in no data being returned.
Generally a fatal result. It means that the service ran out of heap space.
This hard error indicates that the named directory of the table object does not exist. This occurs when the server that should be the parent of the server that serves the table, does not know about the directory in which the table resides.
The named table does not exist.
A request was made to a server that does not serve the given name. Normally this will not occur, however if you are not using the built in location mechanism for servers, you may see this if your mechanism is broken.
No entries in the table matched the search criteria. If the search criteria was null (return all entries) then this result means that the table is empty and may safely be removed by calling the nis_remove().
If the FOLLOW_PATH flag was set, this error indicates that none of the tables in the path contain entries that match the search criteria.
A change request was made to a server that serves the name, but it is not the master server. This can occur when a directory object changes and it specifies a new master server. Clients that have cached copies of the directory object in the /var/nis/NIS_SHARED_DIRCACHE file will need to have their cache managers restarted to flush this cache. Use nis_cachemgr -i.
An attempt to remove an object from the namespace was aborted because the object that would have been removed was not the same object that was passed in the request.
The table name resolved to a NIS+ object that was not searchable.
This result is similar to NIS_NOTFOUND except that it means the request succeeded but resolved to zero entries. When this occurs, the server returns a copy of the table object instead of an entry so that the client may then process the path or implement some other local policy.
This fatal error indicates the RPC subsystem failed in some way. Generally there will be a syslog(3C) message indicating why the RPC request failed.
The named entry does not exist in the table, however not all tables in the path could be searched, so the entry may exist in one of those tables.
Even though the request was successful, a table in the search path was not able to be searched, so the result may not be the same as the one you would have received if that table had been accessible.
The request was successful.
Some form of generic system error occurred while attempting the request. Check the syslog(3C) record for error messages from the server.
The search criteria passed to the server had more attributes than the table had searchable columns.
The server connected to was too busy to handle your request. add_entry(), remove_entry(), and modify_entry() return this error when the master server is currently updating its internal state. It can be returned to nis_list() when the function specifies a callback and the server does not have the resources to handle callbacks.
An attempt was made to add or modify an entry in a table, and the entry passed was of a different type than the table.
When set, this variable is the search path used by nis_list() if the flag EXPAND_NAME is set.
See attributes(5) for descriptions of the following attributes:
niscat(1), niserror(1), nismatch(1), nis_cachemgr(1M), nis_clone_object(3NSL), n, nis_destroy_object(3NSL), nis_error(3NSL), nis_getnames(3NSL), nis_local_names(3NSL), nis_names(3NSL), nis_objects(3NSL), nis_server(3NSL), rpc_svc_calls(3NSL), syslog(3C), attributes(5)
Use the flag HARD_LOOKUP carefully since it can cause the application to block indefinitely during a network partition.
NIS+ might not be supported in future releases of the Solaris operating system. Tools to aid the migration from NIS+ to LDAP are available in the current Solaris release. For more information, visit.
Name | Synopsis | Description | Return Values | Errors | Environment Variables | Attributes | See Also | Warnings | Notes | http://docs.oracle.com/cd/E19253-01/816-5170/6mbb5eskr/index.html | CC-MAIN-2017-13 | refinedweb | 2,285 | 61.46 |
Talk:Volapük
From RationalWiki
Missionality[edit]
New Age bearing, perhaps. Not sure about missionality. Blue Talk 05:51, 17 February 2011 (UTC)
- Are we really going to turn "missionality" into a serious criterion? Shall we just delete the whole "Fun:" namespace now? --Eira OMTG! The Goat be Praised. 01:34, 18 February 2011 (UTC)
- Esperanto has had a page since Dec '07, and is basically the same principle. Aboriginal Noise What the ... 02:05, 18 February 2011 (UTC)
- Sed Esperanto estas multe bona, kaj la nova mundlingvo. Volapük estas sole la stupida ideo de stupida pastro. Tiel, esperanto estas OK para la wikio, kaj Volapük estas elen. --Eira OMTG! The Goat be Praised. 09:14, 18 February 2011 (UTC)
I don't really understand why this article was kept. Is there any point? Volapük may have been promoted as an international language ~100 years ago, but nowadays it seems people speak it just for fun.--Кřěĵ (ṫåɬк) 10:35, 23 March 2014 (UTC)
- Esperanto. Lojban. E-Prime. Volapük. Existing languages are probably on-mission. Languages created for a purpose are certainly on-mission. FuzzyCatPotato!™ (talk/stalk) 15:45, 1 December 2014 (UTC)
Which 'two English words' - and did anyone consider the reforms Double Dutch? Anna Livia (talk) 14:39, 29 January 2018 (UTC) | https://rationalwiki.org/wiki/Talk:Volap%C3%BCk | CC-MAIN-2020-05 | refinedweb | 213 | 60.92 |
Congratulations, newbie. You’ve made the first step towards the side of righteousnous. Vim will guide you towards a place beyond your wildest dreams. Oh, the road shall not be easy. It may test your faith at times, but the rewards will be magnificent.
The cool thing about vim is that it was designed ground up to require the fewest keystrokes possible. Its philsophy is speed when typing and editing, and any time you’re required to move your fingers away from the base row, you’re wasting time.
Unlike most other editors, vim has what are called modes. In particular, vim has 3 modes: visual mode, normal mode, and insert mode.
Normal mode is the default mode - it’s meant for fast navigation and large changes in many lines of text.
Insert mode is meant for? You guessed it, inserting text. This is what we think of when we consider most text editors.
Visual mode is what you do when you select text. Imagine you wanted to select a glob of text and replace it with a word. That’s a job for visual mode.
It seems needlessly complicated at first, but this is at the core of vim’s advantage.
There are several ways to open vim.
vim by itself opens up a new buffer with nothing loaded.
vim [filename] opens up a buffer with that file loaded. If that file doesn’t exist, then it creates a new buffer named
[filename].
Let’s go over normal mode basics:
Great, now we can do basic things in normal mode like navigate. How do we quit vim? To quit vim, you must be in normal mode. In normal mode, use
:q. If your file has unsaved changes, it won’t let you quit (vim doesn’t want you to lose changes by accident - how nice!). If you really want to quit without saving changes, use
:q! in normal mode.
But how do we save?
:w.
w for write. If we want to write and then immediately leave vim, we can chain together
:w and
:q with
:wq.
How do we switch between modes?
The best part about vim is the many ways in which we can enter insert mode.
And there are many more!
Once in insert mode, you simply type like a normal text editor and it simply adds the text.
C-W deletes the previous word, just like on the terminal, when you’re already in insert mode.
No matter what mode you’re in, pressing
Esc will take you back to Normal mode. However,
Esc is rather cumbersome, and that violates Vim’s entire philosophy. Thus,
C-[ (control-left bracket) is often much easier to do, and equivalent. For convenience, I would recommend remapping Caps Lock and Control.
There are 2 kinds of visual modes. To enter regular visual mode, just press
v from normal mode, and begin moving around just as you would with regular normal mode commands. It will begin to select text as normal. Then, when you enter insert mode, your inserts will only apply to that particular block.
For example, if I have
def stuff(): print "Omg. So many lines of code." print "Dude, seriously though." return 5
and I highlight the entire block with visual mode, when I press
S, it will delete the entire block and place the cursor at the beginning of that block, and I will be in insert mode.
Another way to enter visual mode is using
C-V. This is used for column-wise highlighting. The classic situation is commenting out or commenting in a block of code.
def doge(): print "Such code." print "Much python." print "Wow."
Let’s say I wanted to comment out the entire
doge function. Obviously, I wouldn’t shift to insert mode in front of each line, insert
#, and then go back to normal mode, and do the same thing for the other lines. That sounds miserable.
Instead, I’ll press
0 on the first line, taking me to the 1st character. Then, I’ll press
C-V (that’s Control, and while holding it, Shift-V). Now I’m in column-wise visual mode. Then I press
G which takes me to the end of the file, highlighting everything in the first column along the way. Now, pressing
I allows me to insert at the beginning of the line. I add a
# and shift back to normal mode. So much easier!
This stuff takes a lot of time to learn, so if you’re feeling overwhelmed, don’t worry you’re not alone. Vim is no pushover. Keep using it, and anytime you find yourself doing a repetitive keystroke, search for how that could be faster.
Over time, you’ll find yourself memorizing many shortcuts and learning new ones along the way (I still learn new ones every day). Did you know that pressing
C-A in normal mode over a number automatically increments it? Just learned that one yesterday. Apparently it even works on dates! Vim is incredible, and you really never stop learning.
This goes back to that “Hacker Spirit” we spoke of last time. Never stop learning, never stop being curious.
Anyways, vim has many more complicated ways to manipulate text. You can often times string commands together. For example,
caw deletes the word you’re currently on (in normal mode), and automatically shifts you to insert mode. This is an easy way to change a word to something else.
daw on the other hand, simply deletes it while keeping you in normal mode.
If you don’t know regular expressions, you really should consider learning them. The reason languages like Perl are considered the most powerful for text-editing is because of regular expressions, and tools like grep utilize them as well.
Vim is no exception.
Imagine you find yourself in a situation where you need to change every if statement in some section of code from
if (a == 5) to
if (b == 5). Would you want to do that by hand? What if you miss one single if statement. Ouch.
This is where regular expressions come in. In normal mode, this is a single line in vim.
:%s/if (a ==/if (b ==/g. Can you believe such a small line can do something so powerful? Of course, there are much cooler things vim can do - this is simply to give you a taste.
What if you want to edit multiple files in Vim? Should we open multiple terminals and have each one have a single vim file? Of course not.
Vim has many solutions for this. Most novice users will use tabs.
:tabnew in normal mode will create a new tab in vim. Close tabs like you would close vim, with
:q or
:wq.
:gt can be used to cycle through tabs.
Once you create a new tab, it will be empty at first. What if you wanted to load a file onto that tab? Use
:e [filename] to open a particular file. You’ll have to put its relative path from the directory in which you initially opened vim.
That’s decent, but what if you wanted to have multiple files on the same screen? For example, I wanted to have the file
a.c in the top half of my screen and
b.c in the bottom half? Of course, we can do that as well. I open the first file by
vim a.c. Then, in normal mode, I can do
:split or
:sp for short.
:sp Creates a horizontal split where, if I supply no parameters, it uses the current buffer. So there will be 2
a.c’s. Since I wanted
b.c, I instead type
:sp b.c, and voila! My screen is split.
But I have an extra long monitor, you say. I want to split vertically, not horizontally! Not to worry, that is what vertical splits are for!
:vsplit, or
:vsp for short will do just what you desire.
You can navigate between windows in normal mode. If you want to move to the window above you, instead of
k you would do
C-w-k. Similarly, to go to the window below you, instead of
j, use
C-w-k. Easy enough!
But what if I want to view multiple files without using tabs or windows? What if I just wanted one buffer open, but at times I wanted to rapidly switch between files inside that one buffer?
Absolutely. Do note that there are plugins that make this significantly easier (like Unite and Control-P), but of course Vim has a native solution.
How do we even get many files in one buffer? Imagine you did
vim file1.txt file2.txt file3.txt. All three of the files wouldn’t be opened in tabs. Instead, there would be a single buffer with
file1.txt showing.
:buffers lists all buffers currently open - it would show
file2.txt and
file3.txt as well.
:ls and
:files also do the same. (Normal mode, remember!)
Switch to any buffer by doing
:buffer <name> where
<name> is the name of the buffer.
There are many many plugins out there. Vim has been around for longer than most of us have been alive. There are plugins to make installing other plugins easier.
Some are clearly better than others. There are autocomplete plugins (so vim can do things like eclipse and fill in words). There are many syntax highlighting options.
If you ever feel unsatisfied with vim, edit your
~/.vimrc file. There are tons of sample vimrc files out in the interwebs, and many people have extremely useful tips. Feel free to steal them and make it your own! I’ve posted my own vimrc (minus plugins) on Piazza.
Several of the top plugins include:
ntautomatically opens/closes NerdTree
See Recitation 1. At the bottom, there’s a section entitled “The Hacking Spirit”. I’ve decided after much deliberation that although I could go into exactly how I installed this stuff (on a Mac), it would spoil your educational opportunity!
Much of learning is done through Googling, Stack Overflow-ing, and mucking around the terminal to see what works. So go, explore! And if you have any truly dastardly bugs, well then you know where to find me (Sudi 005)
:)
Seriously, these are must reads. You will learn much.
Buffers, windows, and tabs
Using Vim’s tabs like buffers
5 Plugins Some Dude Thought were Cool
Vim Bible Part 1
Vim Bible Part 2
The number 1 rated Vim Plugin in the World
A replacement for PowerLine and every other plugin
Vim Wiki Website
I’ll add one last thing - whatever you’re looking for, guaranteed there’s a plugin out there somewhere. Just look for it first. Vim can do most everything an IDE can do, but sometimes there is such a thing as too much. At one point I was having vim do literally everything Eclipse did - debugger and all - and vim was just as slow. There’s a reason to use vim - it’s fast. Don’t lose sight of that amidst the sparkle of new plugins. | https://cs50.notablog.xyz/tips/Tips1.5.html | CC-MAIN-2018-43 | refinedweb | 1,858 | 85.18 |
view raw
I'm working with web2py and I've been looking through the source code to get
some better understanding. Multiple times I've seen assignments like
# in file appadmin.py
is_gae = request.env.web2py_runtime_gae or False
# in file appadmin.py
if False and request.tickets_db:
from gluon.restricted import TicketStorage
Not quite like what you are assuming. Python evaluates conditions lazily, so if the value is known to satisfy the condition then the evaluation quits. See this example:
>>> None or False False >>> True or False True >>> 0 or False False >>> 'Value' or False 'Value'
The second one, as per lazy evaluation, will simply return
False on that statement and the rest of the statements will not be evaluated. This can be a way to unconditionally disable that if statement. | https://codedump.io/share/JssOYpWsi0k/1/in-python-what39s-the-point-of-39x-or-false39-and-39false-and-x | CC-MAIN-2017-22 | refinedweb | 131 | 59.09 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.