text
stringlengths 454
608k
| url
stringlengths 17
896
| dump
stringlengths 9
15
⌀ | source
stringclasses 1
value | word_count
int64 101
114k
| flesch_reading_ease
float64 50
104
|
---|---|---|---|---|---|
2016 -
1. FlexReport for WPF supports all features as in FlexReport for Winforms except that Chart and Custom Fields (SuperLabel, Map) are not supported in this version. For more information on FlexReport for Winforms, please visit here.
For the first release, we are releasing the FlexViewerPane (Beta) control which renders FlexReport, C1Report and SSRS Documents in it's pane. Full-fledged FlexViewer control would be available in release targeted next year. However, the FlexViewerPane control supports most of basic viewer operations like
Page Navigation
Refresh
You can design FlexReport (.flxr) in (Winforms based) FlexReport Designer App that ships with Studio for WPF.
4. FlexReport for WPF can work in MVVM pattern of WPF Application. The Report Viewer control - FlexViewerPane, supports XAML binding of it's DocumentSource object with FlexReport.
1. Create new WPF Application in VS2015.
2. Drop C1FlexViewerPane on the Designer. 3. Set Display Settings for the viewer - like HorizontalAlignment, VerticalAlignment to Stretch and set the Dimensions of the Viewer. Also, set name of FlexViewer to access it from code behind.
4. Add reference to C1.WPF.FlexReport.
5. Add C1FlexReport file you want to load to the project.
6. Add Windows_Loaded event in XAML. 7. Go to code behind. 8. Include namespace for FlexReport.
9. Create object for FlexReport (native WPF). 10. Load FlexReport file in the report object. 11. Bind FlexViewerPane with FlexReport object.
C1FlexReport rpt = new C1FlexReport(); rpt.Load(@"..\\..\\TelephoneBillReport.flxr", "TelephoneBill"); flv.DocumentSource = rpt;
11. Run the project. Here is how your report looks like -
What do you think about FlexReport for WPF? Drop your comments below. Thanks! | https://www.grapecity.com/blogs/releasing-native-wpf-reporting-tool-getting-started | CC-MAIN-2022-27 | refinedweb | 263 | 61.53 |
Today you are going to learn how to bookland barcode in C#. ByteScout Barcode SDK was made to help with bookland barcode in C#. ByteScout Barcode SDK.
This rich sample source code in C# for ByteScout Barcode SDK includes the number of functions and options you should do calling the API to implement bookland barcode. To do bookland barcode in your C# project or application you may simply copy & paste the code and then run your app! Enhanced documentation and tutorials are available along with installed ByteScout Barcode SDK if you’d like to dive deeper into the topic and the details of the API.
Visit our website provides for free trial version of ByteScout Barcode SDK. Free trial includes lots of source code samples to help you with your C# project.
On-demand (REST Web API) version:
Web API (on-demand version)
On-premise offline SDK for Windows:
60 Day Free Trial (on-premise)
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using Bytescout.BarCode; namespace Sample { class Program { static void Main(string[] args) { // Create new barcode Barcode barcode = new Barcode(); // Set symbology barcode.Symbology = SymbologyType.Bookland; // Set value barcode.Value = "123456789"; // Save barcode to image barcode.SaveImage("result.png"); // Show image in default image viewer Process.Start("result.png"); } } }) | https://bytescout.com/articles/barcode-generator-sdk-c-bookland-barcode | CC-MAIN-2022-27 | refinedweb | 215 | 59.09 |
Method overloading is one of the most useful concepts in Object Oriented Programming languages that allow us to avoid the ambiguity of methods by providing uniqueness among them when declaring them. It's common in normal programming to do this but to use this feature in a web service we need to use a certain procedure. So in this article we will learn about Method Overloading in web services from the basics because I have written this article focusing on students and beginners. Before proceeding further please refer to my previous articles for a better understanding of web services.
I hope you have read those articles. Now let us start from a definition.
Method Overloading
Method Overloading is the creation of multiple methods in a class with the same name but different parameters and the types are called method overloading. Method overloading is an example of compile time polymorphism that is done at compile time.
Method overloading can be done in a web service with the following things:
- By changing the number of parameters used.
- By changing the order of parameters.
- By using different data types for the parameters
- The message name property of the Web method attribute must be defined.
- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New WebSite" - "C#" - "ASP.NET Empty Web Application" (to avoid adding a master page).
- Provide the web site a name such as "MethodOverloadingInWebService" or another as you wish and specify the location.
- Then right-click on Solution Explorer - "Add New Item" then you will see the web service templates.
Now after adding the web service template then the Solution Explorer will look such as follows.
/>
As we have seen in the preceding Solution Explorer, there is the CustomerService.cs web service class with the CustomerService.asmx file. Now create the two functions having the same name but different parameters as follows:
public class CustomerService : System.Web.Services.WebService { [WebMethod] public int GetAddtionOfNumber(int a,int b) { return a + b; } [WebMethod] public int GetAddtionOfNumber(int a, int b,int c) { return a + b + c; } }
To enable method overloading in a web service use the following procedure.
Step 1: Define MessageName property
As I have already said, to enable the method overloading in a web service then we need to use the MessageName property of the Webmethod attribute to make the same named methods unique. If we run the preceding program without the MessageName property then the following error will occur.
/>
So to solve the preceding problem we need to define the MessageName property for the preceding two methods of the CustomerService class. After defining the message name property, the class will look such as follows:; } }
In the preceding example, I overloaded the GetAddtionOfNumber method and at the client site, to differentiate the two methods, I defined the messageName property to make the two methods unique that has the same name.
Step 2: Set WsiProfiles (Web Service Identity) to None
[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]
If we run the preceding program without setting WsiProfiles to None then the following error will occur:
To solve the preceding problem we need to set the WsiProfiles.None as in the following:
/>
Now run the Web Service application. Two methods of the web service class will be run without an error and will look such as follows:
/>
In the preceding image you saw that the method names are the same but each method provides different output. Now the entire code of the web service class will look such as follows:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; /// <summary> /// Summary description for CustmomerService /// </summary> [WebService(Namespace = "")] [WebServiceBinding(ConformsTo = WsiProfiles.None)]; } }
Now let us create the UI with the a simple web application so we can understand how the method overloading works:
After adding the Default.aspx page into the existing web service the Solution Explorer then will look as follows:
- Right-click on the existing Solution Explorer.
- Then choose Add New Item.
- Select the .aspx Page from the template list, define the name and click on OK.
/>
Now add a button, three TextBoxes, one label and one button to the Default.aspx page body section, then it <h4 style="color:White">Article by Vithal Wadje</h4> <form id="form1" runat="server"> <table style="margin-top:60px;color:White"> <tr> <td>First Number</td> <td> <asp:TextBox</asp:TextBox></td> </tr> <tr> <td>Second Number</td> <td> <asp:TextBox</asp:TextBox></td> </tr> <tr> <td>Third Number</td> <td> <asp:TextBox</asp:TextBox></td> </tr> <tr> <td></td><td></td> </tr> <tr> <td></td><td> <asp:Button </td> </tr> <tr> <td> Addition of Two Num. </td> <td id="tdoutputtwo" runat="server"> </td> </tr> <tr> <td> Addition of Three Num. </td> <td id="tdthreeout" runat="server"> </td> </tr> </table> </form> </body> </html>
Now to learn how to consume the web service in a web application, please refer to the following article of mine because in this article I am not going to explain it again:
Now, I hope you have read that article. Let us create the object of the web service class CustomerService.cs in the Default.aspx page to access the methods defined in the web service. After creating the object the default.aspx class file code will look as follows:
using System; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btngetAddition_Click(object sender, EventArgs e) { int a, b, c;//to store the TextBox Values a =Convert.ToInt32( TextBox1.Text); b = Convert.ToInt32(TextBox2.Text); c=Convert.ToInt32(TextBox3.Text); // creating the object of web service class CustomerService obj = new CustomerService(); //assigning web service method return output to the server side HTML td tags tdoutputtwo.InnerText = Convert.ToString(Convert.ToInt32(obj.GetAddtionOfNumber(a,b))); tdthreeout.InnerText = Convert.ToString(Convert.ToInt32(obj.GetAddtionOfNumber(a, b,c))); } }
Now run the application, the initial UI will look as follows:
/>
Now enter the input values into the preceding three textboxes and click on the Get Addition button, the output will be as follows:
/>
In the preceding output, the 40 output is returned by the first method that takes two parameters and 60 is the output returned by the second that takes three parameters, hence from the preceding example it's clear that we can overload the methods in web services.
Notes
Download Sample
MethodOverLoadingInWebService.zip
Summary
I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.
- Download the Zip file from the attachment for the full source code of the application.
MethodOverLoadingInWebService.zip
I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also. | http://www.compilemode.com/2015/05/method-overloading-in-web-services.html | CC-MAIN-2017-13 | refinedweb | 1,120 | 52.7 |
RE: [soapbuilders] Re: Where's decimal?
Expand Messages
- Sam
From you email
How about folks implement what agreed at in Las Vegas:
"2) Expanding the "echo" tests to include the full range of primitive
data
types defined in XML schema part 2 section 3.2"
-jhawk
-----Original Message-----
From: Sam Ruby [mailto:rubys@...]
Sent: Monday, July 02, 2001 12:16 PM
To: [email protected]
Subject: Re: [soapbuilders] Re: Where's decimal?
> I'd like to see boolean... it has interesting lexical aspects.Sounds good to me. I'd actually like to see as many as possible...
duration, byte, short, etc.
- Sam Ruby
-----------------------------------------------------------------
This group is a forum for builders of SOAP implementations to discuss
implementation and interoperability issues. Please stay on-topic.
To unsubscribe from this group, send an email to:
[email protected]
Your use of Yahoo! Groups is subject to
- Alex,
Thanks for the tip, the web.config entry worked great.
I'm now trying to get a .Net (beta 2) client calling a very simple
helloworld Apache SOAP (v2.2) service with one string in and a string
return. After jumping through many hoops already, I am close but
still get this error:
<faultcode>SOAP-ENV:Client</faultcode> <faultstring>No Deserializer
found to deserialize a ':meth1_inType1' using encoding
style ''.</faultstring>
<faultactor>/soap/servlet/rpcrouter</faultactor>
The type attribute for meth1_inType1 is defined as xsd:string. The
equivalent java client works fine and comparing the .net vs. java raw
soap requests, there are only 2 differences. 1) 1999 vs. 2001 XML
Schema namespaces and 2) the encodingStyle attribute is on the 'Body'
tag vs. on the 'helloworld' (method) tag. I read in Apache's doc's
that 2001 schema would be deserialized correctly, but haven't tested
this myself. Also, haven't found a way to tell .Net to put the
encodingStyle attribute on a different tag to test if that
specifically causes the fault.
Any suggestions as to how I can get this simple interoperability test
working?
Best Regards,
Paul
--- In soapbuilders@y..., "Alex DeJarnatt" <alexdej@m...> wrote:
> Paul, I can address the 3 issues you encountered. However, only one
of
> them can be fixed on the .NET side...
>
> 1. the binding attribute of port and the type attribute of binding
are
> QNames. The generated WSDL is correct. That said, this seems to be a
> common mistake -- a good number of the WSDLs on xmethods don't use
> QNames. Perhaps there's a newer import tool you could use that
supports
> this?
>
> 2. ASP.NET web services beta 2 support WSDL 1.1, which requires use
of
> the 2001 XML Schema. Again, perhaps there's a newer import tool you
> could get...
>
> 3. the WSDL for get and post should be spec-compliant according to
the
> rules of WSDL section 4, but it's reasonable to not want to include
this
> in your generated WSDL if you're not interested in using get or
> You can turn off support for GET and POST on a per-appdir basis by
> putting the following in a file called web.config in the same
directory
> as your .asmx
> <configuration>
> <system.web>
> <webServices>
> <protocols>
> <remove name="HttpGet"/>
> <remove name="HttpPost"/>
> </protocols>
> </webServices>
> </system.web>
> </configuration>
>
> alex
>
> -----Original Message-----
> From: Paul Welch [mailto:paulwelch28@y...]
> Sent: Wednesday, July 11, 2001 2:21 PM
> To: soapbuilders@y...
> Subject: [soapbuilders] Re: .NET encoding stuff
>
> I've been trying to work through the .Net to IBM WSTK WSDL
> compatibility. I've made it all the way from .Net Web Service to a
> working auto-generated java client proxy, but only with several
> manual edits of the WSDL. I have a .Net service with the following
> attributes specified:
>
> at the class level:
>
> [WebService(Namespace="")]
> [SoapRpcServiceAttribute(RoutingStyle =
> SoapServiceRoutingStyle.SoapAction)]
>
> and, at the method level:
>
> [WebMethod]
> [SoapRpcMethodAttribute( "",
> RequestNamespadce="",
>
ResponseNamespace="")]
>
> Even though it's generated in RPC style, the .Net WSDL still has
> several incompatibilities with the IBM WSTK proxygen utility
> (using .Net Studio beta 2 and IBM WSTK V2.3). The ones I've
> identified so far are:
>
> - Different Rules for Resolving Fully Qualified Definitions: For
> instance, .Net creates a s0 namespace (tempuri.com by default) and
> tries to qualify types to s0 that are actually defined in the
current
> document. The proxygen does not appear to look in the current
> document for fully qualified types. My solution so far has been to
> delete "s0:" qualifications from these, including the <port
binding>,
> <binding type>, etc.
>
> - Different Levels of Support for XML Schema: .Net generates 2001
XML
> Schema namespace, IBM WSTK expects 1999. So far, changing the WSDL
> to 1999 has worked.
>
> - HTTP Get/Post Support: I need to research this one further,
> however proxygen does not accept the .Net generated definitions for
> these. I was more interested in getting the SOAP binding to work,
so
> I haven't spent much time on it yet.
>
> I realize this is a short-term problem until the tools are more
> mature, but are there any solutions that might be more elegant than
> directly editing the WSDL, such as additional .Net attributes, etc.?
>
> Thanks in advance for any suggestions...
>
> Best Regards,
> Paul
>
>
Your message has been successfully submitted and would be delivered to recipients shortly. | https://groups.yahoo.com/neo/groups/soapbuilders/conversations/topics/4175?l=1 | CC-MAIN-2016-07 | refinedweb | 865 | 60.21 |
Views are part of the MVC architecture. They are code responsible for presenting data to end users. In a Web application, views are usually created in terms of view templates which are PHP script files containing mainly HTML code and presentational PHP code. They are managed by the view application component which provides commonly used methods to facilitate view composition and rendering. For simplicity, we often call view templates or view template files as views.
As aforementioned, a view is simply a PHP script mixed with HTML and PHP code. The following is the view that presents a login form. As you can see, PHP code is used to generate the dynamic content, such as the page title and the form, while HTML code organizes them into a presentable HTML page.
use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $form yii\widgets\ActiveForm */ /* @var $model app\models\LoginForm */ $this->title = 'Login'; <h1> = Html::encode($this->title) </h1> <p>Please fill out the following fields to login:</p> $form = ActiveForm::begin(); = $form->field($model, 'username') = $form->field($model, 'password')->passwordInput() = Html::submitButton('Login') ActiveForm::end();
Within a view, you can access
$this which refers to the view component managing
and rendering this view template.
Besides
$this, there may be other predefined variables in a view, such as
$model in the above
example. These variables represent the data that are pushed into the view by controllers
or other objects which trigger the view rendering.
Tip: The predefined variables are listed in a comment block at beginning of a view so that they can be recognized by IDEs. It is also a good way of documenting your views.
When creating views that generate HTML pages, it is important that you encode and/or filter the data coming from end users before presenting them. Otherwise, your application may be subject to cross-site scripting attacks.
To display a plain text, encode it first by calling yii\helpers\Html::encode(). For example, the following code encodes the user name before displaying it:
use yii\helpers\Html; <div class="username"> <?= Html::encode($user->name) ?> </div>
To display HTML content, use yii\helpers\HtmlPurifier to filter the content first. For example, the following code filters the post content before displaying it:
use yii\helpers\HtmlPurifier; <div class="post"> <?= HtmlPurifier::process($post->text) ?> </div>
Tip: While HTMLPurifier does excellent job in making output safe, it is not fast. You should consider caching the filtering result if your application requires high performance.
Like controllers and models, there are conventions to organize views.
@app/views/ControllerIDby default, where
ControllerIDrefers to the controller ID. For example, if the controller class is
PostController, the directory would be
@app/views/post; if it is
PostCommentController, the directory would be
@app/views/post-comment. In case the controller belongs to a module, the directory would be
views/ControllerIDunder the module directory.
WidgetPath/viewsdirectory by default, where
WidgetPathstands for the directory containing the widget class file.
You may customize these default view directories by overriding the yii\base\ViewContextInterface::getViewPath() method of controllers or widgets.
You can render views in controllers, widgets, or any other places by calling view rendering methods. These methods share a similar signature shown as follows,
/** * @param string $view view name or file path, depending on the actual rendering method * @param array $params the data to be passed to the view * @return string rendering result */ methodName($view, $params = [])
Within controllers, you may call the following controller methods to render views:
For example,
namespace app\controllers; use Yii; use app\models\Post; use yii\web\Controller; use yii\web\NotFoundHttpException; class PostController extends Controller { public function actionView($id) { $model = Post::findOne($id); if ($model === null) { throw new NotFoundHttpException; } // renders a view named "view" and applies a layout to it return $this->render('view', [ 'model' => $model, ]); } }
Within widgets, you may call the following widget methods to render views.
For example,
namespace app\components; use yii\base\Widget; use yii\helpers\Html; class ListWidget extends Widget { public $items = []; public function run() { // renders a view named "list" return $this->render('list', [ 'items' => $this->items, ]); } }
You can render a view within another view by calling one of the following methods provided by the view component:
For example, the following code in a view renders the
_overview.php view file which is in the same directory
as the view being currently rendered. Remember that
$this in a view refers to the view component:
$this->render('_overview')=
In any place, you can get access to the view application component by the expression
Yii::$app->view and then call its aforementioned methods to render a view. For example,
// displays the view file "@app/views/site/license.php" echo \Yii::$app->view->renderFile('@app/views/site/license.php');
When you render a view, you can specify the view using either a view name or a view file path/alias. In most cases, you would use the former because it is more concise and flexible. We call views specified using names as named views.
A view name is resolved into the corresponding view file path according to the following rules:
.phpwill be used as the extension. For example, the view name
aboutcorresponds to the file name
about.php.
//, the corresponding view file path would be
@app/views/ViewName. That is, the view is looked for under the application's view path. For example,
//site/aboutwill be resolved into
@app/views/site/about.php.
/, the view file path is formed by prefixing the view name with the view path of the currently active module. If there is no active module,
@app/views/ViewNamewill be used. For example,
/user/createwill be resolved into
@app/modules/user/views/user/create.php, if the currently active module is
user. If there is no active module, the view file path would be
@app/views/user/create.php.
aboutwill be resolved into
@app/views/site/about.phpif the context is the controller
SiteController.
itemwill be resolved into
@app/views/post/item.phpif it is being rendered in the view
@app/views/post/index.php.
According to the above rules, calling
$this->render('view') in a controller
app\controllers\PostController will
actually render the view file
@app/views/post/view.php, while calling
$this->render('_overview') in that view
will render the view file
@app/views/post/_overview.php.
There are two approaches to access data within a view: push and pull.
By passing the data as the second parameter to the view rendering methods, you are using the push approach.
The data should be represented as an array of name-value pairs. When the view is being rendered, the PHP
extract() function will be called on this array so that the array is extracted into variables in the view.
For example, the following view rendering code in a controller will push two variables to the
report view:
$foo = 1 and
$bar = 2.
echo $this->render('report', [ 'foo' => 1, 'bar' => 2, ]);
The pull approach actively retrieves data from the view component or other objects accessible
in views (e.g.
Yii::$app). Using the code below as an example, within the view you can get the controller object
by the expression
$this->context. And as a result, it is possible for you to access any properties or methods
of the controller in the
report view, such as the controller ID shown in the following:
The controller ID is: $this->context->id=
The push approach is usually the preferred way of accessing data in views, because it makes views less dependent on context objects. Its drawback is that you need to manually build the data array all the time, which could become tedious and error prone if a view is shared and rendered in different places.
The view component provides the params property that you can use to share data among views.
For example, in an
about view, you can have the following code which specifies the current segment of the
breadcrumbs.
$this->params['breadcrumbs'][] = 'About Us';
Then, in the layout file, which is also a view, you can display the breadcrumbs using the data passed along params:
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [], ])= yii\widgets\Breadcrumbs::widget([
Layouts are a special type of views that represent the common parts of multiple views. For example, the pages for most Web applications share the same page header and footer. While you can repeat the same page header and footer in every view, a better way is to do this once in a layout and embed the rendering result of a content view at an appropriate place in the layout.
Because layouts are also views, they can be created in the similar way as normal views. By default, layouts
are stored in the directory
@app/views/layouts. For layouts used within a module,
they should be stored in the
views/layouts directory under the module directory.
You may customize the default layout directory by configuring the yii\base\Module::$layoutPath property of
the application or modules.
The following example shows how a layout looks like. Note that for illustrative purpose, we have greatly simplified the code in the layout. In practice, you may want to add more content to it, such as head tags, main menu, etc.
use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $content string */ $this->beginPage() <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> = Html::csrfMetaTags() <title> = Html::encode($this->title) </title> $this->head() </head> <body> $this->beginBody() <header>My Company</header> = $content <footer>© 2014 by My Company</footer> $this->endBody() </body> </html> $this->endPage()
As you can see, the layout generates the HTML tags that are common to all pages. Within the
<body> section,
the layout echoes the
$content variable which represents the rendering result of content views and is pushed
into the layout when yii\base\Controller::render() is called.
Most layouts should call the following methods like shown in the above code. These methods mainly trigger events about the rendering process so that scripts and tags registered in other places can be properly injected into the places where these methods are called.
<head>section of an HTML page. It generates a placeholder which will be replaced with the registered head HTML code (e.g. link tags, meta tags) when a page finishes rendering.
<body>section. It triggers the EVENT_BEGIN_BODY event and generates a placeholder which will be replaced by the registered HTML code (e.g. JavaScript) targeted at the body begin position.
<body>section. It triggers the EVENT_END_BODY event and generates a placeholder which will be replaced by the registered HTML code (e.g. JavaScript) targeted at the body end position.
Within a layout, you have access to two predefined variables:
$this and
$content. The former refers to
the view component, like in normal views, while the latter contains the rendering result of a content
view which is rendered by calling the render() method in controllers.
If you want to access other data in layouts, you have to use the pull method as described in the Accessing Data in Views subsection. If you want to pass data from a content view to a layout, you may use the method described in the Sharing Data among Views subsection.
As described in the Rendering in Controllers subsection, when you render a view
by calling the render() method in a controller, a layout will be applied
to the rendering result. By default, the layout
@app/views/layouts/main.php will be used.
You may use a different layout by configuring either yii\base\Application::$layout or yii\base\Controller::$layout.
The former governs the layout used by all controllers, while the latter overrides the former for individual controllers.
For example, the following code makes the
post controller to use
@app/views/layouts/post.php as the layout
when rendering its views. Other controllers, assuming their
layout property is untouched, will still use the default
@app/views/layouts/main.php as the layout.
namespace app\controllers; use yii\web\Controller; class PostController extends Controller { public $layout = 'post'; // ... }
For controllers belonging to a module, you may also configure the module's layout property to use a particular layout for these controllers.
Because the
layout property may be configured at different levels (controllers, modules, application),
behind the scene Yii takes two steps to determine what is the actual layout file being used for a particular controller.
In the first step, it determines the layout value and the context module:
null, use it as the layout value and the module of the controller as the context module.
null, search through all ancestor modules (including the application itself) of the controller and find the first module whose layout property is not
null. Use that module and its layout value as the context module and the chosen layout value. If such a module cannot be found, it means no layout will be applied.
In the second step, it determines the actual layout file according to the layout value and the context module determined in the first step. The layout value can be:
@app/views/layouts/main).
/main): the layout value starts with a slash. The actual layout file will be looked for under the application's layout path which defaults to
@app/views/layouts.
main): the actual layout file will be looked for under the context module's layout path which defaults to the
views/layoutsdirectory under the module directory.
false: no layout will be applied.
If the layout value does not contain a file extension, it will use the default one
.php.
Sometimes you may want to nest one layout in another. For example, in different sections of a Web site, you want to use different layouts, while all these layouts share the same basic layout that generates the overall HTML5 page structure. You can achieve this goal by calling beginContent() and endContent() in the child layouts like the following:
$this->beginContent('@app/views/layouts/base.php'); ...child layout content here... $this->endContent();
As shown above, the child layout content should be enclosed within beginContent() and endContent(). The parameter passed to beginContent() specifies what is the parent layout. It can be either a layout file or alias.
Using the above approach, you can nest layouts in more than one levels.
Blocks allow you to specify the view content in one place while displaying it in another. They are often used together with layouts. For example, you can define a block in a content view and display it in the layout.
You call beginBlock() and endBlock() to define a block.
The block can then be accessed via
$view->blocks[$blockID], where
$blockID stands for a unique ID that you assign
to the block when defining it.
The following example shows how you can use blocks to customize specific parts of a layout in a content view.
First, in a content view, define one or multiple blocks:
... $this->beginBlock('block1'); ...content of block1... $this->endBlock(); ... $this->beginBlock('block3'); ...content of block3... $this->endBlock();
Then, in the layout view, render the blocks if they are available, or display some default content if a block is not defined.
... if (isset($this->blocks['block1'])): = $this->blocks['block1'] else: ... default content for block1 ... endif; ... if (isset($this->blocks['block2'])): = $this->blocks['block2'] else: ... default content for block2 ... endif; ... if (isset($this->blocks['block3'])): = $this->blocks['block3'] else: ... default content for block3 ... endif; ...
View components provides many view-related features. While you can get view components
by creating individual instances of yii\base\View or its child class, in most cases you will mainly use
the
view application component. You can configure this component in application configurations
like the following:
[ // ... 'components' => [ 'view' => [ 'class' => 'app\components\View', ], // ... ], ]
View components provide the following useful view-related features, each described in more details in a separate section:
You may also frequently use the following minor yet useful features when you are developing Web pages.
Every Web page should have a title. Normally the title tag is being displayed in a layout. However, in practice the title is often determined in content views rather than layouts. To solve this problem, yii\web\View provides the title property for you to pass the title information from content views to layouts.
To make use of this feature, in each content view, you can set the page title like the following:
$this->title = 'My page title';
Then in the layout, make sure you have the following code in the
<head> section:
<title>$this->title) </title>= Html::encode(
Web pages usually need to generate various meta tags needed by different parties. Like page titles, meta tags
appear in the
<head> section and are usually generated in layouts.
If you want to specify what meta tags to generate in content views, you can call yii\web\View::registerMetaTag() in a content view, like the following:
$this->registerMetaTag(['name' => 'keywords', 'content' => 'yii, framework, php']);
The above code will register a "keywords" meta tag with the view component. The registered meta tag is rendered after the layout finishes rendering. The following HTML code will be generated and inserted at the place where you call yii\web\View::head() in the layout:
<meta name="keywords" content="yii, framework, php">
Note that if you call yii\web\View::registerMetaTag() multiple times, it will register multiple meta tags, regardless whether the meta tags are the same or not.
To make sure there is only a single instance of a meta tag type, you can specify a key as a second parameter when calling the method. For example, the following code registers two "description" meta tags. However, only the second one will be rendered.
$this->registerMetaTag(['name' => 'description', 'content' => 'This is my cool website made with Yii!'], 'description'); $this->registerMetaTag(['name' => 'description', 'content' => 'This website is about funny raccoons.'], 'description');
Like meta tags, link tags are useful in many cases, such as customizing favicon, pointing to RSS feed or delegating OpenID to another server. You can work with link tags in the similar way as meta tags by using yii\web\View::registerLinkTag(). For example, in a content view, you can register a link tag like follows,
$this->registerLinkTag([ 'title' => 'Live News for Yii', 'rel' => 'alternate', 'type' => 'application/rss+xml', 'href' => '', ]);
The code above will result in
<link title="Live News for Yii" rel="alternate" type="application/rss+xml" href="">
Similar as registerMetaTag(), you can specify a key when calling registerLinkTag() to avoid generating repeated link tags.
View components trigger several events during the view rendering process. You may respond to these events to inject content into views or process the rendering results before they are sent to end users.
falseto cancel the rendering process.
For example, the following code injects the current date at the end of the page body:
\Yii::$app->view->on(View::EVENT_END_BODY, function () { echo date('Y-m-d'); });
Static pages refer to those Web pages whose main content are mostly static without the need of accessing dynamic data pushed from controllers.
You can output static pages by putting their code in the view, and then using the code like the following in a controller:
public function actionAbout() { return $this->render('about'); }
If a Web site contains many static pages, it would be very tedious repeating the similar code many times. To solve this problem, you may introduce a standalone action called yii\web\ViewAction in a controller. For example,
namespace app\controllers; use yii\web\Controller; class SiteController extends Controller { public function actions() { return [ 'page' => [ 'class' => 'yii\web\ViewAction', ], ]; } }
Now if you create a view named
about under the directory
@app/views/site/pages, you will be able to
display this view by the following URL:
The
GET parameter
view tells yii\web\ViewAction which view is requested. The action will then look
for this view under the directory
@app/views/site/pages. You may configure yii\web\ViewAction::$viewPrefix
to change the directory for searching these views.
Views are responsible for presenting models in the format that end users desire. In general, views
$_GET,
$_POST. This belongs to controllers. If request data is needed, they should be pushed into views by controllers.
To make views more manageable, avoid creating views that are too complex or contain too much redundant code. You may use the following techniques to achieve this goal:
Found a typo or you think this page needs improvement?
Edit it on github ! | https://www.yiiframework.com/doc/guide/2.0/uz/structure-views | CC-MAIN-2021-04 | refinedweb | 3,396 | 53.81 |
Match TypesEdit this page on GitHub
A match type reduces to one of a number of right hand sides, depending on a scrutinee type. Example:
type Elem[X] = X match { case String => Char case Array[t] => t case Iterable[t] => t }
This defines a type that, depending on the scrutinee type
X, can reduce to one of its right hand sides. For instance,
Elem[String] =:= Char Elem[Array[Int]] =:= Int Elem[List[Float]] =:= Float Elem[Nil] =:= Nothing
Here
=:= is understood to mean that left and right hand sides are mutually subtypes of each other.
In general, a match type is of the form
S match { P1 => Tn ... Pn => Tn }
where
S,
T1, ...,
Tn are types and
P1, ...,
Pn are type patterns. Type variables
in patterns start as usual with a lower case letter.
Match types can form part of recursive type definitions. Example:
type LeafElem[X] = X match { case String => Char case Array[t] => LeafElem[t] case Iterable[t] => LeafElem[t] case AnyVal => X }
Recursive match type definitions can also be given an upper bound, like this:
type Concat[+Xs <: Tuple, +Ys <: Tuple] <: Tuple = Xs match { case Unit => Ys case x *: xs => x *: Concat[xs, Ys] }
In this definition, every instance of
Concat[A, B], whether reducible or not, is known to be a subtype of
Tuple. This is necessary to make the recursive invocation
x *: Concat[xs, Ys] type check, since
*: demands a
Tuple as its right operand.
Representation of Match Types
The internal representation of a match type
S match { P1 => Tn ... Pn => Tn }
is
Match(S, C1, ..., Cn) <: B where each case
Ci is of the form
[Xs] => P => T
Here,
[Xs] is a type parameter clause of the variables bound in pattern
Pi. If there are no bound type variables in a case, the type parameter clause is omitted and only the function type
P => T is kept. So each case is either a unary function type or a type lambda over a unary function type.
B is the declared upper bound of the match type, or
Any if no such bound is given.
We will leave it out in places where it does not matter for the discussion. Scrutinee, bound and pattern types must be first-order types.
Match type reduction
We define match type reduction in terms of an auxiliary relation,
can-reduce:
Match(S, C1, ..., Cn) can-reduce i, T'
if
Ci = [Xs] => P => T and there are minimal instantiations
Is of the type variables
Xs such that
S <: [Xs := Is] P T' = [Xs := Is] T
An instantiation
Is is minimal for
Xs if all type variables in
Xs that appear
covariantly and nonvariantly in
Is are as small as possible and all type variables in
Xs that appear contravariantly in
Is are as large as possible. Here, "small" and "large" are understood wrt
<:.
For simplicity, we have omitted constraint handling so far. The full formulation of subtyping tests describes them as a function from a constraint and a pair of types to
either success and a new constraint or failure. In the context of reduction, the subtyping test
S <: [Xs := Is] P is understood to leave the bounds of all variables
in the input constraint unchanged, i.e. existing variables in the constraint cannot be instantiated by matching the scrutinee against the patterns.
Using
can-reduce, we can now define match type reduction proper in the
reduces-to relation:
Match(S, C1, ..., Cn) reduces-to T
if
Match(S, C1, ..., Cn) can-reduce i, T
and, for
j in
1..i-1:
C_j is disjoint from
C_i, or else
S cannot possibly match
C_j.
See the section on overlapping patterns for an elaboration of "disjoint" and "cannot possibly match".
Subtyping Rules for Match Types
The following rules apply to match types. For simplicity, we omit environments and constraints.
The first rule is a structural comparison between two match types:
Match(S, C1, ..., Cn) <: Match(T, D1, ..., Dm)
if
S <: T, m <= n, Ci <: Di for i in 1..n
I.e. scrutinees and corresponding cases must be subtypes, no case re-ordering is allowed, but the subtype can have more cases than the supertype.
The second rule states that a match type and its redux are mutual subtypes
Match(S, Cs) <: T T <: Match(S, Cs)
if
Match(S, Cs) reduces-to T
The third rule states that a match type conforms to its upper bound
(Match(S, Cs) <: B) <: B
Variance Laws for Match Types
Within a match type
Match(S, Cs) <: B, all occurrences of type variables count as covariant. By the nature of the cases
Ci this means that occurrences in pattern position are contravarant (since patterns are represented as function type arguments).
Typing Rules for Match Expressions
Typing rules for match expressions are tricky. First, they need some new form of GADT matching for value parameters. Second, they have to account for the difference between sequential match on the term level and parallel match on the type level. As a running example consider:
type M[+X] = X match { case A => 1 case B => 2 }
We'd like to be able to typecheck
def m[X](x: X): M[X] = x match { case _: A => 1 // type error case _: B => 2 // type error }
Unfortunately, this goes nowhere. Let's try the first case. We have:
x.type <: A and
x.type <: X. This tells
us nothing useful about
X, so we cannot reduce
M in order to show that the right hand side of the case is valid.
The following variant is more promising:
def m(x: Any): M[x.type] = x match { case _: A => 1 case _: B => 2 }
To make this work, we'd need a new form of GADT checking: If the scrutinee is a term variable
s, we can make use of
the fact that
s.type must conform to the pattern's type and derive a GADT constraint from that. For the first case above,
this would be the constraint
x.type <: A. The new aspect here is that we need GADT constraints over singleton types where
before we just had constraints over type parameters.
Assuming this extension, we can then try to typecheck as usual. E.g. to typecheck the first case
case _: A => 1 of the definition of
m above, GADT matching will produce the constraint
x.type <: A. Therefore,
M[x.type] reduces to the singleton type
1. The right hand side
1 of the case conforms to this type, so the case typechecks.
Typechecking the second case hits a snag, though. In general, the assumption
x.type <: B is not enough to prove that
M[x.type] reduces to
2. However we can reduce
M[x.type] to
2 if the types
A and
B do not overlap.
So correspondence of match terms to match types is feasible only in the case of non-overlapping patterns.
For simplicity, we have disregarded the
null value in this discussion.
null does not cause a fundamental problem but complicates things somewhat because some forms of patterns do not match
null.
Overlapping Patterns
A complete defininition of when two patterns or types overlap still needs to be worked out. Some examples we want to cover are:
- Two classes overlap only if one is a subtype of the other
- A final class
Coverlaps with a trait
Tonly if
Cextends
Tdirectly or indirectly.
- A class overlaps with a sealed trait
Tonly if it overlaps with one of the known subclasses of
T.
- An abstract type or type parameter
Aoverlaps with a type
Bonly if
A's upper bound overlaps with
B.
- A union type
A_1 | A_2overlaps with
Bonly if
A_1overlaps with
Bor
A_2overlaps with
B.
- An intersection type
A_1 & A_2overlaps with
Bonly if both
A_1and
A_2overlap with
B.
- If
C[X_1, ..., X_n]is a case class, then the instance type
C[A_1, ..., A_n]overlaps with the instance type
C[B_1, ..., B_n]only if for every index
iin
1..n, if
X_iis the type of a parameter of the class, then
A_ioverlaps with
B_i.
The last rule in particular is needed to detect non-overlaps for cases where the scrutinee and the patterns are tuples. I.e.
(Int, String) does not overlap
(Int, Int) since
String does not overlap
Int.
Handling Termination
Match type definitions can be recursive, which raises the question whether and how to check that reduction terminates. This is currently an open question. We should investigate whether there are workable ways to enforce that recursion is primitive.
Note that, since reduction is linked to subtyping, we already have a cycle dectection mechanism in place. So the following will already give a reasonable error message:
type L[X] = X match { case Int => L[X] } def g[X]: L[X] = ???
| val x: Int = g[Int] | ^^^^^^ | found: Test.L[Int] | required: Int
The subtype cycle test can be circumvented by producing larger types in each recursive invocation, as in the following definitions:
type LL[X] = X match { case Int => LL[LL[X]] } def gg[X]: LL[X] = ???
In this case subtyping enters into an infinite recursion. This is not as bad as it looks, however, because
dotc turns selected stack overflows into type errors. If there is a stackoverflow during subtyping,
the exception will be caught and turned into a compile-time error that indicates
a trace of the subtype tests that caused the overflow without showing a full stacktrace.
Concretely:
| val xx: Int = gg[Int] | ^ |Recursion limit exceeded. |Maybe there is an illegal cyclic reference? |If that's not the case, you could also try to increase the stacksize using the -Xss JVM option. |A recurring operation is (inner to outer): | | subtype Test.LL[Int] <:< Int | subtype Test.LL[Int] <:< Int | ... | subtype Test.LL[Int] <:< Int
(The actual error message shows some additional lines in the stacktrace).
Related Work
Match types have similarities with closed type families in Haskell. Some differences are:
- Subtyping instead of type equalities.
- Match type reduction does not tighten the underlying constraint, whereas type family reduction does unify. This difference in approach mirrors the difference between local type inference in Scala and global type inference in Haskell.
- No a-priori requirement that cases are non-overlapping. Uses parallel reduction instead of always chosing a unique branch.
Match types are also similar to Typescript's conditional types. The main differences here are:
- Conditional types only reduce if scrutinee and pattern are ground, whereas match types also work for type parameters and abstract types.
- Match types can bind variables in type patterns.
- Match types support direct recursion.
Conditional types in Typescript distribute through union types. We should evaluate whether match types should support this as well. | http://dotty.epfl.ch/docs/reference/new-types/match-types.html | CC-MAIN-2019-22 | refinedweb | 1,775 | 72.26 |
. The better the communication, the more effectively ideas can be shared and topics discussed. And while there are lots of resources out there for general advice about how to communicate well, and we have dictionaries and thesauruses when we need to figure out what words mean, industry-specific language can be more challenging.
Whether you call it jargon, lingo, or something else, some words only make sense in the context of a specific industry. In the case of software development, sometimes a specific programming language, library, or tool even has its own terms. And you won’t find them in most dictionaries.
Because they’re so specific to particular fields and are often taught verbally to new people as they’re learning the ropes, it’s much easier for there to be misunderstandings around some of these words. Today, I’d like to talk about a few of those words in the context of React.
What is React?
If you aren’t already familiar with it, React’s purpose is to speed up the display of the user interface for web apps. It’s a JavaScript library that acts as an intermediary between business logic and the browser. As a developer, I tell React what I want to appear on the screen and it works its magic to make sure those things appear quickly and update efficiently as the user interacts with them.
A responsive and snappy user interface is an important part of any application so it’s easy to see why we use React at Metal Toad - because we care about the experience of our users and are dedicated to using the latest tools to give them the best experience possible.
Now that you have some context for why we use React, let's look at the smallest parts of a React app:
Elements
React elements are the building blocks of React. They are objects used to create a representation of each part of what should be displayed on the screen - each *element*, you might say.
So what does an element look like in code? It looks like this:
<div />
Or, if you're working on a project that doesn't use JSX, then it would look like this:
React.createElement('div')
(JSX compiles to regular JavaScript functions - see how it works with Babel’s interactive compiler.)
That function call creates a JavaScript object which includes all of the information React needs to display that piece of the user interface and control it. You might recognize this element as the humble
<div> tag from HTML. In fact, that is the code to create that tag in React. Of course, the fun really starts when we combine multiple elements. Let's look at a larger element:
<div> <h1>React Stuff You Need to Know</h1> <p>Here is some stuff about React…</p> </div>
As you can see, there are 3 elements here:
<div>,
<h1>, and
<p>. However, this code still only returns one element. Why? Looking at the non-JSX version will be helpful here:
React.createElement('div', null, React.createElement('h1', null, 'React Stuff You Need to Know'), React.createElement('p', null, 'Here is some stuff about React…') )
The three elements are definitely created, but the two child elements become a part of the parent element. The parent element function call takes the function calls for the children as two of its parameters so the end result is one return from the parent function call.
So far we've been just using standard HTML tags as React elements. Let's switch now and look at how you can create your own elements:
Components
In React, a component is a function that returns a React element. Let's take a look at one:
const ReallyCoolComponent = () => (<div />)
Here are a few other ways of creating the same function using different JavaScript syntax:
function ReallyCoolComponent() { return <div /> } const ReallyCoolComponent = () => React.createElement('div') function ReallyCoolComponent() { return React.createElement('div') }
Now this is a pretty basic component - and frankly, not super useful - but it illustrates all of the requirements for a React component:
It's a function
It returns a React element
That's it! If it has those two properties, it's a React component.
If you've used React some, you might have some objections to this simplistic definition:
Q: What about Class components?
A: Yes, you can use the class syntax to define a React component and it is different than simply defining it using a function, but ultimately *it is still a function*. Don't believe me? Try it yourself in a Repl.
Of course, this doesn’t mean that a functional component and a class component are the same. It just means they both fit the description of being a function.
Q: Doesn't React accept other things besides React elements in the return of a component?
A: Yep, you've got me there. Strings, numbers, booleans, and null are also allowed. The first two are turned into React elements automagically and the other two are ignored (but valid). For simplicity, I'm including all of these things under the umbrella of React elements because React treats them all like elements (or the lack thereof).
Q: What about props?
A: Good question! Although props are almost always used in a component, they're not actually required. If they are used, though, they add two additional rules:
The only parameter a React Component accepts is one object called
props.
The component must act like a pure function with regard to it's props.
Let's look at a component that accepts props:
const ApplePicker = (props) => { return ( <div> <p>{`I picked ${props.picked} apples today!`}</p> <p>{`I should pick ${props.totalNeeded - props.picked} more…`}</p> </div> ) }
You can see that it accepts a single parameter object. In this case, it expects that object to have two properties called
picked and
totalNeeded. It can then use those properties to display data and, in this case, calculate how many more apples should be picked.
Importantly, the component doesn't change its props or take in additional parameters. That's what it means to act like a pure function with regard to it's props (our last rule).
Here’s the complete list of rules for a React component:
It must be a function. (Classes are functions.)
It must return a valid React element (including string, number, boolean, or null).
If it accepts parameters, it should accept one parameter object called 'props'.
It must act like a pure function with regard to its props.
Now that we have a pretty good handle on elements and components, let's take a look at the next step up from there:
Higher-Order Components
What’s a higher-order component? Just like a component is a function that returns a React element, a higher-order component (HOC) is a function that returns a React component. Let's jump straight in with an example:
const withData = (data, AComponent) => { return (props) => (<AComponent {...props} data={data} />) }
And for clarity, here it is without the JSX:
function withData(data, AComponent) { return function(props) { return React.createElement(AComponent, {...props, data}) } }
This is definitely a function, but is it an HOC? Let's do a quick check to see if what it returns is a React component using our four rules for React components:
Is it a function? Yep!
Does it return a React element? Yep. (Note:
AComponentis a React component, but
<AComponent … />is a React element.)
If it accepts parameters, is it one parameter called
props? Yep.
Does it act like a pure function with regard to its props? It does indeed.
Success! Since this function returns a component, it’s a higher order component. As you can see, it appears to be adding data to the props of
AComponent. This is one of the common ways HOC’s are used.
Don’t Forget Context
If you’re like me, you might already have realized that you’ve used one of these words incorrectly in a discussion about React. Especially when it comes to elements and components, the words are also used in more general ways so it’s easy to confuse them. That’s why it’s important to clarify the context for how you’re using these words. Usually, simply adding ‘React’ in front of ‘element’ or ‘component’ can help everyone follow you.
I also found that, when I tried to explain higher order components to a coworker, I couldn’t clearly articulate what I knew. That made it so even though we took the time to try to close a communication gap, we couldn’t quite do it on the spot. (It also led me to do the research that ultimately led to this blog post.)
Hopefully, this article has helped you to solidify your understanding of these concepts so you can use them confidently and help clear up any miscommunications that may happen to you and your team. Thanks for reading!
Other Resources
To continue reading about this subject, I recommend checking out these other great articles:
- The React introduction pages for Elements and Components (in that order)
- Dan Abramov's article about React Components, Elements, and Instances
Add new comment | https://www.metaltoad.com/blog/react-detail-elements-components-and-hocs | CC-MAIN-2020-16 | refinedweb | 1,536 | 62.98 |
Code blocks
The
CodeBlock feature allows inserting and editing blocks of pre–formatted code into the WYSIWYG editor. Each code block has a specific programming language assigned (e.g. “Java” or “CSS”) and supports basic editing tools, for instance, changing the line indentation using the keyboard.
If you would like to use inline code formatting in your WYSIWYG editor, check out the basic text styles feature with its support for inline
<code> element.
# Demo
# Configuring code block languages
Each code block can be assigned a programming language. The language of the code block is represented as a CSS class of the
<code> element, both when editing and in the editor data:
<pre><code class="language-javascript">window.alert( 'Hello world!' )</code></pre>
It is possible to configure which languages are available to the users. You can use the
codeBlock.languages configuration and define your own languages. For example, the following editor supports only two languages (CSS and HTML):
ClassicEditor .create( document.querySelector( '#editor' ), { codeBlock: { languages: [ { language: 'css', label: 'CSS' }, { language: 'html', label: 'HTML' } ] } } ) .then( ... ) .catch( ... );
Put some text in the
<body>:
Hello world!
Then set the font color:
body { color: red }
By default, the CSS class of the
<code> element in the data and editing is generated using the
language property (prefixed with “language-”). You can customize it by specifying an optional
class property. You can set multiple classes but only the first one will be used as defining language class:
ClassicEditor .create( document.querySelector( '#editor' ), { codeBlock: { languages: [ // Do not render the CSS class for the plain text code blocks. { language: 'plaintext', label: 'Plain text', class: '' }, // Use the "php-code" class for PHP code blocks. { language: 'php', label: 'PHP', class: 'php-code' }, // Use the "js" class for JavaScript code blocks. // Note that only the first ("js") class will determine the language of the block when loading data. { language: 'javascript', label: 'JavaScript', class: 'js javascript js-code' }, // Python code blocks will have the default "language-python" CSS class. { language: 'python', label: 'Python' } ] } } ) .then( ... ) .catch( ... );
The first language defined in the configuration is considered the default one. This means it will be applied to code blocks loaded from the data that have no CSS
class specified (or no
class matching the configuration). It will also be used when creating new code blocks using the toolbar button. By default it is “Plain text” (the
language-plaintext CSS class).
# Integration with code highlighters
Although live code block highlighting is impossible when editing in CKEditor 5 (learn more), the content can be highlighted when displayed in the frontend (e.g. in blog posts, messages, etc.).
The code language configuration helps to integrate with external code highlighters (e.g. highlight.js or Prism). Please refer to the documentation of the highlighter of your choice and make sure the CSS classes configured in
codeBlock.languages correspond with the code syntax auto–detection feature of the highlighter.
# Tips and tweaks
# Editing text around code blocks
There could be situations when there is no obvious way to set the caret before or after a block of code and type. This can happen when the code block is preceded or followed by a widget (e.g. a table) or when the code block is the first or the last child of the document (or both).
To type before the code block: Put the selection at the beginning of the first line of the code block and press Enter. Move the selection to the empty line that has been created and press Enter again. A new paragraph that you can type in will be created before the code block.
To type after the code block: Put the selection at the end of the last line of the code block and press Enter twice. A new paragraph that you can type in will be created after the code block.
# Changing line indentation
You can change the indentation of the code using keyboard shortcuts and toolbar buttons:
- To increase indentation: Select the line (or lines) you want to indent. Hit the Tab key or press the “Increase indent” button in the toolbar.
- To decrease indentation: Select the line (or lines) the indent should decrease. Hit the Shift+Tab keys or press the “Decrease indent” button in the toolbar.
The indentation created this way can be changed. Use the
codeBlock.indentSequence configuration to choose some other character (or characters) of your preference (e.g. four spaces). By default, the indentation changes by a single tab (
\t) character.
You can disable the indentation tools and their associated keystrokes altogether by setting the
codeBlock.indentSequence configuration to
false.
# Preserving line indentation
To speed up the editing, when typing in a code block, the indentation of the current line is preserved when you hit Enter and create a new line. If you want to change the indentation of the new line, take a look at some easy ways to do that.
# Installation
To add the code blocks feature to your rich-text editor, install the
@ckeditor/ckeditor5-code-block package:
npm install --save @ckeditor/ckeditor5-code-block
Then add it to your plugin list and the toolbar configuration:
import CodeBlock from '@ckeditor/ckeditor5-code-block/src/codeblock'; ClassicEditor .create( document.querySelector( '#editor' ), { plugins: [ CodeBlock, ... ], toolbar: [ 'codeBlock', ... ] } ) .then( ... ) .catch( ... );
Read more about installing plugins.
# Common API
The
CodeBlock plugin registers:
The
'codeBlock'split button with a dropdown allowing to choose the language of the block.
The
'codeBlock'command.
The command converts selected WYSIWYG editor content into a code block. If no content is selected, it creates a new code block at the place of the selection.
You can choose which language the code block is written in when executing the command. The language will be set in the editor model and reflected as a CSS class visible in the editing view and the editor (data) output:
editor.execute( 'codeBlock', { language: 'css' } );
When executing the command, you can use languages defined by the
codeBlock.languagesconfiguration. The default list of languages is as follows:
codeBlock.languages: [ { language: 'plaintext', label: 'Plain text' }, // The default language. { language: 'c', label: 'C' }, { language: 'cs', label: 'C#' }, { language: 'cpp', label: 'C++' }, { language: 'css', label: 'CSS' }, { language: 'diff', label: 'Diff' }, { language: 'html', label: 'HTML' }, { language: 'java', label: 'Java' }, { language: 'javascript', label: 'JavaScript' }, { language: 'php', label: 'PHP' }, { language: 'python', label: 'Python' }, { language: 'ruby', label: 'Ruby' }, { language: 'typescript', label: 'TypeScript' }, { language: 'xml', label: 'XML' } ]
Note: If you execute the command with a specific
languagewhen the selection is anchored in a code block, and use the additional
forceValue: trueparameter, it will update the language of this particular block.
editor.execute( 'codeBlock', { language: 'java', forceValue: true } );
Note: If the selection is already in a code block, executing the command will convert the block back into plain paragraphs.
The
'indentCodeBlock'and
'outdentCodeBlock'commands.
Both commands are used by the Tab and Shift+Tab keystrokes as described in the section about indentation:
- The
'indentCodeBlock'command is enabled when the selection is anchored anywhere in the code block and it allows increasing the indentation of the lines of code. The indentation character (sequence) is configurable using the
codeBlock.indentSequenceconfiguration.
- The
'outdentCodeBlock'command is enabled when the indentation of any code lines within the selection can be decreased. Executing it will remove the indentation character (sequence) from these lines, as configured by
codeBlock.indentSequence.. | https://ckeditor.com/docs/ckeditor5/22.0.0/features/code-blocks.html | CC-MAIN-2020-40 | refinedweb | 1,210 | 54.73 |
Sharing the goodness…
Beth Massi is a Senior Program Manager on the Visual Studio team at Microsoft and a community champion for business application developers. Learn more about Beth.
More videos »
We just got a new section started on the Visual Basic Community page that showcases donated articles from the expert VB community. The first article Jim Duffy, a Visual Basic MVP, walks us through System.Net.Mail namespace. More articles from our MVPs will come online every few weeks. Stay tuned for WCF and WPF/Silverlight content in the coming months! Many thanks to the MVPs that have volunteered so far.
Enjoy! | http://blogs.msdn.com/b/bethmassi/archive/2007/07/23/new-community-articles-on-the-vb-developer-center.aspx | CC-MAIN-2013-48 | refinedweb | 103 | 56.96 |
A.
Definition at line 69 of file TProcessID.h.
#include <TProcessID.h>
Default constructor.
Definition at line 75 of file TProcessID.cxx.
Destructor.
Definition at line 93 of file TProcessID.cxx.
Static function to add a new TProcessID to the list of PIDs.
Definition at line 114 of file TProcessID.cxx.
static function returning the ID assigned to obj If the object is not yet referenced, its kIsReferenced bit is set and its fUniqueID set to the current number of referenced objects so far.
Definition at line 153 of file TProcessID.cxx.
Initialize fObjects.
Definition at line 190 of file TProcessID.cxx.
static function (called by TROOT destructor) to delete all TProcessIDs
Definition at line 202 of file TProcessID.cxx.
delete the TObjArray pointing to referenced objects this function is called by TFile::Close("R")
Reimplemented from TNamed.
Definition at line 216 of file TProcessID.cxx.
The reference fCount is used to delete the TProcessID in the TFile destructor when fCount = 0.
Definition at line 236 of file TProcessID.cxx.
Definition at line 93 of file TProcessID.h.
Return the (static) number of process IDs.
Definition at line 254 of file TProcessID.cxx.
Return the current referenced object count fgNumber is incremented every time a new object is referenced.
Definition at line 322 of file TProcessID.cxx.
Definition at line 94 of file TProcessID.h.
returns the TObject with unique identifier uid in the table of objects
Definition at line 330 of file TProcessID.cxx.
static: returns pointer to current TProcessID
Definition at line 341 of file TProcessID.cxx.
static: returns array of TProcessIDs
Definition at line 349 of file TProcessID.cxx.
static function returning a pointer to TProcessID number pid in fgPIDs
Definition at line 246 of file TProcessID.cxx.
static function returning a pointer to TProcessID with its pid encoded in the highest byte of obj->GetUniqueID()
Definition at line 295 of file TProcessID.cxx.
static function returning a pointer to TProcessID with its pid encoded in the highest byte of uid
Definition at line 263 of file TProcessID.cxx.
static function returning the pointer to the session TProcessID
Definition at line 303 of file TProcessID.cxx.
Increase the reference count to this object.
Definition at line 311 of file TProcessID.cxx.
static function. return kTRUE if pid is a valid TProcessID
Definition at line 358 of file TProcessID.cxx.
stores the object at the uid th slot in the table of objects The object uniqued is set as well as its kMustCleanup bit
Definition at line 381 of file TProcessID.cxx.
called by the object destructor remove reference to obj from the current table if it is referenced
Reimplemented from TObject.
Definition at line 410 of file TProcessID.cxx.
static function to set the current referenced object count fgNumber is incremented every time a new object is referenced
Definition at line 434 of file TProcessID.cxx.
Definition at line 76 of file TProcessID.h.
Definition at line 84 of file TProcessID.h.
Definition at line 82 of file TProcessID.h.
Spin lock for initialization of fObjects.
Definition at line 80 of file TProcessID.h.
Definition at line 81 of file TProcessID.h.
Array pointing to the referenced objects.
Definition at line 78 of file TProcessID.h.
Reference count to this object (from TFile)
Definition at line 77 of file TProcessID.h. | https://root.cern.ch/doc/v622/classTProcessID.html | CC-MAIN-2021-21 | refinedweb | 554 | 50.84 |
MOVE_PANEL(3) NetBSD Library Functions Manual MOVE_PANEL(3)Powered by man-cgi (2021-06-01). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.
NAME
move_panel -- change panel position
LIBRARY
Z-order for curses windows (libpanel, -lpanel)
SYNOPSIS
#include <panel.h> int move_panel(PANEL *p, int y, int x);
DESCRIPTION
A panel can be moved to a new position by calling the move_panel() func- tion. The y and x positions are the new origin of the panel on the screen. This function is the panel library counterpart of the curses mvwin(3) function. Curses mvwin() must never be directly used on a window associ- ated with a panel.
RETURN VALUES
The move_panel() function will return one of the following values: OK The function completed successfully. ERR An error occurred in the function.
SEE ALSO
mvwin(3), panel(3) NetBSD 9.99 October 28, 2015 NetBSD 9.99 | https://man.netbsd.org/move_panel.3 | CC-MAIN-2021-39 | refinedweb | 151 | 51.55 |
Recently and smallest values from a group of numbers without using Arrays. So here is another approach.
This program accepts input from the user and then prints out the largest and smallest numbers.
import java.util.*; public class NumberSorter{ public static void main(String args[]){ double a, b, c, x, y; Scanner console = new Scanner(System.in); System.out.print("Enter the first number: " ); a = console.nextDouble() ; System.out.print("Enter the second number: " ); b = console.nextDouble() ; System.out.print("Enter the third number: " ); c = console.nextDouble(); x= Math.min(a, Math.min(b, c)); y= Math.max(a, Math.max(b, c)); System.out.println("\n" +x + " is the smallest number.\n" + y +" is the largest number."); } }
Hope you find this useful. Share your ideas on how else can we find largest and smallest values from a group of numbers Java.
Genius! I didn’t know of those methods in java, Math.min() and Math.max(); Very useful thanks for sharing.
this is great! i havnt thought about this procedure.
I did a course of Java and for this method i’ve learned another algorithm. This method works too.
Nice article ! But I don’t think I can cope with it . LOL ! My nose is bleeding when it comes to math .
we can even divide the numbers in two – two parts n use if statements to compare the larger n smaller value .. that is a much easier way to understand .. according to me ! 🙂
thanks i will use this script codes
The following can also work:
Double[] dblArr = {a, b, c, x, y};
double x=Collections.min(Arrays.asList(dblArr));
double y = Collections.max(Arrays.asList(dblArr));
reali nyc…. fnx guys
thanks for the method! i really learned from u! God bless 🙂
Hi there to every body, it’s my first pay a quick visit of this webpage; this website carries awesome and genuinely excellent information in support of visitors.
What you said made a ton of sense. But, think on this, what if you were to
write a killer headline? I am not suggesting your information is
not good, but suppose you added a title to maybe grab people’s attention? I mean Sort numbers in Java to find minimum and maximum values without using Array is a little plain. You might look at Yahoo’s home page
and watch how they create post titles to grab people to open the links.
You might try adding a video or a pic or two to grab readers interested about
what you’ve written. In my opinion, it might bring your blog a little bit more interesting.
Terrific article! This is the type of information that should be shared across
the net. Shame on Google for no longer positioning this post upper!
Come on over and talk over with my website . Thank you =)
You can even reuse these and have whatsoever you like. The firm was started by British designers Melanie Marshall and Suzi Bergman.
A single has to verify for certificate expiry, and authorities who have licensed this website.
The initially matter you have to assume about is
the measurement..
com/
It’s genuinely very complex in this full of activity life to listen news on Television, therefore I just use web for that reason, and get the newest news.
Do you have a spam problem on this website; I also am a blogger, and I was curious about your situation; many of us have created some
nice practices and we are looking to swap techniques with other folks, why not shoot me
an email if interested.
Also visit my homepage; How To Make A Blog
website could certainly be one of the best in its niche.
Good blog!
Good day! This is my first comment here so I just wanted
to give a quick shout out and tell you I genuinely
enjoy reading your posts. Can you suggest any other blogs/websites/forums
that cover the same subjects? Thanks a lot!
I visited several web sites but the audio feature for audio songs current at this site is really wonderful.
I’m really impressed with your writing skills as well as with the structure in your weblog. Is this a paid theme or did you modify it yourself? Either way keep up the excellent quality writing, it is uncommon to see a nice blog like this one these days..
Thanks for finally writing about > Sort numbers in Java to find minimum and maximum values without using
Array < Loved it!
I like it when individuals come together and share
views. Great website, keep it up!
?????? ?????? ? ???? ??????? ??? ???? ???
??? ????? ???? ???? ???? ???? ?? ????? ???????? ? ?? ???????????????
?? ???? ? ??? ???1
? ? ?????? ???? ??? ?? ?? ? ???????
The situation needs extremely gourmet craftsmanship. Implementing
such approaches to applying designer companies is more
low cost for an natural people. Louis Vuitton Handbags can be seen all
over the post. Need to more and more people prefer style returning to
practical use found in a bag..
com/
Why people still make use of to read news papers when in this technological globe all is
existing on net?
Up above all, pick a shoe that can sometimes your feet comfortable.
It holds a high-resolution multi-touch more effective inch screen by using
a wide viewing slope. A pair of good quality jogging shoes is the single most
important item a athlete can buy. Gradually, Nike shoes have become the
footwear men like to put..
com/userinfo.php?uid=26554
I think that is one of the most vital information for me.
And i’m glad reading your article. However want to observation on some basic things, The site style is wonderful, the articles is in reality great : D. Good job, cheers
Umbrellas and wet tissues would also offer to the over-all weight of the bags.
In stand-up humorous you need for funny,
not your entire shirt. They have a meaningful nice, snug casual fit
and also nothing is made up. Is definitely important for a high heel
shoe for you to become well fitted..
hooptrick.org/profile.php?mode=viewprofile&u=17803
What’s up, I wish for to subscribe for this website to obtain latest updates, thus where can i do it please help.
????????????????????????yr-?????????????????????ft???????????????????????? ???? ?????????????????????????? ???? ?????? ????
???????????? ??? ?? .
Hello There. I found your blog using msn.
This is a very well written article. I will be sure
to bookmark it and return to read more of your useful information.
Thanks for the post. I’ll certainly return.
Feel free to surf to my web site … no przecie? nie
Fantastic goods from you, man. I have understand your
stuff previous to and you’re just too great. I actually like what you’ve acquired here, really
like what you’re saying and the way in which you say it. You make it enjoyable and you still care for to keep it smart. I can’t wait to read much more
from you. This is really a wonderful website.
If some one wants expert view on the topic of running a blog after that i recommend
him/her to go to see this website, Keep up the nice job.
Hi colleagues, how is everything, and what you want to say
concerning this article, in my view its actually awesome designed for me.
Asking questions are really pleasant thing if you are not understanding something entirely, but this paragraph gives nice understanding yet..
It is actually a nice and helpful piece of information. I am happy that you simply shared this helpful information with us. Please stay us informed like this. Thank you for sharing. fcfbffgfeged
Wonderful.
Greetings from Colorado! I’m bored at work so I decided to
I love the info you present here and can’t wait to take a look
when I get home. I’m amazed at how fast your blog loaded
on my phone .. I’m not even using WIFI, just 3G ..
Anyways, superb blog! | http://zparacha.com/sort-numbers-in-java-find-minimum-and-maximum-values-without-using-array | CC-MAIN-2017-51 | refinedweb | 1,306 | 75.91 |
Get Started with Microsoft Azure IoT Starter Kit - Adafruit Feather Huzzah ESP8266 (Arduino-compatible)
This page contains technical information to help you get familiar with Azure IoT using the Azure IoT Starter Kit - Adafruit Feather Huzzah ESP8266 (Arduino-compatible). You will find two tutorials that will walk you through different scenarios: the first tutorial will show you how to connect your Azure IoT Starter kit to our Remote Monitoring preconfigured solution from Azure IoT Suite. In the second tutorial, you will leverage Azure IoT services to create your own IoT architecture.
You can choose to start with whichever tutorial you want to. If you've never worked with Azure IoT services before, we encourage you to start with the Remote Monitoring solution tutorial, because all of the Azure services will be provisioned for you in a built-in preconfigured solution. Then you can explore how each of the services work by going through the second tutorial.
We hope you enjoy the process. Please provide feedback if there's anything that we can improve.
Don't have a kit yet?: Click here
- Running a Simple Remote Monitoring Solution on Adafruit Feather Huzzah ESP8266
- Using Microsoft Azure IoT to Process and Use Sensor Data to Indicate Abnormal Temperatures
Running a Simple Remote Monitoring Solution on Adafruit Feather Huzzah ESP8266 (Arduino-compatible)
This tutorial describes the process of taking your Adafruit Feather Huzzah ESP8266 kit, and using it to develop a temperature, humidity and pressure reader that can communicate with the cloud using the Microsoft Azure IoT SDK.
Table of Contents
- 1.1 Tutorial Overview
- 1.2 Before Starting
- 1.3 Connect your device to the Temperature sensor
- 1.4 Create a New Azure IoT Suite Remote Monitoring solution and Add Device
- 1.5 Configure the Arduino IDE
- 1.6 Modify the Remote Monitoring Sample
- 1.7 Build and Run Your Remote Monitoring Sample
- 1.8 View the Sensor Data from the Remote Monitoring Portal
- 1.9 Stop using the Azure IoT Suite
- 1.10 Next steps
1.1 Tutorial Overview
In this tutorial, you'll be doing the following: - Setting up your environment on Azure using the Microsoft Azure IoT Suite Remote Monitoring preconfigured solution, getting a large portion of the set-up that would be required done in one step. - Setting your device and sensors up so that it can communicate with both your computer, and Azure IoT. - Updating the device code sample to include our connection data and send it to Azure IoT to be viewed remotely.
1.2 Before Starting
1.2.1 Required Software
- Arduino IDE, version 1.6.8 (or newer) from (Earlier versions will not work with the AzureIoT library)
1.2.2 Required Hardware
- Adafruit Feather Huzzah ESP8266 kit
- Huzzah ESP8266 board
- DHT22 Sensor
- Breadboard
- M/M jumper wires
- 10k Ohm Resistor (brown, black, orange)
- A microB USB cable
- A desktop or laptop computer which can run Arduino IDE 1.6.8 or newer
1.3 Connect your device to the Temperature sensor
- Using this image as a reference, connect your Adafruit Feather Huzzah ESP8266 kit to the DHT22 Temperature sensor using the breadboard:
Note: Column on the left corresponds to sensor and on the Right to board. On the image, the board is place between 10 and 30, with the RST pin connected to row 30, and sensor between 1 and 9, with the VDD pin connected to the row 1.
- Connect the board, sensor and parts on the breadboard:
- For sensor pins, we will use the following wiring:
- For more information, see: Adafruit DHT22 sensor setup.
At the end of your work, your Adafruit Feather Huzzah ESP8266 should be connected with a working sensor.
1.4 Create a New Azure IoT Suite Remote Monitoring solution and Add Device
- Log in to Azure IoT Suite with your Microsoft account and click Create a new Solution
Note: For first time users, click here to get your Azure free trial which gives you $200 of credit to get started.
- Click the
selectbutton in the Remote Monitoring option
- Type in a solution name. For this tutorial we’ll be using “HuzzahSuite” (You will have to name it something else. Make it unique. I.E. "ContosoSample")
- Choose your subscription and desired region to deploy, then click Create Solution
- Wait for Azure to finish provisioning your IoT suite (this process may take up to 10 minutes), and then click Launch
Note: You may be asked to log back in. This is to ensure your solution has proper permissions associated with your account.
- Open the link to your IoT Suite’s “Solution Dashboard.” You may have been redirected there already.
- This opens your personal remote monitoring site at the URL <Your Azure IoT Hub suite name>.azurewebsites.net (e.g. HuzzahSuite.azurewebsites.net)
- Click Add a Device at the lower left hand corner of your screen
- Add a new custom device
- Enter your desired
device ID. In this case we’ll use “Huzzah_w_DHT22”, and then click Check ID
- If Device ID is available, go ahead and click Create
IMPORTANT NOTE: Write down your
device ID,
Device Key, and
IoT Hub Hostnameto enter into the code you’ll run on your device later
Make sure your device displays in the devices section. The device status is Pending until the device establishes a connection to the remote monitoring solution.
1.5 Configure the Arduino IDE
In this step, we will be using the Arduino IDE. If you have not downloaded the IDE, please download it from the Arduino website.
1.5.1 Add the Adafruit Feather Huzzah ESP8266 to the Arduino IDE
You will need to install the Adafruit Feather Huzzah ESP8266 board extension for the Arduino IDE. In our steps below, we will be following the same instructions as in this link, which you can also use for troubleshooting. After going through the following steps, you should have a working sample with a blinking light on your board.
Open the Arduino IDE and go to
File -> Preferences
Go to the field titled
"Additional Boards Manager URLs:" and type
Click on
Tools -> Board -> Boards Manager
esp8266, left click on the result titled
esp8266 by ESP8266 Community and click on install
After the board is installed select
Tools -> Board -> Adafruit HUZZAH ESP8266
1.5.2 Configuration settings
Set the CPU frequency to 80MHz by clicking on
Tools -> CPU Frequency -> 80MHz
Set the upload speed to 115200 by clicking on
Tools -> Upload Speed -> 115200
Set the COM port by clicking on
Tools -> Port -> COMx. If you see multiple COM ports, then you will have to experiment, in order to find the one that corresponds to your device. One way to do that is to disconnect your device, check the list of COM ports, reconnect the device and then find which port was not there before.
In order to verify that you've set the correct COM port, you can click on
Tools -> Get Board Info. If you see the message "Native serial port, can't obtain port info", then you have not selected the correct port. You can change the COM port using the step above and retry this step, until you see a message similar to:
If you run into any connection issues, unplug the board, hold the reset button, and while still holding it, plug the board back in. This will flash to board to try again.
1.5.3 Install Library Dependencies
For this project, we'll also need the following libraries:
- Adafruit DHT Unified
- DHT Sensor Library
- AzureIoTHub
- AzureIoTUtility
- AzureIoTProtocol_MQTT
- Adafruit Unified Sensor
To install these libraries, click on the
Sketch -> Include Library -> Manage Libraries.
Search for each of these libraries using the box in the upper-right to filter your search, click on the found library, and click the "Install" button.
If you have any problems while installing the libraries, you can find more instructions here.
Note: Starting on version 1.0.17,
AzureIoTHub required the
AzureIoTUtility and one of the available protocols. These samples use the
AzureIoTProtocol_MQTT, but it is prepared to work with
AzureIoTProtocol_HTTP too.
1.6 Modify the Remote Monitoring sample
- Unzip the example code, go to the
remote_monitoringdirectory and double-click the file
remote_monitoring.inoto open the project in the Arduino IDE.
- In the project, edit the
iot_configs.h, look for the following lines of code:
#define IOT_CONFIG_WIFI_SSID "<Your WiFi network SSID or name>" #define IOT_CONFIG_WIFI_PASSWORD "<Your WiFi network WPA password or WEP key>"
- Replace the placeholders with your WiFi name (SSID) and the WiFi password.
- Find the Device id, Iot Hub Hostname and Device Key that you wrote down, when you saw the following screen after adding your custom device into the Azure IoT suite:
If you cannot find this data, then you can go to your Remote Monitoring Solution in Azure IoT Suite, click on Devices and then select your device. Check the device properties section at the right part of the page for the DEVICEID, HOSTNAME and Authentication Keys (bottom right of the page). Click on "View Authentication keys" and copy "KEY 1" as your deviceKey.
- Look for the following line of code and replace the placeholders connection information (also remove the "<" and ">" when replacing the information):
#define IOT_CONFIG_CONNECTION_STRING "HostName=<host_name>.azure-devices.net;DeviceId=<device_id>;SharedAccessKey=<device_key>"
- Save with
Control-s
1.7 Build and Run Your Remote Monitoring Sample
- Build, upload and run the code using Sketch -> Upload or by clicking on the arrow button (second from the left)
- If your code is correct and all libraries was properly installed, you will receive something like the following message in the IDE.
Sketch uses 376,409 bytes (36%) of program storage space. Maximum is 1,044,464 bytes. Global variables use 50,220 bytes (61%) of dynamic memory, leaving 31,700 bytes for local variables. Maximum is 81,920 bytes.
- While the code is being downloaded, there.
Note: When first starting you will likely see a “Fetching NTP epoch time failed” error – This is normal, and it trying to sync with Azure. This can take even up to 30 seconds to find a NTP server to sync with. One it is synced, it should start transmitting from there.
1.8 View the Sensor Data from the Remote Monitoring Portal
- Once you have the sample running, visit your dashboard by visiting azureiotsuite.com and clicking “Launch” on your solution
- Make sure the “Device to View” in the upper right is set to your device
- If the demo is running, you should see the graph change as your data updates in real time!
1.9 Stop using the Azure IoT Suite
Warning: The Remote Monitoring solution provisions a set of Azure IoT Services in your Azure account. It is meant to reflect a real enterprise architecture and thus its Azure consumption is quite heavy.
To avoid unnecessary Azure consumption, you can delete, stop or downsize your Azure IoT Suite. We recommend you delete the preconfigured solution in azureiotsuite.com once you are done with your work (since it is easy to recreate).
If you want to read additional information about the Azure IoT Suite, you can go the following websites: - -
1.9.1 Delete the Azure IoT Suite
Go to, click on your existing solution (not on the "Launch" button) and then click the red button
Delete Solution in the right pane
1.9.2 Stop the Azure IoT Suite
1.9.3 Downsize the Azure IoT Suite
Alternatively, if you want to keep it up and running you can do two things to reduce consumption:
1) Visit this guide to run the solution in demo mode and reduce the Azure consumption.
2) Disable the simulated devices created with the solution (Go to Devices>>Select the device>> on the device details menu on the right, clich on Disable Device. Repeat with all the simulated devices).
1.10 Next steps
Please visit our Azure IoT Dev Center for more samples and documentation on Azure IoT.
Using Microsoft Azure IoT Services to Identify Temperature Anomalies
This tutorial describes the process of taking your Microsoft Azure IoT Starter Kit for the Adafruit Feather Huzzah ESP8266, and using it to develop a temperature and humidity reader that can communicate with the cloud using the Microsoft Azure IoT SDK.
Table of Contents
- 2.1 Tutorial Overview
- 2.2 Before Starting
- 2.3 Connect the Sensor Module to your Device
- 2.4 Create a New Microsoft Azure IoT Hub and Add Device
- 2.5 Create an Event Hub
- 2.6 Create a Storage Account for Table Storage
- 2.7 Create a Stream Analytics job to Save IoT Data in Table Storage and Raise Alerts
- 2.8 Node Application Setup
- 2.9 Add the Adafruit Feather Huzzah ESP8266 to the Arduino IDE
- 2.10 Install Library Dependencies
- 2.11 Modify the Command Center Sample
- 2.12 Build Your Command Center Sample
- 2.13 Next steps
2.1 Tutorial Overview
This tutorial has the following steps: - Provision an IoT Hub instance on Microsoft Azure and adding your device. - Prepare the device, get connected to the device, and set it up so that it can read sensor data. - Configure your Microsoft Azure IoT services by adding Event Hub, Storage Account, and Stream Analytics resources. - Prepare your local web solution for monitoring and sending commands to your device. - Update the sample code to respond to commands and include the data from our sensors, sending it to Microsoft Azure to be viewed remotely.
Here is a breakdown of the data flow: - The application running on the Adafruit Feather Huzzah ESP8266 will get temperature data from the temperature sensor and it will send them to the IoT Hub - A Stream Analytics job will read the data from IoT Hub and write them to an Azure Storage Table. Also, if an anomaly is detected, then this job will write data to an Event Hub - The Node.js application that is running on your computers will read the data from the Azure Storage Table and the Event Hub and will present them to the user
The end result will be a functional command center where you can view the history of your device's sensor data, a history of alerts, and send commands back to the device.
2.2 Before Starting
2.2.1 Required Software
- Git - For cloning the required repositories
- Node.js - For the Node application, we will go over this later.
- Arduino IDE, version 1.6.8. (Earlier versions will not work with the Azure IoT library)
- Sensor interface library from Adafruit.
2.2.2 Required Hardware
- Adafruit Feather Huzzah ESP8266 IoT kit
- Huzzah ESP8266 board
- DHT22 Sensor
- breadboard
- M/M jumper wires
- 10k Ohm Resistor (brown, black, orange)
- 2x 330 Ohm Resistor (orange, orange, brown) or 2x 560 Ohm Resistor (green, blue, brown)
- Green LED
- Red LED
- A microB USB cable
- A desktop or laptop computer which can run Arduino IDE 1.6.8
2.3 Connect the Sensor Module to your Device
- Using this image as a reference, connect your DHT22 and Adafruit Feather Huzzah ESP8266 to the breadboard
Note: Column on the left corresponds to sensor and on the Right to board. On the image, the board is place between 10 and 30 and sensor between 1 and 9. Additionally, when counting the - pins, start from the right and count in, as these do not align with the numbers indicated on the board.
Note: The resistor can change a little from one kit to another, e.g. it can be 330 Ohm (orange, orange, brown) or 560 Ohm (green, blue, brown). Both will work with success.
- Connect the board, sensor, and parts on the breadboard:
- For the pins, we will use the following wiring:
- For more information, see: Adafruit DHT22 sensor setup.
At the end of your work, your Adafruit Feather Huzzah ESP8266 should be connected with a working sensor.
2.4 Create a New Microsoft Azure IoT Hub and Add Device
- To create your Microsoft Azure IoT Hub and add a device, follow the instructions outlined in the Setup IoT Hub Microsoft Azure Iot SDK page.
- After creating your device, make note of your connection string to enter into the code you’ll run on your device later
2.5 Create an Event Hub
Event Hub is an Azure IoT publish-subscribe service that can ingest millions of events per second and stream them into multiple applications, services or devices.
- Log on to the Microsoft Azure Portal
- Click on New -> Internet of Things-> Event Hub
- Enter the following settings for the Event Hub Namespace (use a name of your choice for the event hub and the namespace):
- Name:
Your choice(we chose
Huzzah2Suite)
- Pricing Tier:
Basic
- Subscription:
Your choice
- Resource Group:
Your choice
- Location:
Your choice
- Click on Create
- Wait until the Event Hub Namespace is created, and then create an Event Hub using the following steps:
- Click on your
Huzzah2SuiteEvent Hub Namespace (or pick any other name that you used)
- Click the Add Event Hub
- Name:
huzzahEventHub
- Click on Create
- Wait until the new Event Bus is created
- Click on the Event Hubs arrow in the Overview tab (might require a few clicks, until the UI is updated)
- Select the
huzzahEventHubeventhub and go in the Configure tab in the Shared Access Policies section, add a new policy:
- Name =
readwrite
- Permissions =
Send, Listen
- Click Save at the bottom of the page, then click the Dashboard tab near the top and click on Connection Information at the bottom
- Copy down the connection string for the
readwritepolicy you created.
- From the your IoT Hub Settings (The Resource that has connected dots) on the Microsoft Azure Portal, click the Messaging blade (found in your settings), write down the Event Hub-compatible name
- Look at the Event-hub-compatible Endpoint, and write down this part: sb://thispart.servicebus.windows.net/ we will call this one the IoTHub EventHub-compatible namespace
2.6 Create a Storage Account for Table Storage
Now we will create a service to store our data in the cloud. - Log on to the Microsoft Azure Portal - In the menu, click New and select Data + Storage then Storage Account - Name:
Your choice (we chose
huzzahstorage) - Deployment model:
Classic - Performance:
Standard - Replication:
Read-access geo-redundant storage (RA-GRS) - Subscription:
Your choice - Resource Group:
Your choice - Location:
Your choice - Once the account is created, find it in the resources blade or click on the pinned tile, go to Settings, Keys, and write down the primary connection string.
2.7 Create a Stream Analytics job to Save IoT Data in Table Storage and Raise Alerts
Stream Analytics is an Azure IoT service that streams and analyzes data in the cloud. We'll use it to process data coming from your device.
- Log on to the Microsoft Azure Portal
- In the menu, click New, then click Internet of Things, and then click Stream Analytics Job
- Enter a name for the job (We chose “HuzzahStorageJob”), a preferred region, then choose your subscription. At this stage you are also offered to create a new or to use an existing resource group. Choose the resource group you created earlier.
- Once the job is created, open your Job’s blade or click on the pinned tile, and find the section titled “Job Topology” and click the Inputs tile. In the Inputs blade, click on Add
Enter the following settings:
- Input Alias =
TempSensors
- Source Type =
Data Stream
- Source =
IoT Hub
- IoT Hub =
Huzzah2Suite(use the name for the IoT Hub you create before)
- Shared Access Policy Name =
iothubowner
- Shared Access Policy Key = The
iothubownerprimary key can be found in your IoT Hub Settings -> Shared access policies
- IoT Hub Consumer Group = "" (leave it to the default empty value)
- Event serialization format =
JSON
- Encoding =
UTF-8
Back to the Stream Analytics Job blade, click on the Query tile (next to the Inputs tile). In the Query settings blade, type in the below query and click Save:
SELECT DeviceId, EventTime, MTemperature as TemperatureReading INTO TemperatureTableStorage from TempSensors WHERE DeviceId is not null and EventTime is not null SELECT DeviceId, EventTime, MTemperature as TemperatureReading INTO TemperatureAlertToEventHub FROM TempSensors WHERE MTemperature>25
Note: You can change the
25 to
0 when you're ready to generate alerts to look at. This number represents the temperature in degrees celsius to check for when creating alerts. 25 degrees celsius is 77 degrees fahrenheit.
- Back to the Stream Analytics Job blade, click on the Outputs tile and in the Outputs blade, click on Add
- Enter the following settings then click on Create:
- Output Alias =
TemperatureTableStorage
- Sink =
Table Storage
- Subscription =
Provide table settings storage manually
- Storage account =
huzzahstorage(The storage account you created earlier)
- Storage account key = (The primary key for the storage account made earlier, can be found in Settings -> Keys -> Primary Access Key)
- Table Name =
TemperatureRecords(Your choice - If the table doesn’t already exist, Local Storage will create it)
- Partition Key =
DeviceId
- Row Key =
EventTime
- Batch size =
1
- Back to the Stream Analytics Job blade, click on the Outputs tile, and in the Outputs blade, click on Add
- Enter the following settings then click on Create:
- Output Alias =
TemperatureAlertToEventHub
- Sink =
Event Hub
- Subscription =
Provide table settings storage manually
- Service Bus Namespace =
Huzzah2Suite
- Event Hub Name =
huzzaheventhub(The Event Hub you made earlier)
- Event Hub Policy Name =
readwrite
- Event Hub Policy Key =
Primary Key for readwrite Policy name(That's the one you wrote down after creating the event hub)
- Partition Key Column =
0
- Event Serialization format =
JSON
- Encoding =
UTF-8
- Format =
Line separated
- Back in the** Stream Analytics blade, start the job by clicking on the Start **button at the top
Note: Make sure to stop your Command Center jobs once you have when you take a break or finish to avoid unnecessary Azure consumption! (See: Troubleshooting)
2.8 Node Application Setup
- If you do not have it already, install Node.js and NPM.
- Windows and Mac installers can be found here:
- Ensure that you select the options to install NPM and add to your PATH.
- Linux users can use the commands:
sudo apt-get update sudo apt-get install nodejs sudo apt-get install npm
- Additionally, make sure you have cloned the project repository locally by issuing the following command in your desired directory:
git clone
- Open the
command_center_nodefolder in your command prompt (
cd <path to locally cloned repro>/command_center_node) and install the required modules by running the following:
npm install -g bower npm install bower install
Open the
config.jsonfile and replace the information with your project. See the following for instructions on how to retrieve those values.
- eventhubName:
- Open the Classic Azure Management Portal
- Open the Service Bus namespace you created earlier
- Switch to the EVENT HUBS page
- You can see and copy the name of your event hub from that page
- ehConnString:
- Click on the name of the event hub from above to open it
- Click on the "CONNECTION INFORMATION" button along the bottom.
- From there, click the button to copy the readwrite shared access policy connection string.
- deviceConnString:
- Use the information on the Manage IoT Hub to retrieve your device connection string using either the Device Explorer or iothub-explorer tools.
- iotHubConnString:
- In the Azure Portal
- Open the IoT Hub you created previously.
- Open the "Settings" blade
- Click on the "Shared access policies" setting
- Click on the "service" policy
- Copy the primary connection string for the policy
- storageAccountName:
- In the Azure Portal
- Open the classic Storage Account you created previously to copy its name
- storageAccountKey:
- Click on the name of the storage account above to open it
- Click the "Settings" button to open the Settings blade
- Click on the "Keys" setting
- Click the button next to the "PRIMARY ACCESS KEY" top copy it
- storageTableName:
- This must match the name of the table that was used in the Stream Analytics table storage output above.
- If you used the instructions above, you would have named it
TemperatureRecords
- If you named it something else, enter the name you used instead.
{ "port": "3000", "eventHubName": "event-hub-name", "ehConnString": "Endpoint=sb://name.servicebus.windows.net/;SharedAccessKeyName=readwrite;SharedAccessKey=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=", "deviceConnString": "HostName=name.azure-devices.net;DeviceId=device-id;SharedAccessKey=aaaaaaaaaaaaaaaaaaaaaa==" "iotHubConnString": "HostName=iot-hub-name.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=", "storageAcountName": "aaaaaaaaaaa", "storageAccountKey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa==", "storageTable": "TemperatureRecords" }
- Now it is time to run it! Enter the following command:
node server.js
- You should then see something similar to:
app running on client connected
- Visit the url in your browser and you will see the Node app running!
To deploy this project to the cloud using Azure, you can reference Creating a Node.js web app in Azure App Service.
Next, we will update your device so that it can interact with all the things you just created.
2.9 Add the Adafruit Feather Huzzah ESP8266 to the Arduino IDE
You will need to install the Adafruit Feather Huzzah ESP8266 board extension for the Arduino IDE:
- Follow the instructions here. There you will see how to add a URL pointing to Adafruit's repository of board extensions, how to make the Adafruit Feather Huzzah ESP8266 board selectable under the Tools menu, and how to get the Blink sketch to run.
- As we explained on the item 1.5, boards with microB connector don't have the GPIO0 button. So, in the 'Blink Test', ignore the steps to put the board in the bootload mode, and go directly to the step to upload the sketch via the IDE.
- After going through this, you should have a working sample with a blinking light on your board.
- If you run into any connection issues, unplug the board, hold the reset button, and while still holding it, plug the board back in. This will flash to board to try again.
2.10 Install Library Dependencies
For this project, we'll also need the the following libraries:
- DHT Sensor Library
- Adafruit DHT Unified
- AzureIoTHub
- AzureIoTUtility
- AzureIoTProtocol_MQTT
To install them, click on the
Sketch -> Include Library -> Manage Libraries. Search for each library using the box in the upper-right to filter your search, click on the found library, and click the "Install" button.
The Adafruit Unified Sensor library is also needed. This can be downloaded here. Instructions for manually installing a library can be found here.
2.11 Modify the Command Center sample
- Unzip the example code, and double-click the file
command_center.inoto open the project in the Arduino IDE.
- You will be prompted to creat a folder. Do this, and move the other files in the folder into the newly created child folder
- Look for the following lines of code:
static const char ssid[] = "[Your WiFi network SSID or name]"; static const char pass[] = "[Your WiFi network WPA password or WEP key]"; static const char* connectionString = "[Device Connection String]";
- Replace the placeholders with your WiFi name (SSID), WiFi password, and the device connection string you created at the beginning of this tutorial.
Save with
Control-s
In the same project, click on the
command_center.ctab to see that file.
Look for the following lines of code:
static const char DeviceId[] = "[Device Name]"; static const char connectionString[] = "[Device Connection String]";
- Replace the placeholders with your Device ID and connection string you created at the beginning of this tutorial.
- Save with
Control-s
2.12 Build Your Command Center Sample
- Build and upload the code using Sketch -> Upload.
Note: As of 1.6.8, the Arduino IDE doesn't properly show "Upload Completed", even when it succeeds.
- There should.
- Data is now being sent off at regular intervals to Microsoft Azure. When it detects something out of range, you will see the LED you’ve set up turn from green to red!
- You can click the green button (labeled "Turn on") and the red button (labeled "Turn off") in the application to toggle the green and red LEDs in your kit.
Head back to your Node application and you will have a fully functional command center, complete with a history of sensor data, alerts that display when the temperature got outside a certain range, and commands that you can send to your device remotely.
Note: Make sure to stop your Command Center jobs once you have when you finish to avoid unnecessary Azure consumption! (See: Troubleshooting)
2.13 Next steps
Please visit our Azure IoT Dev Center for more samples and documentation on Azure IoT.
Troubleshooting
Stopping Provisioned Services
-
Data is not showing up in the Node.js application
In this section we will explain how to see the data flowing from the Arduino application to the Node.js application: - Arduino application: In the Arduino IDE go to Tools -> Serial Monitor - IoT Hub: Use Device Explorer - Azure Storage Table: Use Azure Storage Explorer
更多示例由 Hector Garcia Tellado 提供
- Get Started with Microsoft Azure IoT Starter Kit - Intel Edison
- Get Started with Microsoft Azure IoT Starter Kit - SparkFun ESP8266 Thing Dev Kit (Arduino-compatible)
- Get Started with Microsoft Azure IoT Starter Kit - Adafruit Feather M0 WiFi (Arduino-compatible)
- Get Started with Microsoft Azure IoT Starter Kit - Raspberry Pi2 and Pi3 | https://azure.microsoft.com/zh-cn/resources/samples/iot-hub-c-huzzah-getstartedkit/ | CC-MAIN-2017-30 | refinedweb | 4,817 | 57.5 |
import "github.com/pingcap/tidb/store/tikv"
Package tikv provides tcp connection to kvserver.
Package tikv provides tcp connection to kvserver.
2pc.go backoff.go client.go client_batch.go coprocessor.go delete_range.go error.go interface.go kv.go lock_resolver.go mock_tikv_service.go pd_codec.go range_task.go rawkv.go region_cache.go region_request.go safepoint.go scan.go snapshot.go split_region.go test_util.go txn.go
const ( // NoJitter makes the backoff sequence strict exponential. NoJitter = 1 + iota // FullJitter applies random factors to strict exponential. FullJitter // EqualJitter is also randomized, but prevents very short sleeps. EqualJitter // DecorrJitter increases the maximum jitter based on the last random value. DecorrJitter )
Back off types.
Maximum total sleep time(in ms) for kv/cop commands.
const ( // This is almost the same as 'tikv_gc_safe_point' in the table 'mysql.tidb', // save this to pd instead of tikv, because we can't use interface of table // if the safepoint on tidb is expired. GcSavedSafePoint = "/tidb/store/gcworker/saved_safe_point" GcSafePointCacheInterval = time.Second * 100 )
Safe point constants.
ResolvedCacheSize is max number of cached txn status.
var ( ReadTimeoutMedium = 60 * time.Second // For requests that may need scan region. ReadTimeoutLong = 150 * time.Second // For requests that may need scan region multiple times. GCTimeout = 5 * time.Minute UnsafeDestroyRangeTimeout = 5 * time.Minute )
Timeout durations.
var ( ErrTiKVServerTimeout = terror.ClassTiKV.New(mysql.ErrTiKVServerTimeout, mysql.MySQLErrName[mysql.ErrTiKVServerTimeout]) ErrResolveLockTimeout = terror.ClassTiKV.New(mysql.ErrResolveLockTimeout, mysql.MySQLErrName[mysql.ErrResolveLockTimeout]) ErrPDServerTimeout = terror.ClassTiKV.New(mysql.ErrPDServerTimeout, mysql.MySQLErrName[mysql.ErrPDServerTimeout]) = terror.ClassTiKV.New(mysql.ErrRegionUnavailable, mysql.MySQLErrName[mysql.ErrRegionUnavailable]) ErrTiKVServerBusy = terror.ClassTiKV.New(mysql.ErrTiKVServerBusy, mysql.MySQLErrName[mysql.ErrTiKVServerBusy]) ErrGCTooEarly = terror.ClassTiKV.New(mysql.ErrGCTooEarly, mysql.MySQLErrName[mysql.ErrGCTooEarly]) )
MySQL error instances.
var ( // MaxRawKVScanLimit is the maximum scan limit for rawkv Scan. MaxRawKVScanLimit = 10240 // ErrMaxScanLimitExceeded is returned when the limit for rawkv Scan is to large. ErrMaxScanLimitExceeded = errors.New("limit should be less than MaxRawKVScanLimit") )
CommitMaxBackoff is max sleep time of the 'commit' command
var ( // ErrBodyMissing response body is missing error ErrBodyMissing = errors.New("response body is missing") )
MaxRecvMsgSize set max gRPC receive message size received from server. If any message size is larger than current value, an error will be reported from gRPC.
NewGCHandlerFunc creates a new GCHandler. To enable real GC, we should assign the function to `gcworker.NewGCWorker`.
Global variable set by config file.
ShuttingDown is a flag to indicate tidb-server is exiting (Ctrl+C signal receved for example). If this flag is set, tikv client should not retry on network error because tidb-server expect tikv client to exit as soon as possible.
NewBackoffFn creates a backoff func which implements exponential backoff with optional jitters. See
func NewTestTiKVStore(client Client, pdClient pd.Client, clientHijack func(Client) Client, pdClientHijack func(pd.Client) pd.Client, txnLocalLatches uint) (kv.Storage, error)
NewTestTiKVStore creates a test store with Option
func SplitRegionRanges(bo *Backoffer, cache *RegionCache, keyRanges []kv.KeyRange) ([]kv.KeyRange, error)
SplitRegionRanges get the split ranges from pd region.
Backoffer is a utility for retrying queries.
NewBackoffer creates a Backoffer with maximum sleep time(in ms).
NewNoopBackoff create a Backoffer do nothing just return error directly
Backoff sleeps a while base on the backoffType and records the error message. It returns a retryable error if total sleep time exceeds maxSleep.
BackoffWithMaxSleep sleeps a while base on the backoffType and records the error message and never sleep more than maxSleepMs for each sleep.
Clone creates a new Backoffer which keeps current Backoffer's sleep time and errors, and shares current Backoffer's context.
func (b *Backoffer) Fork() (*Backoffer, context.CancelFunc)
Fork creates a new Backoffer which keeps current Backoffer's sleep time and errors, and holds a child context of current Backoffer's context.
WithVars sets the kv.Variables to the Backoffer and return it.
type Client interface { // Close should release all data. Close() error // SendRequest sends Request. SendRequest(ctx context.Context, addr string, req *tikvrpc.Request, timeout time.Duration) (*tikvrpc.Response, error) }
Client is a client that sends RPC. It should not be used after calling Close().
NewTestRPCClient is for some external tests.
type CopClient struct { kv.RequestTypeSupportedChecker // contains filtered or unexported fields }
CopClient is coprocessor client.
Send builds the request and gets the coprocessor iterator response.
DeleteRangeTask is used to delete all keys in a range. After performing DeleteRange, it keeps how many ranges it affects and if the task was canceled or not.
func NewDeleteRangeTask(store Storage, startKey []byte, endKey []byte, concurrency int) *DeleteRangeTask
NewDeleteRangeTask creates a DeleteRangeTask. Deleting will be performed when `Execute` method is invoked. Be careful while using this API. This API doesn't keep recent MVCC versions, but will delete all versions of all keys in the range immediately. Also notice that frequent invocation to this API may cause performance problems to TiKV.
func NewNotifyDeleteRangeTask(store Storage, startKey []byte, endKey []byte, concurrency int) *DeleteRangeTask
NewNotifyDeleteRangeTask creates a task that sends delete range requests to all regions in the range, but with the flag `notifyOnly` set. TiKV will not actually delete the range after receiving request, but it will be replicated via raft. This is used to notify the involved regions before sending UnsafeDestroyRange requests.
func (t *DeleteRangeTask) CompletedRegions() int
CompletedRegions returns the number of regions that are affected by this delete range task
func (t *DeleteRangeTask) Execute(ctx context.Context) error
Execute performs the delete range operation.
Driver implements engine Driver.
Open opens or creates an TiKV storage with given path. Path example: tikv://etcd-node1:port,etcd-node2:port?cluster=1&disableGC=false
ErrDeadlock wraps *kvrpcpb.Deadlock to implement the error interface. It also marks if the deadlock is retryable.
func (d *ErrDeadlock) Error() string
EtcdBackend is used for judging a storage is a real TiKV.
EtcdSafePointKV implements SafePointKV at runtime
NewEtcdSafePointKV creates an instance of EtcdSafePointKV
func (w *EtcdSafePointKV) Get(k string) (string, error)
Get implements the Get method for SafePointKV
func (w *EtcdSafePointKV) Put(k string, v string) error
Put implements the Put method for SafePointKV
type GCHandler interface { // Start starts the GCHandler. Start() // Close closes the GCHandler. Close() }
GCHandler runs garbage collection job.
KeyLocation is the region and range that a key is located.
func (l *KeyLocation) Contains(key []byte) bool
Contains checks if key is in [StartKey, EndKey).
Lock represents a lock from tikv server.
NewLock creates a new *Lock.
LockResolver resolves locks and also caches resolved txn status.
NewLockResolver creates a LockResolver. It is exported for other pkg to use. For instance, binlog service needs to determine a transaction's commit state.
func (lr *LockResolver) BatchResolveLocks(bo *Backoffer, locks []*Lock, loc RegionVerID) (bool, error)
BatchResolveLocks resolve locks in a batch
GetTxnStatus queries tikv-server for a txn's status (commit/rollback). If the primary key is still locked, it will launch a Rollback to abort it. To avoid unnecessarily aborting too many txns, it is wiser to wait a few seconds before calling it after Prewrite.
func (lr *LockResolver) ResolveLocks(bo *Backoffer, locks []*Lock) (msBeforeTxnExpired int64, err error)
ResolveLocks tries to resolve Locks. The resolving process is in 3 steps: 1) Use the `lockTTL` to pick up all expired locks. Only locks that are too
old are considered orphan locks and will be handled later. If all locks are expired then all locks will be resolved so the returned `ok` will be true, otherwise caller should sleep a while before retry.
2) For each lock, query the primary key to get txn(which left the lock)'s
commit status.
3) Send `ResolveLock` cmd to the lock's region to resolve all locks belong to
the same transaction.
MockSafePointKV implements SafePointKV at mock test
func NewMockSafePointKV() *MockSafePointKV
NewMockSafePointKV creates an instance of MockSafePointKV
func (w *MockSafePointKV) Get(k string) (string, error)
Get implements the Get method for SafePointKV
func (w *MockSafePointKV) Put(k string, v string) error
Put implements the Put method for SafePointKV
type RPCContext struct { Region RegionVerID Meta *metapb.Region Peer *metapb.Peer PeerIdx int Store *Store Addr string }
RPCContext contains data that is needed to send RPC to a region.
func (c *RPCContext) GetStoreID() uint64
GetStoreID returns StoreID.
func (c *RPCContext) String() string
RangeTaskHandler is the type of functions that processes a task of a key range. The function should calculate Regions that succeeded or failed to the task. Returning error from the handler means the error caused the whole task should be stopped.
RangeTaskRunner splits a range into many ranges to process concurrently, and convenient to send requests to all regions in the range. Because of merging and splitting, it's possible that multiple requests for disjoint ranges are sent to the same region.
func NewRangeTaskRunner( name string, store Storage, concurrency int, handler RangeTaskHandler, ) *RangeTaskRunner
NewRangeTaskRunner creates a RangeTaskRunner.
`requestCreator` is the function used to create RPC request according to the given range. `responseHandler` is the function to process responses of errors. If `responseHandler` returns error, the whole job will be canceled.
func (s *RangeTaskRunner) CompletedRegions() int
CompletedRegions returns how many regions has been sent requests.
func (s *RangeTaskRunner) FailedRegions() int
FailedRegions returns how many regions has failed to do the task.
RunOnRange runs the task on the given range. Empty startKey or endKey means unbounded.
func (s *RangeTaskRunner) SetRegionsPerTask(regionsPerTask int)
SetRegionsPerTask sets how many regions is in a divided task. Since regions may split and merge, it's possible that a sub task contains not exactly specified number of regions.
func (s *RangeTaskRunner) SetStatLogInterval(interval time.Duration)
SetStatLogInterval sets the time interval to log the stats.
RangeTaskStat is used to count Regions that completed or failed to do the task.
RawKVClient is a client of TiKV server which is used as a key-value storage, only GET/PUT/DELETE commands are supported.
NewRawKVClient creates a client with PD cluster addrs.
func (c *RawKVClient) BatchDelete(keys [][]byte) error
BatchDelete deletes key-value pairs from TiKV
func (c *RawKVClient) BatchGet(keys [][]byte) ([][]byte, error)
BatchGet queries values with the keys.
func (c *RawKVClient) BatchPut(keys, values [][]byte) error
BatchPut stores key-value pairs to TiKV.
func (c *RawKVClient) Close() error
Close closes the client.
func (c *RawKVClient) ClusterID() uint64
ClusterID returns the TiKV cluster ID.
func (c *RawKVClient) Delete(key []byte) error
Delete deletes a key-value pair from TiKV.
func (c *RawKVClient) DeleteRange(startKey []byte, endKey []byte) error
DeleteRange deletes all key-value pairs in a range from TiKV
func (c *RawKVClient) Get(key []byte) ([]byte, error)
Get queries value with the key. When the key does not exist, it returns `nil, nil`.
func (c *RawKVClient) Put(key, value []byte) error
Put stores a key-value pair to TiKV.
func (c *RawKVClient) ReverseScan(startKey, endKey []byte, limit int) (keys [][]byte, values [][]byte, err error)
ReverseScan queries continuous kv pairs in range [endKey, startKey), up to limit pairs. Direction is different from Scan, upper to lower. If endKey is empty, it means unbounded. If you want to include the startKey or exclude the endKey, append a '\0' to the key. For example, to scan (endKey, startKey], you can write: `ReverseScan(append(startKey, '\0'), append(endKey, '\0'), limit)`. It doesn't support Scanning from "", because locating the last Region is not yet implemented.
func (c *RawKVClient) Scan(startKey, endKey []byte, limit int) (keys [][]byte, values [][]byte, err error)
Scan queries continuous kv pairs in range [startKey, endKey), up to limit pairs. If endKey is empty, it means unbounded. If you want to exclude the startKey or include the endKey, append a '\0' to the key. For example, to scan (startKey, endKey], you can write: `Scan(append(startKey, '\0'), append(endKey, '\0'), limit)`.
Region presents kv region
Contains checks whether the key is in the region, for the maximum region endKey is empty. startKey <= key < endKey.
ContainsByEnd check the region contains the greatest key that is less than key. for the maximum region endKey is empty. startKey < key <= endKey.
EndKey returns EndKey.
func (r *Region) FollowerStorePeer(rs *RegionStore, followerStoreSeed uint32) (store *Store, peer *metapb.Peer, idx int)
FollowerStorePeer returns a follower store with follower peer.
GetID returns id.
GetLeaderID returns leader region ID.
GetLeaderStoreID returns the store ID of the leader region.
GetMeta returns region meta.
StartKey returns StartKey.
func (r *Region) VerID() RegionVerID
VerID returns the Region's RegionVerID.
WorkStorePeer returns current work store with work peer.
RegionCache caches Regions loaded from PD.
func NewRegionCache(pdClient pd.Client) *RegionCache
NewRegionCache creates a RegionCache.
func (c *RegionCache) BatchLoadRegionsFromKey(bo *Backoffer, startKey []byte, count int) ([]byte, error)
BatchLoadRegionsFromKey loads at most given numbers of regions to the RegionCache, from the given startKey. Returns the endKey of the last loaded region. If some of the regions has no leader, their entries in RegionCache will not be updated.
func (c *RegionCache) Close()
Close releases region cache's resource.
func (c *RegionCache) GetRPCContext(bo *Backoffer, id RegionVerID, replicaRead kv.ReplicaReadType, followerStoreSeed uint32) (*RPCContext, error)
GetRPCContext returns RPCContext for a region. If it returns nil, the region must be out of date and already dropped from cache.
func (c *RegionCache) GroupKeysByRegion(bo *Backoffer, keys [][]byte, filter func(key, regionStartKey []byte) bool) (map[RegionVerID][][]byte, RegionVerID, error)
GroupKeysByRegion separates keys into groups by their belonging Regions. Specially it also returns the first key's region which may be used as the 'PrimaryLockKey' and should be committed ahead of others. filter is used to filter some unwanted keys.
func (c *RegionCache) InvalidateCachedRegion(id RegionVerID)
InvalidateCachedRegion removes a cached Region.
func (c *RegionCache) ListRegionIDsInKeyRange(bo *Backoffer, startKey, endKey []byte) (regionIDs []uint64, err error)
ListRegionIDsInKeyRange lists ids of regions in [start_key,end_key].
func (c *RegionCache) LoadRegionsInKeyRange(bo *Backoffer, startKey, endKey []byte) (regions []*Region, err error)
LoadRegionsInKeyRange lists ids of regions in [start_key,end_key].
func (c *RegionCache) LocateEndKey(bo *Backoffer, key []byte) (*KeyLocation, error)
LocateEndKey searches for the region and range that the key is located. Unlike LocateKey, start key of a region is exclusive and end key is inclusive.
func (c *RegionCache) LocateKey(bo *Backoffer, key []byte) (*KeyLocation, error)
LocateKey searches for the region and range that the key is located.
func (c *RegionCache) LocateRegionByID(bo *Backoffer, regionID uint64) (*KeyLocation, error)
LocateRegionByID searches for the region with ID.
func (c *RegionCache) OnRegionEpochNotMatch(bo *Backoffer, ctx *RPCContext, currentRegions []*metapb.Region) error
OnRegionEpochNotMatch removes the old region and inserts new regions into the cache.
func (c *RegionCache) OnSendFail(bo *Backoffer, ctx *RPCContext, scheduleReload bool, err error)
OnSendFail handles send request fail logic.
func (c *RegionCache) PDClient() pd.Client
PDClient returns the pd.Client in RegionCache.
func (c *RegionCache) UpdateLeader(regionID RegionVerID, leaderStoreID uint64, currentPeerIdx int)
UpdateLeader update some region cache with newer leader info.
RegionRequestSender sends KV/Cop requests to tikv server. It handles network errors and some region errors internally.
Typically, a KV/Cop request is bind to a region, all keys that are involved in the request should be located in the region. The sending process begins with looking for the address of leader store's address of the target region from cache, and the request is then sent to the destination tikv server over TCP connection. If region is updated, can be caused by leader transfer, region split, region merge, or region balance, tikv server may not able to process request and send back a RegionError. RegionRequestSender takes care of errors that does not relevant to region range, such as 'I/O timeout', 'NotLeader', and 'ServerIsBusy'. For other errors, since region range have changed, the request may need to split, so we simply return the error to caller.
func NewRegionRequestSender(regionCache *RegionCache, client Client) *RegionRequestSender
NewRegionRequestSender creates a new sender.
func (s *RegionRequestSender) SendReq(bo *Backoffer, req *tikvrpc.Request, regionID RegionVerID, timeout time.Duration) (*tikvrpc.Response, error)
SendReq sends a request to tikv server.
func (s *RegionRequestSender) SendReqCtx(bo *Backoffer, req *tikvrpc.Request, regionID RegionVerID, timeout time.Duration) (*tikvrpc.Response, *RPCContext, error)
SendReqCtx sends a request to tikv server and return response and RPCCtx of this RPC.
RegionStore represents region stores info it will be store as unsafe.Pointer and be load at once
RegionVerID is a unique ID that can identify a Region at a specific version.
func (r *RegionVerID) GetID() uint64
GetID returns the id of the region
SafePointKV is used for a seamingless integration for mockTest and runtime.
Scanner support tikv scan
Close close iterator.
Key return key.
Next return next element.
Valid return valid.
Value return value.
type Storage interface { kv.Storage // GetRegionCache gets the RegionCache. GetRegionCache() *RegionCache // SendReq sends a request to TiKV. SendReq(bo *Backoffer, req *tikvrpc.Request, regionID RegionVerID, timeout time.Duration) (*tikvrpc.Response, error) // GetLockResolver gets the LockResolver. GetLockResolver() *LockResolver // GetSafePointKV gets the SafePointKV. GetSafePointKV() SafePointKV // UpdateSPCache updates the cache of safe point. UpdateSPCache(cachedSP uint64, cachedTime time.Time) // GetGCHandler gets the GCHandler. GetGCHandler() GCHandler // SetOracle sets the Oracle. SetOracle(oracle oracle.Oracle) // SetTiKVClient sets the TiKV client. SetTiKVClient(client Client) // GetTiKVClient gets the TiKV client. GetTiKVClient() Client // Closed returns the closed channel. Closed() <-chan struct{} }
Storage represent the kv.Storage runs on TiKV.
Store contains a kv process's address.
TxnStatus represents a txn's final status. It should be Lock or Commit or Rollback.
CommitTS returns the txn's commitTS. It is valid iff `IsCommitted` is true.
IsCommitted returns true if the txn's final status is Commit.
Package tikv imports 62 packages (graph) and is imported by 73 packages. Updated 2019-09-12. Refresh now. Tools for package owners. | https://godoc.org/github.com/pingcap/tidb/store/tikv | CC-MAIN-2019-39 | refinedweb | 2,846 | 51.55 |
Grinder
Dart workflows, automated.
Grinder consists of a library to define project tasks (e.g. test, build, doc), and a command-line tool to run them.
Getting Started
To start using
grinder, add it to your dev_dependencies.
Defining Tasks
Tasks are defined entirely by Dart code allowing you to take advantage of
the whole Dart ecosystem to write and debug them. Task definitions reside
in a
tool/grind.dart script. To create a simple grinder script, run:
pub run grinder:init
In general, grinder scripts look something like this:
import 'package:grinder/grinder.dart'; main(args) => grind(args); @DefaultTask('Build the project.') build() { log("Building..."); } @Task('Test stuff.') @Depends(build) test() { new PubApp.local('test').run([]); } @Task('Generate docs.') doc() { log("Generating docs..."); } @Task('Deploy built app.') @Depends(build, test, doc) deploy() { ... }
Any task dependencies (see
@Depends above), are run before the dependent task.
Grinder contains a variety of convenience APIs for common task definitions, such
as
PubApp referenced above. See the
API Documentation for
full details.
Running Tasks
First install the
grind executable:
pub global activate grinder
then use it to run desired tasks:
grind test grind build doc
or to run a default task (see
@DefaultTask above):
grind
or to display a list of available tasks and their dependencies:
grind -h
or to tab-complete your tasks (thanks to unscripted):
grind --completion install . ~/.bashrc grind [TAB][TAB] build test doc grind b[TAB] grind build
You can also bypass installing
grind and instead use. | https://www.dartdocs.org/documentation/grinder/0.8.0+3/index.html | CC-MAIN-2017-47 | refinedweb | 246 | 67.45 |
Just a quick post today, I had some time free this weekend and figured I'd take a crack at an old classic: "Conway's Game of Life".
This is an interesting puzzle because it centers around context-based computations, each cell determines whether it lives or dies in the next generation based on its nearby neighbours. This is typically considered one of the trickier things to do in a functional language and solutions often end up being a bit clunky at best. I think clunkiness usually results when attempting to port a solution from an imperative language over to a functional language. To do so you need to figure out some way to iterate over your grid in 2 dimensions at once doing complicated indexing to compute your neighbours and attempting to store your results somewhere as you go. It definitely can be done, you can fake loops using folds and traversable, but I feel like there are better approaches. Allow me to present my take on it.
If you like to load up code and follow along you can find the source here!
We'll be using some pretty standard language extensions, and we'll be using Representable and Comonads, so let's import a few things to get started:
{-# language GeneralizedNewtypeDeriving #-} {-# language TypeFamilies #-} module Conway where import Data.Functor.Compose (Compose(..)) import qualified Data.Vector as V import Data.Bool (bool) import Data.Distributive (Distributive(..)) import Data.Functor.Rep (Representable(..), distributeRep) import Data.Functor.Identity (Identity(..)) import Control.Arrow ((***)) import Control.Comonad.Representable.Store (Store(..), StoreT(..), store, experiment) import Control.Comonad (Comonad(..))
Conway's game of life runs on a grid, so we'll need to think up some way to represent that. We'll need to be able to index into that grid and be able to compute neighbours of a given location, so we can let that guide our representation.
I've often seen people try to represent grids in Haskell as List Zippers generalized to higher dimensions, i.e. if we have a structure like
data Zipper a = Zipper [a] a [a], you might try representing a grid as
Zipper (Zipper a).
While this is a totally valid representation, indexing into it and defining comonad's
extend becomes prohibitively difficult to reason about. I propose we try something a little different by extracting the 'index' from the data structure and holding them together side by side. We'll represent our grid as a Vector of Vectors just as you'd expect, but then we'll pair that with a set of
(x, y) coordinates and set up some indexing logic to take care of our Comonad instance for us!
If your Category Theory senses are tingling you may recognize this as the Store Comonad.
Store is typically represented as a tuple of
(s -> a, s). This means that you have some index type
s and you know how to look up an
a from it. We can model our grid as
(Vector (Vector a), (Int, Int)) then our
s -> a is simply a partially applied Vector lookup! I tried setting this up, but the default Store comonad does no optimization or memoization over the underling function so for each progressive step in Conway's game of life it had to compute all previous steps again! That's clearly pretty inefficient, we can do better!
Enter
Control.Comonad.Representable.Store! As we just noticed, a Store is just an indexing function alongside an index, since Representable Functors are indexable by nature, they make a great companion for the Store comonad. Now instead of partially applying our index function we can actually just keep the Representable functor around and do operations over that, so the Store is going to look something like this:
(Vector (Vector a), (Int, Int)).
Unfortunately there isn't a Representable instance defined for Vectors (since they can vary in size), so we'll need to take care of that first. For simplicity we'll deal with a fixed grid-size of
20x20, meaning we can enforce that each vector is of exactly length 20 which lets us write a representable instance for it!. We'll wrap the Vectors in a
VBounded newtype to keep things straight:
newtype VBounded a = VBounded (V.Vector a) deriving (Eq, Show, Functor, Foldable) instance Distributive VBounded where distribute = distributeRep gridSize :: Int gridSize = 20 instance Representable VBounded where type Rep VBounded = Int index (VBounded v) i = v V.! (i `mod` gridSize) tabulate desc = VBounded $ V.generate gridSize desc
There's the heavy lifting done! Notice that in the Representable instance for VBounded we're doing pac-man 'wrap-around' logic by taking the modulus of indices by grid size before indexing.
Now let's wrap it up in a Store, we're using
store provided by
Control.ComonadRepresentable.Store takes a tabulation function and a starting index and builds up a representable instace for us. For our starting position we'll take a list of coordinates which are 'alive'. That means that our tabulation function can just compute whether the index it's passed is part of the 'living' list!
type Grid a = Store (Compose VBounded VBounded) a type Coord = (Int, Int) mkGrid :: [Coord] -> Grid Bool mkGrid xs = store lookup (0, 0) where lookup crd = crd `elem` xs
Now for the meat and potatoes, we need to compute the successive iterations of the grid over time. We may want to switch the set of life rules later, so let's make it generic. We need to know the neighbours of each cell in order to know how it will change, which means we need to somehow get each cell, find its neighbours, compute its liveness, then slot that into the grid as the next iteration. That sounds like a lot of work! If we think about it though, contextual computations are a comonad's specialty! Our Representable Store is a comonad, which means it implements
extend :: (Grid a -> b) -> Grid a -> Grid b. Each Grid passed to the function is focused on one of the slots in the grid, and whatever the function returns will be put into that slot! This makes it pretty easy to write our rule!
type Rule = Grid Bool -> Bool -- Offsets for the neighbouring 8 tiles, avoiding (0, 0) which is the cell itself neighbourCoords :: [(Int, Int)] neighbourCoords = [(x, y) | x <- [-1, 0, 1], y <- [-1, 0, 1], (x, y) /= (0, 0)] basicRule :: Rule basicRule g = (alive && numNeighboursAlive `elem` [2, 3]) || (not alive && numNeighboursAlive == 3) where alive = extract g addCoords (x, y) (x', y') = (x + x', y + y') neighbours = experiment (\s -> addCoords s <$> neighbourCoords) g numNeighboursAlive = length (filter id neighbours) step :: Rule -> Grid Bool -> Grid Bool step = extend
Two things here, we've defined
step = extend which we can partially apply with a rule for our game, turning it into just
Grid Bool -> Grid Bool which is perfect for iterating through cycles! The other interesting thing is the use of
experiment which is provided by the
ComonadStore typeclass. Here's the generalized signature alongside our specialized version:
experiment :: (Functor f, ComonadStore s w) => (s -> f s) -> w a -> f a experiment :: (Coord -> [Coord]) -> Grid a -> [a]
Experiment uses a function which turns an index into a functor of indexes, then runs it on the index in a store and extracts a value for each index using fmap to replace each index with its value from the store! A bit confusing perhaps, but it fits our use case perfectly!
Now we need a way to render our board to text!
render :: Grid Bool -> String render (StoreT (Identity (Compose g)) _) = foldMap ((++ "\n") . foldMap (bool "." "#")) g
First we're unpacking the underlying
VBounded (VBounded a), then we convert each bool to a representative string, fold those strings into lines, then fold those lines into a single string by packing newlines in between.
We cleverly defined
mkGrid earlier to take a list of coords which were alive to define a board; if we make up some interesting combinators we can make a little DSL for setting up a starting grid!
at :: [Coord] -> Coord -> [Coord] at xs (x, y) = fmap ((+x) *** (+y)) xs glider, blinker, beacon :: [Coord] glider = [(1, 0), (2, 1), (0, 2), (1, 2), (2, 2)] blinker = [(0, 0), (1, 0), (2, 0)] beacon = [(0, 0), (1, 0), (0, 1), (3, 2), (2, 3), (3, 3)] start :: Grid Bool start = mkGrid $ glider `at` (0, 0) ++ beacon `at` (15, 5) ++ blinker `at` (16, 4)
That's pretty slick if you ask me!
It's not terribly important, but here's the actual game loop if you're interested:
import Conway import Control.Concurrent tickTime :: Int tickTime = 200000 main :: IO () main = loop (step basicRule) start loop :: (Grid Bool -> Grid Bool) -> Grid Bool -> IO () loop stepper g = do putStr "\ESC[2J" -- Clear terminal screen putStrLn (render g) threadDelay tickTime loop stepper (stepper g)
That's about it, hope you found something interesting! | https://chrispenner.ca/posts/conways-game-of-life | CC-MAIN-2018-30 | refinedweb | 1,483 | 55.88 |
Testing Groovy Scripts
February 24, 2011 8 Comments
I often start Groovy development with scripts rather than classes. Scripts are quick and easy, both to write and to run, and the feeling of having only a few lines of code makes me more willing to experiment. Most of my scripts eventually turn into classes, but once in a while, either for convenience or as demos, they stay the way they are.
This happens a lot while I’m working on my book*. I often generate little scripts that illustrate one point or another, and most of them aren’t worth converting into classes.
(*What book is that, you say? Why, Making Java Groovy, which shows you how to add Groovy to Java to make your development tasks easier. It’s available now from the Manning Early Access Program at)
While I’m not sure I practice true Test Driven Development (TDD), I know I practice GDD. That’s Guilt Driven Development, which means if I write anything significant that isn’t tested I feel guilty about it, so I then write the tests. In this post I’ll show how I now write tests for my Groovy scripts.
Before I do so, however, I should acknowledge the assistance of the indefatigable Hamlet D’Arcy on the Groovy Users email list. He blogged about a similar issue back in 2006 (!). Of course, he was dealing with straight Java back then and trying to manage standard error.
There are two features I need to use:
- The
groovy.lang.GroovyShelland
groovy.lang.Bindingclasses, and
- Overriding
System.outto capture printed output
I use a
GroovyShell to execute the scripts, and a
Binding to manage input and output variables, if any. To handle printed output, I redirect standard output to a
ByteArrayOutputStream and then check the results.
To illustrate, here are three extremely powerful scripts. The first is the classic “Hello, World!” script in Groovy. I stored it in a file called
hello_world.groovy.
println 'Hello, World!'
Second, here is a script that contains an
assert in it, in a file I called
script_with_assert.groovy.
def ok = true assert ok
I used a local variable, called
ok, in that script, mostly to contrast it with a binding variable. Speaking of which, here’s my super duper script that has a binding variable in it, stored in a file called
script_with_variable.groovy.
package mjg.scripts ok
Recall from the fantastic book Groovy in Action* (even after all these years and language changes, I still find valuable information in there) that if a variable in a script is not declared, then it can be set and retrieved via an instance of
groovy.lang.Binding.
(*Yeah, I linked to the second edition, even though I’m still using the first edition on a regular basis. That’s still my all-time favorite technical book, so I don’t mind recommending the new version.)
With all that in mind, here’s my JUnit 4 test, written in Groovy for convenience.
package mjg.scripts import static org.junit.Assert.* import org.junit.After; import org.junit.Before; import org.junit.Test; class ScriptTests { GroovyShell shell Binding binding PrintStream orig ByteArrayOutputStream out @Before void setUp() { orig = System.out out = new ByteArrayOutputStream() System.setOut(new PrintStream(out)) binding = new Binding() shell = new GroovyShell(binding) } @After void tearDown() { System.setOut(orig) } @Test void testScriptWithAssert() { shell.evaluate(new File("src/mjg/scripts/script_with_assert.groovy")) } @Test void testScriptWithTrueVariable() { binding.ok = true shell.evaluate(new File("src/mjg/scripts/script_with_variable.groovy")) assertTrue shell.ok } @Test void testScriptWithFalseVariable() { binding.ok = false shell.evaluate(new File("src/mjg/scripts/script_with_variable.groovy")) assertFalse shell.ok } @Test void testHelloWorld() { shell.evaluate(new File("src/mjg/scripts/hello_world.groovy")) assertEquals "Hello, World!", out.toString().trim() } }
Actually, all my scripts (and the test class) are in a package called
mjg.scripts, where
mjg stands for Making Java Groovy, of course.
I made the
GroovyShell and the
Binding instances attributes so I could reuse them. It turns out that by keeping a reference to the
Binding, I can still set and get variables using it even though I’ve already instantiated by Groovy shell around it. That’s helpful.
In the set up method (annotated with
@Before), I save the current output stream into an attribute so I can restore it later in the tear down method (annotated with
@After). That’s not really necessary here, but it seems like a good practice in general.
I’m using a
ByteArrayOutputStream to hold the printed data in memory. The
System.setOut method requires a
PrintStream as an argument, so I wrapped the byte stream inside one.
The first test,
testScriptWithAssert, finds the proper file and executes it. That script has the line
assert ok in it, after setting the local variable
ok to
true. If I go into the script and change
ok to
false, the test fails. This tells me two things:
- If my scripts are full of
assertstatements, I can run them as part of a normal build and failures will be reported in the usual way.
- If an
assertfails, there isn’t much I can do to prepare for it in my tests. I can’t, for example, wrap the call inside an
assertFalsecall. The failure happens before I get back, for one thing.
I basically have to hope that any
assert statements in my scripts always succeed, or my tests will fail. Arguably that’s what I want anyway.
The next two tests,
testScriptWithTrueVariable and
testScriptWithFalseVariable, set the
ok variable from the binding, then run the script. The script in question just returns the variable. I check the binding variable at the end of each script, just to prove that I was able to set it properly with the binding.
Finally, I test the “Hello, World!” script. By redirecting standard out to the byte stream, I’m able to capture the print output in a variable. I then invoke the
toString method to get the value in the buffer. The
trim call is added to handle any whitespace associated with carriage returns, line feeds, etc.
In his blog post, Hamlet used an encoding as the argument to his
toString call, claiming that otherwise the output would be different on different platforms. I decided to let Groovy worry about that, so hopefully I won’t get burned by it later.
That’s all there is to it. Now, whenever I add Groovy scripts to a chapter of my book, I make sure to add a test class to check them as well. So far that seems to be working just fine.
Any comments, especially about errors or omissions, are of course welcome. For those who have already purchased the book, (1) you totally rock, and (2) a new chapter will be added to the MEAP early next week, on using Groovy with SOAP-based web services. I’ll blog about that when the new chapter appears.
Note: the source code for this project, including a Gradle build file, is located in my TestingGroovyScripts repository at GitHub.
Pingback: Tweets that mention Testing Groovy Scripts « Stuff I’ve learned recently… -- Topsy.com
Actually, instead of redirecting System.out, you should set the “out” variable in the binding, which is used by printle. So you could avoid encoding issues, avoid redirecting streams, by doing something like this:
def content = new StringWriter()
binding.out = new PrintWriter(content)
println “hello”
assert content.toString() == “hello\n”
You know, that’s why I blog about these things. It’s only partly to share what I’ve learned. More importantly, it’s to give people like you an opportunity to show me what I didn’t know in the first place. 🙂
Thanks for this. I’ll definitely revise my tests to match this approach. is a simple example using GINT to test groovy scripts.
FYI, the “ok” is not appearing in the script_with_variable.groovy code. Actually, it looks like it shows up for a split second, and then the code formatting wipes it out so it’s all empty. At least it does in Chrome and Opera.
Also, could you post an updated Test file, just so I’m sure I followed Laforge’s advice properly? Thanks!!
That’s weird about the ok vanishing in the blog post. I’ll try adding a comment and see if that helps.
The test case at GitHub is already updated to use Guillaume’s approach. See the code at . Even if you’re not a git user, you can browse the code online. I made the changes he suggested right away. When Guillaume Laforge tells me something, I listen. 🙂
The ok is now ok 🙂
I tried that StringWriter approach myself, in my hellow_world.groovy script I typed
println "hello world"two times. But I wasn’t getting a good assert comparison. However, I changed the code to
print "hello world\n"twice, and everything asserted perfectly.
In other words, this assert line
assertEquals response.toString().trim(), 'hello world\nhello world\n'works with two print’s in the script, but not two println’s.
Any ideas what I’m doing wrong?
Pingback: Confluence: Technology | https://kousenit.org/2011/02/24/testing-groovy-scripts/ | CC-MAIN-2019-22 | refinedweb | 1,522 | 75.1 |
¤ Home » Programming » C Tutorial » Pointers in C - Part 3 of 9
Similar to a one dimensional integer array, the name of a character array or string holds the address of the starting element. However, unlike the integer array, a character array is always terminated by a null (\0) terminator. Thus a character pointer can directly be assigned with a string constant. For example, consider the following initialization:
Such a statement however, can only appear outside main(). To incorporate the same inside the main() function, the storage class static should be used as a prefix to the previous statement.
Since, city_name is a pointer to a character, it can be incremented or decremented to traverse along the string. But it is always a better practice to retain the starting address of the string, because losing that may create difficulty in accessing the complete string. You may use a second pointer to traverse the string.
The following programs illustrate usage of pointers for string manipulation:
#include <stdio.h> main() { char string[80], *ptr; ptr = string; printf("Enter the string to find it's length\n"); /* Read the string */ while((*ptr++ = getchar()) != '\n'); * --ptr = '\0'; printf("\n String is: %s\n", string); printf("It's length is: %d\n", (ptr - string)); }
#include <stdio.h> #include <malloc.h> main() { /* s1, s2 and s3 are pointers to characters */ char *s1, *s2, *s3, c; int i, j, len = 81; /* allocate memory */ s1 = (char *) malloc(len * sizeof(char)); s2 = (char *) malloc(len * sizeof(char)); s3 = (char *) malloc((2 * len - 1) * sizeof(char)); printf("Enter string 1 (length should not exceed 80 chars)\n"); gets(s1); printf("String entered is: %s\n", s1); printf("\nEnter string 2 (length should not exceed 80 chars)\n"); gets(s2); printf("String entered is: %s\n", s2); i = 0; while((c = *(s1 + i)) != '\0') { *(s3 + i) = c; i++; } j = 0; while((c = *(s2 + j)) != '\0') { *(s3 + i + j) = c; j++; } *(s3 + i + j) = '\0'; printf("\nThe Concatenated string is: %s\n", s3); }
State what the following C function will do.
void fun(char *s, char *t) { while((*s++ = *t++) != '\0'); }
Pointers in C - Part 1 of 9
Pointers in C - Part 2 of 9
Pointers in C - Part. | http://www.how2lab.com/programming/c/pointer3.php | CC-MAIN-2018-47 | refinedweb | 366 | 60.14 |
28 Sep 2020 07:11 AM
Hello,
I am completely new with Dynatrace environment and am still struggling with some concepts.
I am using OpenShift 4.5 to deploy Dynatrace Oneagent, using Dynatrace operator. Everything is running as intended, but what I do not understand is why are so many dependencies set up on underlying node (e.g. certificates, there are also quite some binaries set under `/opt/dynatrace/oneagent/agent/bin`)? Shouldn't those be part of image or in case of e.g. certificates mounted via configMap/secret?
Reason why I am asking this is since the idea of running OpenShift/Kubernetes on CoreOS type of OS is that there no dependencies set on underlying host and I am worries this might interfere with update process of OpenShift 4 platform.
Thank you and best regards,
Bostjan
Solved! Go to Solution.
28 Sep 2020 11:00 PM
Hi @Bostjan B.,
I assume you have deployed the OneAgent operator and it deployed the OneAgent via container on the nodes - probably the most common way on OpenShift. Files are put on the node to be able to inject code modules into other processes running in containers and on the host itself.
I'm not sure about your question regarding certificates, as they are not involved in the deployment of the OneAgent itself, but operator uses https connection to the Dynatrace API (either to the cluster or to the ActiveGate) to fetch the installers.
If the question stands for why there are some certificate filtes in the /opt/oneagent directories, then it's because the same OneAgent is also used for non-kubernetes platforms.
There are also more deployment strategies that are available with OneAgent Operator 0.8.0 such as automated runtime injection using admission controllers.
See more here:
Julius
29 Sep 2020 12:36 AM
Hello @Julius L.
thank you very much for provided information. That means that if I use default deployment strategy (using Oneagent CRD), pods created by that DaemonSet trigger fetching of those modules/wrappers so they are available for processes running on nodes right? And are then Oneagent pods responsible only to keep those modules up to date or do they also orchestrate whole Dynatrace collection logic on underlying host?
I guess if I do not need host monitoring, I could use OneagentAPM then, which would run just as sidecar and would not touch host's filesystem right?
Maybe one more subquestion - do you know what Red Hat stance on this is? Since as far as I know, there should be no changes to underlying host unless it is done via image/MachineConfigs.
Best regards, Bostjan
29 Sep 2020 04:20 AM
For the 'default' strategy - the OneAgent DaemonSet injects into your application pods, and also has access to metrics on the host. The Operator is what keeps the DaemonSet up to date. The /opt directory is on a shared volume so that each pod can use the same binaries without having to download / install them each and every time.
If you do not care about host monitoring, then the OneAgentAPM will work as you say, without the shared volume, though there is this kubectl apply my-app.yml peformance hit as described above, since the agents must be unzipped and installed for each pod.
Red Hat is one of our largest partners. We work with them, jointly, on both technical and sales opportunities, and collaborate closely with their engineering teams. Their stance is that monitoring is critical and there are always trade-offs. If you want host metrics, you need access to the host.
We are exploring alternative ways of mounting volumes across pods. We are also aware of some custom configurations at a few of our larger customers who are isolating these mounts by namespace using either their own, or some third-party solutions.
07 Oct 2020 12:00 AM
Thank you very much for info and sorry for late reply.
Maybe just a follow-up question regarding OneAgent DaemonSet - what do you mean with injecting into application pods? I went through docs and I still have problem fully understanding how everything works. This is what I currently have:
What I am missing is:
14 Oct 2020 02:46 PM
Hi @Bostjan B.,
How are applications accessing `/opt/dynatrace` on underlying host? Since pods require permissions to mount `hostPath`. I also checked some pods and at least in configuration, they do not mount that
It's on the host. Injecting into applications is performed by the host by preloading a library to each process. Processes in a container are still processes on the host, just running in a separate cgroup.
How to mark application for monitoring? Or is this done automatically as soon as you start DaemonSet and this is configured on Dynatrace side?
Not sure what you mean by that. As soon as OneAgent is injected into your processes, instrumentation happens and tracing and metrics are collected.
15 Oct 2020 02:21 AM
Hello @Julius L.,
ah ok, that makes sense. I was not sure how libraries are injected into application, now I understand.
Regarding second question, it was more on the side how is it specified to which application libraries are injected. As far as I understand, this is then done for all started pods, including platform pods (e.g. etcd container).
15 Oct 2020 02:47 AM
Exactly. For each process started on the host. Depending on the technology used in the process, the library then chooses the right instrumentation means (Java/NodeJS/PHP... ). This is a key differentiator from other deep monitoring tools doing instrumentation. | https://community.dynatrace.com/t5/Dynatrace-Open-Q-A/Why-are-Dynatrace-Oneagent-dependencies-installed-on-OpenShift/td-p/117267 | CC-MAIN-2021-25 | refinedweb | 935 | 63.9 |
Im trying to scrape the response to this website using a pre-filled zip:
zip who (i.e. the zip code is already filled in.) I tried to do this using the scrapy shell as follows
scrapy shell
import requests
import lxml.html as lh
url = ''
form_data = {
'zip': '77098'
}
response = requests.post(url, data=form_data)
tree = lh.document_fromstring(response.content)
tree.xpath('//td[@class="keysplit"]')
The reason that you can't find this data in the HTML is that it's generated dynamically with a script. If you look at the first script in the HTML, you'll see a function called
getData that contains the data that you want. Another script later uses this function to build what you see in your browser.
So to scrape this data I'd just extract it directly from the script: get the string that the function returns, split it by
, and so on.
Good luck! | https://codedump.io/share/NO9FV8xDIV3K/1/scrape-webpage-after-form-fill | CC-MAIN-2017-13 | refinedweb | 153 | 73.07 |
This is not a question anyway related a single homework assignment, but rather a request for someone to help someone learn C on the side, without them taking a class. This post starts out with some general information on my skill level, and works its way to down to a list of things you could do to help me learn C. It's a fairly long read so if you aren't interested in helping this is a forewarning that it might be a waste of time.
Hello, I am a Junior in High School, and recently I decided to take a class called "AP Computer Science I" which required me to skip "Intro to Computer Science" (a class which does not cover much) and "Windows Programming" (a dual-enrollment class which mainly works with Visual Basic? I think... I didn't take it lol). At first, I had a real hard time understanding programming terminology, and I got off to a rough start. Over the first 2 weeks or so, we learned some scheme. The programs that we made were extremely low level and after this brief intro into programming (for me at least), we switched to Java. After more struggling, I began to get the gist of programming at a low level.
Currently, we are working on a program called StringUtil, in which we have to create functions that manipulate strings. Such as: Reverse, Palindrome Checker, Pig Latin Converter, and Short Hand Converter. Each of these must be done recursively, and since we have not learned loops or arrays, neither can be used, along with StringBuffer and additional useful methods that can be found in the Java API. I have already written: Reverse and the Palindrome Checker. I had them checked and they work as intended and were done recursively (the right way).
As far as Programming in C, I have only read the "C Made Easy" Beginner Tutorials on this site from the first lesson "Intro to C" through "C-Style Strings." I read this tutorials today, and I do not fully understand them, but I have learned somewhat the basics. While coming from Java Background (though a very incomplete one), the lesson on pointers was the most confusing and difficult lesson.
I do understand some basics of pointers vaguely, such as:
- How to declare a pointer
- How to assign the address of a variable to a pointer
- How to initialize pointers using malloc
- How to free pointers and set them to become null pointers
But, I lack the understanding of when to use them and ultimately, why to use them? This is a very important subject to learn and fully understand, and anyway in which you could help me understand them would be greatly appreciated.
Even though we have not learned loops, I decided to read ahead in our Java Lessons, and I have a basic understanding of loops in Java (and some in C via the Tutorials on this site). After reading this I decided to go ahead and do one of the assignments which we may do or may not. This assignment included finding magic squares and writing a method to find the Least Common Multiple or LCM of two numbers. I found this not too hard in Java. I wrote a program which included the two methods which worked.
Now, I am trying to write the magic square portion of that program in C as an attempt to grasp what I have read because without any practice I will not learn anything about C. This is one of the major problems I face. I have no assignments which are at my level and no person to help me through this process.
I have a fair amount of desire to learn C, but I am somewhat lazy, and I would like to ask if anyone (or a number of people) would like to help me get the hang of C by:
1) Taking the first step by helping me complete and understand this magic square program which I have attempted writing in C
2) Possibly take a step back to review the very basics of C by providing me a couple of simple programs to write and for you (or a number of people to check)
3) Continue to move forward by giving me additional programs to write increasing in difficulty provided with help to complete them and obtain the optimal solution
I know this a lot to ask, but any help would be much appreciated. I am considering programming as a career.
Now, back to the magic square program which i am trying to duplicate in C. Here is a little bit of information that was provided to help me understand what a magic square was:
Magic square problem:
1. Some perfect squares have unique mathematical properties. For example, 36 is:
- A perfect square, 6^2
- And the sum of the integers 1 to 8 (1+2+3+4+5+6+7+8 = 36)
So let us call a "magic square" any number that is both a perfect square AND equal to the sum of consecutive integers beginning with 1.
2. The next magic square is 1225:
352 = 1225
1225 = sum of 1 to 49
3. Write a method that prints the first n magic squares.
Here is my version of this completed in Java:
Here is my attempt in C:Here is my attempt in C:Code:public class FunLoops { public void magicSquare(int n) { int ms = 0; //Variable for storing the amount of magic squares found long num = 1, num2 = 1; long ps = 1, cia = 1; //Ps stands for Perfect Square, and Cia stands for Consecutive Integer Addition while( ms < n) { while( ps < cia) { num++; ps = num*num; } while( ps > cia) { num2++; cia += num2; } if( ps == cia) { System.out.println(ps); ms++; num++; num2++; ps = num*num; cia += num2; } } }
It does compile and it gives me the first 2 magic squares (1 and 36) but for some reason stops right there.It does compile and it gives me the first 2 magic squares (1 and 36) but for some reason stops right there.Code:#include <stdio.h> #include <stdlib.h> int main() { int n; int ms = 0; int num1 = 1; int num2 = 1; int ps = 1; int cia = 1; printf( "Please enter the number of magic squares\n" ); printf( "to be found and displayed:\n\n" ); printf( "(Remember these values will be found in\n" ); printf( " order, from the lowest possible magic\n" ); printf( " square to the highest possible magic square)\n\n" ); printf( " Input: " ); scanf( "&d\n", &n ); while ( ms < n ) { while ( ps < cia ) { num1++; ps = num1*num1; } while ( ps > cia ) { num2++; cia += num2; } if ( ps == cia ) { printf( "\n%d\n", ps ); ms++; num1++; num2++; ps = num1*num1; cia += num2; } } }
I know that this was a horrible attempt, and I basically just copied the code, but I did learn a couple of things by this attempt. Remember, that I don't know when to use pointers and anything I do know was learned in a 4 hour reading of half of the Tutorials on this site. | https://cboard.cprogramming.com/c-programming/94308-help-ambitious-16-year-old-learn-c.html | CC-MAIN-2017-13 | refinedweb | 1,186 | 59.98 |
I had a working Spark Core code built and working on in Sep-2016. Since then I had not update the code.
Today, I try to update the code, and notice it will not build anymore.
I made the changes from all Spark. into Particle. class already.
All the files build but with more warning.
Due to I include legacy libraries, any replacement, I should use instead ???
#include "flashee-eeprom/flashee-eeprom.h" #include "SparkIntervalTimer/SparkIntervalTimer.h" /workspace/SparkIntervalTimer/SparkIntervalTimer.h:60:2: warning: #warning "CORE NEW" [-Wcpp] #warning "CORE NEW" /usr/local/gcc-arm-embedded/bin/../lib/gcc/arm-none-eabi/4.8.4/../../../../arm-none-eabi/bin/ld: /workspace/target/workspace.elf section '.text' will not fit in region 'APP_FLASH' /usr/local/gcc-arm-embedded/bin/../lib/gcc/arm-none-eabi/4.8.4/../../../../arm-none-eabi/bin/ld: region 'APP_FLASH' overflowed by 7052 bytes
Any suggestions what had been changed since last year which I need to make changes to build ??
Thanks for your help | https://community.particle.io/t/build-error-for-previous-spark-core-code/31448 | CC-MAIN-2020-40 | refinedweb | 168 | 52.26 |
Interfacing USB mass storage devices (aka USB flash drives)
Inspired by this thread I've been working on making mbed read USB sticks. After making an initial port of NXP's USBHostLite example, I got stuck since my mbed was an older, LPC2368 model, and did not have USB host. However, kind people helped me to get a 1768 unit much faster than Mouser could get it in stock, and with the help of Ilya I I finally have a working example that plugs into the standard FATFileSystem.
Usage
You can try my code by importing this project: MSCUsbHost
To use it in your program, you will need to copy everything from the USBHostLite folder, and also MSCFileSystem.h/cpp files.
Usage is similar to LocalFileSystem or SDFileSystem classes:
#include "mbed.h" #include "MSCFileSystem.h" MSCFileSystem msc("msc"); // Mount flash drive under the name "msc" int main() { printf("\nTesting file write:\n"); FILE *fp = fopen( "/msc/msctest.txt", "w"); if ( fp == NULL ) { error("Could not open file for write\n"); } fprintf(fp, "Hello mass storage!"); fclose(fp); printf("\n - OK\n"); }
Connection
Flash drives, as many unpowered USB devices, require 5V on their VBUS pin to work. You can connect it to mbed's Vu output, however you should remember that Vu is powered from mbed's USB connector. If you use independent power source connected to Vin, you'll need to power the flash drive separately with regulated 5V.
D-, D+ and ground should be connected to the corresponding pins on mbed.
Here's what the sample program outputs for my memory stick:
================================ USB Mass storage demo program for mbed LPC1768 ================================ In Host_Init Initializing Host Stack Host Initialized Connect a Mass Storage device Mass Storage device connected Successfully initialized mass storage interface; 511997 blocks of size 512 Inquiry reply: Peripheral device type: 00h - Direct access (floppy) Removable Media Bit: 1 ANSI Version: 00h ECMA Version: 00h ISO Version: 00h Response Data Format: 01h Additional length: 1Fh Vendor Information: 'WIBU - ' Product Identification: 'CodeMeter-StickM' Product Revision: 'v1.0' List of files on the flash drive: - IO.SYS - MSDOS.SYS - COMMAND.COM - autoexec.bat - config.sys - himem.exe - ISSDFUT.EXE - BOOTLOG.TXT - more.exe - README.TXT - BOOTLOG.PRV - msctest.txt Testing file write: - OK Testing file read: - OK, read string: 'Hello mass storage!'
Notes
Insertion/removal detection is not working. The USB drive should be connected before you try to access it.
Remarks
While making this stuff work, I found some things that are not explained sufficiently (if at all) in the user manual. Maybe this will help other people working with the LPC17xx's USB host.
1) Port 1 must be configured as a host using the (underdocumented in the LPC17xx UM) PORT_FUNC field in the OTGStCtrl register. It is described in a somewhat more detail in the LPC23xx manual:
In short, you need to set bit 0 to 1 to enable host operation on port U1. Both 0b01 and 0b11 worked for me.
2) to access that register, you must set PORT_SEL_EN (aka OTG_CLK_EN) bit in the OTGClkSt register beforehand. It can be turned off afterwards.
3) in addition to the host clock (HOST_CLK_EN), you also need to enable the AHB clock (AHB_CLK_EN) in the OTGClkSt register. I guess it's kinda obvious in the hindsight (since USB needs AHB to work), but it's not mentioned explicitly anywhere.
You need to log in to post a comment
Very impressive detective work! It is not a trivial manual to decipher.
I tried your program and it works pretty well. It gives me a couple of warnings in the printout, but it does not prevent from writing and reading a file.
What do you think is needed for insertion/removal detection to work? Is it something that should be handled in the ISR and given to a callback function? | https://os.mbed.com/users/igorsk/notebook/interfacing-usb-mass-storage-devices-aka-usb-flash/?page=1 | CC-MAIN-2019-51 | refinedweb | 639 | 60.95 |
You too can learn how to code
Almost anyone can learn how to program a computer, or, as it’s more fashionable to call it now, “coding.” You too can learn how to “code,” and I intend to show you that by getting you started on a simple Tic-Tac-Toe game.
Not that there is any shortage of “you too can learn how to code” articles here on Medium, though such articles generally focus more on the author’s own life journey and rarely say anything about a specific programming project.
I will cover a little bit of my journey up to this point before diving into the Tic-Tac-Toe project. I started learning programming in my teen years. I read Problem Solving and Structured Programming in Pascal by Elliott B. Koffman front to back when I didn’t have a computer equipped with the Pascal programming language, or any computer at all.
In high school, I discovered that IBM-compatible PCs came with Microsoft QBasic. I copied a GW-Basic program for drawing fractals from a book, and made a couple of optimizations in the process of adapting it for QBasic.
I also wrote a sort-of scroller video game, in which a spaceship must navigate an asteroid field without getting shot at by the enemy ships. It was primitive compared to the video games available at the time, but for not having my own computer, it was something to be proud of.
There are several criticisms of BASIC, the Beginner’s All-purpose Symbolic Instruction Code, but it does what it set out to do: provide beginners with a simple programming language that can be used for many different purposes.
Later on, as a college student, I had access to Microsoft Visual Studio 6.0, with which I could write programs in Visual Basic and Visual C++.
I did write simple DOS programs in C++, and thought about writing Windows programs. But since I still did not have my own computer, the amount of time I would have to spend in the school’s computer labs seemed prohibitive.
It wasn’t until 2013 that I bought my own computer. It was on sale at Best Buy, and the blue shirts tried to persuade me to buy a more expensive computer. At the time, I figured Visual Studio would cost at least twice as much as my computer.
All throughout that time, I read books about Java and C#, but I was unaware that professional grade integrated development environments (IDEs) for Java were available for no cost other than the time and energy it takes your computer to download the installer.
In 2017, I learned about NetBeans, and downloaded and installed version 8.2 on my computer. Eclipse and IntelliJ (Community Edition) are also available.
BASIC is no longer as widely available as it once was. JavaScript is far more ubiquitous now. If you’re reading this on a modern Web browser like Google Chrome or Mozilla Firefox, you have access to JavaScript.
Some of you might remember VBScript, which was available on Microsoft Internet Explorer as an alternative to JavaScript. VBScript was based on Microsoft Visual Basic, a professional programming language that is still used by a few .NET developers resisting the switch to C#.
Don’t think that JavaScript is to Java what VBScript is to Visual Basic, it’s not. Aside from the superficial similarities to Java, and Sun Microsystems allowing the licensing of the “Java” name, JavaScript is a very different animal from Java, very loose and sloppy.
Except for its ready availability, JavaScript is profoundly unsuited for beginners. For one thing, JavaScript developed very haphazardly. It was not at first meant to be object oriented or functional, now it’s both (though with caveats).
Also, to learn JavaScript, you also pretty much also have to learn HTML and CSS, since, despite the existence of Node.js, JavaScript is still pretty much bound up with Web pages.
The Hyper Text Markup Language (HTML) is not a programming language, but, like the name says, a markup language. To turn a text document into a hypertext document, you mark it up with tags to indicate which pieces of text are headings, which are links, which are paragraphs, etc.
Ideally, a markup language does not specify formatting. That is the job of a style sheet. The preferred style sheet format for HTML (the only one I’m aware of, actually) is Cascading Style Sheets (CSS).
A style sheet might specify, for example, that all top level headings in a group of documents are to be styled as 24-point Palatino bold, or some other serif font if Palatino bold is not available. (HTML used to have formatting tags, which are now deprecated, but browsers still understand them).
And so, HTML tags should describe the structure of the content, while CSS declarations define the presentation of the content.
This is important because it is often necessary to separate presentation from content in order to serve the content to a user or program that needs a different presentation.
For example, how should a text-to-speech converter render text marked up as 24-point Palatino bold? The program might infer that the biggest font size in use on the page is for a top level heading, but the operation would be much more reliable if top level headings are clearly marked as such.
Separating content and presentation also helps with consistency. Suppose you have to specify 24-point Palatino bold over and over again for each top level heading and 20-point Palatino bold for each secondary level heading instead of defining them once each on a style sheet.
That opens up the potential for a whole bunch of mistakes, like for example, you might mistakenly style one secondary level heading as 51-point Palatino. And then that would throw off our hypothetical text-to-speech converter’s inference of what the top level heading is in the affected document.
One style sheet can format several documents, and one document can be formatted by different style sheets or combinations of style sheets. A style sheet can even be embedded into a document, but the separation of presentation and content still needs to be clearly discerned.
Although CSS has some animation capabilities, a document that is just HTML and CSS is rather static. This is where JavaScript comes in. JavaScript enables the document to change itself programmatically in response to user actions.
With JavaScript, it becomes a little more difficult to maintain the separation between content and presentation, as both are dynamically inserted into a document in ways that we might not always be able to foresee.
Though this is not as much of a concern for a game, like a Tic-Tac-Toe game. Making the game playable by the blind would require a lot more than proper structural markup. So the game I’ll start you off on will be for people with some level of sight.
We’ll do it in JavaScript, so you just need a suitable browser, like Firefox 65.0, and a plain text editor. On Windows that would be Notepad. On Mac OS X, you can use TextEdit, but be wary of its annoying tendency to want to turn everything to rich text.
In your plaint text editor, copy and paste the following:
<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-
<meta name="description" content="Play Tic-Tac-Toe against the computer." />
<style type="text/css"><!--h1 { font-family: Palatino, serif; font-size: 36pt }
table { width: 96%; border-collapse: collapse }
td { width: 32%; border: 25px solid black; font-size: 120pt;
font-family: sans-serif; text-align: center }
td#cell1 { border-left: none; border-top: none }
td#cell2 { border-top: none }
td#cell3 { border-top: none; border-right: none }
td#cell4 { border-left: none }
// td#cell5 { }
td#cell6 { border-right: none }
td#cell7 { border-left: none; border-bottom: none }
td#cell8 { border-bottom: none }
td#cell9 { border-bottom: none; border-right: none }
@media only screen and (max-width: 360px) {
td { font-size: 72pt }
}// --></style>
<script type="text/javascript"><!-- // PLACEHOLDER FOR JAVASCRIPT// --></script>
</head>
<body onload="gameInit();"><h1>Tic-Tac-Toe</h1><table>
<tr><td id="cell1" class="tttCell"> </td><td id="cell2" class="tttCell"> </td><td id="cell3" class="tttCell"> </td></tr>
<tr><td id="cell4" class="tttCell"> </td><td id="cell5" class="tttCell"> </td><td id="cell6" class="tttCell"> </td></tr>
<tr><td id="cell7" class="tttCell"> </td><td id="cell8" class="tttCell"> </td><td id="cell9" class="tttCell"> </td></tr>
</table></body>
</html>
Save it as
TicTacToe.html in a subfolder of your Documents folder, or wherever is convenient for you.
Depending on your operating system and default Web browser setting, you might see within your Documents folder something like the screenshot on the left. The screenshot was taken on a Windows 8 machine in which Mozilla Firefox is the default Web browser.
If you double-click the
TicTacToe.html icon, the Web page should open in a new tab on your default Web browser. In the following screenshot, we see the Firefox preview of what the page might look like on an iPhone 5.
You can click on the Tic-Tac-Toe board all you want, nothing is going to happen.
That’s because we haven’t really attached any JavaScript to this yet. The
body tag does include the
onload="gameInit()" declaration, but
gameInit() is not defined anywhere.
In fact, if you access the JavaScript console (with the F12 key, at least on Firefox for Windows), you will see the error message
ReferenceError: gameInit is not defined.
So the next step here is to define
gameInit(), a subroutine that will attach
onclick event listeners to the nine squares of the Tic-Tac-Toe board. Then, when the human player clicks one of the square, the
captureSquare() subroutine will be called.
Back in the plain text editor, delete the JavaScript placeholder and paste in the following:
var humanPlayerToken = "X";
var computerPlayerToken = "O";
var ticTacToeArray = [" ", " ", " ", " ", " ", " ", " ", " ",
" "];
var ticTacToeCells; function won(token) {
return false;
} function captureSquare() {
// PLACEHOLDER
} function gameInit() {
ticTacToeCells = document.getElementsByClassName("tttCell");
for (var i = 0; i < ticTacToeCells.length; i++) {
ticTacToeCells[i].addEventListener("click", captureSquare)
}
}
This defines some global variables to help the computer keep track of the squares.
Now, it might seem inefficient to use a variable with a16-letter name to refer to a single letter. And it is, for now. But it gives us the flexibility to later give the human player the ability to choose a token other than “X” without having to rewrite too much.
Most programming languages make very clear distinctions between subroutines that return values to the callers and subroutines that don’t. In the Pascal programming language, they are called functions and procedures.
For example, a subroutine that takes an angle and returns a cosine is rightly said to be a function, but a subroutine that takes and angle and displays it on the screen without returning anything to the caller is procedure.
JavaScript blurs the distinction between functions and procedures, as it has both of them defined with the keyword
function. Sometimes, the only way to tell whether a JavaScript subroutine returns a value or not is by the presence or absence of the
return keyword.
So
won() is a function that is supposed to check if the player identified by
token has captured three squares in a line: if that’s the case, it returns
true, if not it returns
false. However, in this early draft, it doesn’t actually check that, it just returns
false regardless.
Then
captureSquare() and
gameInit() are procedures, but they’re defined with the keyword
function. For now,
captureSquare() doesn’t do anything, it just has a “comment.”
Almost all programming languages have some syntax for comments, which are remarks that the parser ignores when compiling or interpreting the source code. Comments are a great way to set up “scaffolding” for your program.
In JavaScript, two consecutive forward slashes cause the parser to regard everything afterwards, up to the end of the line, as a comment. Eventually the placeholder comment in
captureSquare() will be replaced with actual JavaScript commands.
Lastly,
gameInit() attaches the event listeners to each
td element in the HTML document having class attribute
tttCell, after putting them in a collection with the
document.getElementsByClassName() function.
Note that in many programming languages, indexes start at 0, not 1. Thus our iterator through the collection of nine squares starts out at
i = 0, then is incremented as long as
i < 9 (though it’s better form to not hard-code 9 as the threshold, and instead rely on the
length property of the squares collection).
This should be enough so that our program does not trigger any error or warning messages. But we still need to define what exactly
captureSquare() does before our program actually does anything visible.
For starters, it needs to put the human player’s token (“X” only for now) in the square, remove the event listener, and update the array. Edit
captureSquare() like this (new lines are in bold):
function captureSquare() {
this.innerText = humanPlayerToken;
this.removeEventListener("click", captureSquare);
var index = parseInt(this.id.substring(4)) - 1;
ticTacToeArray[index] = humanPlayerToken;
}
Since
captureSquare() will be called in response to the human player clicking on one of the board’s squares, the
this keyword will refer to that square, so we don’t actually need to know the square’s index to put the human player’s token in the square and remove the event listener.
The
this keyword in JavaScript is one of the most confusing aspects of JavaScript ever. Luckily, there are several articles here on Medium that explain it. If one of them doesn’t do it for you, look up another.
At this point it’s not terribly important to actually remove the event listener, since we’re not keeping track of the move count yet. If we were, we should not assume that no player would ever waste a move trying to capture a square they had already captured before.
We do need to know the captured square’s index to update the internal Tic-Tac-Toe array. If you look back at the HTML, you will see each of the cells has an HTML
id attribute from
cell1 to
cell9. So we just need to extract that number and subtract 1 to put it in the range 0 to 8 in order to change
ticTacToeArray accordingly.
Save in the editor and refresh in the browser. Assuming no mistakes in the source (like misspellings in variable names or misplaced symbols), you should now be able to put an “X” in each of the nine squares.
Obviously this still requires more work to be a viable game. But at least you have verified that the event listeners are working as they should, so that the human player can place his or her first token in any of the nine squares.
Then the next step is to modify
captureSquare() so that it calls
won() to check if the human player has captured three aligned squares. If not, the computer should make its countermove. And of course we’ll need to actually write
won(), which I suggest we do by writing a helper function called
checkLine().
function checkLine(indexA, indexB, indexC, token) {
return (ticTacToeArray[indexA] == token
&& ticTacToeArray[indexA] == ticTacToeArray[indexB]
&& ticTacToeArray[indexB] == ticTacToeArray[indexC]);
}
You can insert
checkLine() almost anywhere you want within the HTML
script tags, just as long as you take care not to insert it into another subroutine.
In most programming languages,
= means assign to a variable or constant,
== means check if they’re equal. JavaScript has both of those, plus also
===, a strict equality check, but hopefully
== will be sufficient for our purposes.
Then
won() can be pretty much just a series of
checkLine() calls. We’ll have the function first check the three rows, then the three columns, and lastly the two diagonals. Delete the placeholder in
won(), and replace it with what’s bolded in the following:
function won(token) {
var winFlag = false;
var currIndex = 0;
while (currIndex < ticTacToeCells.length && !winFlag) {
winFlag = checkLine(currIndex, currIndex + 1, currIndex + 2,
token);
currIndex += 3;
}
currIndex = 0;
while (currIndex < 4 && !winFlag) {
winFlag = checkLine(currIndex, currIndex + 3, currIndex + 6,
token);
currIndex++;
}
if (!winFlag) {
winFlag = checkLine(0, 4, 8, token);
}
if (!winFlag) {
winFlag = checkLine(2, 4, 6, token);
}
return winFlag;
}
I could have written
currIndex = currIndex + 3 and
currIndex = currIndex + 1, but I generally prefer the shortcuts
currIndex += 3 and
currIndex++.
For some reason, long ago, someone decided that an exclamation as a prefix would mean “not.” So
!true is “not true,” meaning “false,” and
!false is “not false,” meaning “true.” A lot of languages, including JavaScript, followed suit, so this is now too entrenched to change.
Thus “
if !winFlag” means “
if winFlag == false,” so that if the function hasn’t found a winning line, it should keep looking.
There are too many hard-coded values for my liking here. But I don’t want to complicate things more than necessary. Next, we amend
captureSquare():
function captureSquare() {
this.innerText = humanPlayerToken;
this.removeEventListener("click", captureSquare);
var index = parseInt(this.id.substring(4)) - 1;
ticTacToeArray[index] = humanPlayerToken;
if (won(humanPlayerToken)) {
notifyWinner(humanPlayerToken);
} else {
counterMove();
}
}
Now we will need to write
notifyWinner() and
counterMove(). For
notifyWinner(), a simple Web browser alert will suffice for now, you can add some flair and pizzazz later.
function notifyWinner(token) {
alert(token + "'s wins the game!");
}
I think this is probably about the point I should let you take over. I’ll write a simple
counterMove() that merely chooses the first available square, and then I leave it to you to rewrite the algorithm so that it plays more competitively.
function counterMove() {
var availableSquare = false;
var currIndex = 0;
while (currIndex < ticTacToeCells.length && !availableSquare) {
availableSquare = (ticTacToeArray[currIndex] == " ");
if (availableSquare) {
ticTacToeArray[currIndex] = computerPlayerToken;
ticTacToeCells[currIndex].innerText = computerPlayerToken;
ticTacToeCells[currIndex].removeEventListener("click",
captureSquare);
}
currIndex++;
}
if (won(computerPlayerToken)) {
notifyWinner(computerPlayerToken);
}
}
Here it becomes very important to remove the event listener from the square captured by the computer, because you don’t want the human player to be able to capture a square that the computer has captured.
Even so, with this version of
counterMove(), the only way the computer can win is if you let it. So, if you choose to continue with this project, your top priority is to rewrite
counterMove() so that the computer becomes capable of thwarting the human player from capturing three squares in a line. Such as by having it check if the human player has already captured two squares in a line.
Then, if you like, you could give the human player the ability to play O’s instead of X’s. You could use other letters, and even emoji, as tokens. Other possible improvements include a fancier winner notification and the ability to reset the board without having to refresh the page. And some way to draw a line through the winning captured squares. These improvements would require learning more not just about JavaScript but also learning more about HTML and CSS.
I hope that this exercise proves to you that you too can learn how to “code.” You might also want to learn programming methodologies, like “Agile” and test-driven development, but I’m sure you’re also capable of learning those.
The more important question, and one I don’t have an answer to, is: how do you get a job in this field if you’re not a twenty-something white guy?
Lack of experience in a programming job is of course a shortcoming for a young white male applicant, but an understandable one. That understanding does not generally extend to other demographics of job applicants.
One slightly encouraging thing I have noticed, however, is that, regardless of your race, if you can get your first programming job and hold on to it for a few months, recruiters will try to poach you for another company.
You are only as desirable to one software company as you’re desirable to another software company. How “good” you are at “coding” is just one factor, and hardly the biggest obstacle. | https://alonso-delarte.medium.com/you-too-can-learn-how-to-code-9e02943bee63 | CC-MAIN-2021-21 | refinedweb | 3,378 | 61.16 |
I've come to appreciate the new Visual Studio 2010 code editor IntelliSense features like Pascal case lookup and the narrowing list that is presented as you type. Unfortunately, these new code editor features did not make it into the XAML Editor. But not to worry…
Pascal case lookup is always enabled regardless of the narrowing filter option. When all of your text is upper case, this feature kicks in to quickly locate the item you are looking for. Note, this feature requires at least two upper case characters be entered before kicking in.
The below image demonstrates the Pascal case lookup:
Locating an assembly using the xmlns Pascal case IntelliSense is super fast.
When the narrowing list filter is enabled, it provides two features.
Grid.Row
Grid.RowSpan
This was my original driving force behind writing this extension. I found myself frustrated when a type in XAML had 2 properties, 4 events and 75 namespaces listed in the IntelliSense listing. Problem solved.
Standard list of items, notice the multitude of namespaces that are listed.
Toggle the namespaces ToolBar button by clicking it and they are filtered for you.
The other ToolBar filter buttons work the same. The gray background is the enabled state. The white background with grayscale image is the disabled state.
The below image demonstrates the two filter buttons in the xamls IntelliSense presenter.
Another way to locate your assemblies very quickly is demonstrated in the below image. There are two filter buttons in the default state and I entered WC to quickly find an assembly in my solution.
In the below image, I'm taking advantage of the narrowing filter to locate all assemblies that have the word media. When searching the text with this type of search, the entire entry line of text is searched including the assembly name inside the (…).
To view your installed extensions, use the Visual Studio 2010 menu, Tools, Extension Manager…
From here, you can either disable or uninstall extensions.
You can also configure settings for extensions using the Tools, Options dialog.
Visual Studio 2010 Release Candidate or later version.
This will probably work on Visual Studio 2010 Beta2, but I have not tested it.
If you elect to download the source and possibly modify to meet your needs, you MUST uninstall the Extension if you used the VSIX to install it.
Additionally, I got burned when I first started this project and I had been studying a sample on CodePlex. If you want to develop your own extension, be sure the following folder is cleared out before you start a new project. If you have a conflicting project, i.e., another IntelliSense extension in the below folder, you could get conflicts when debugging.
C:\Users\<your login in name is here>\AppData\Local\Microsoft\VisualStudio\10.0Exp\Extensions
I learned SO MUCH writing this extension. Over the next week or two, I'll do a blog post explaining this extension and what is so different about this extension and the extension samples on CodePlex.
After the Visual Studio 2010 Launch Event, I'll make suggested changes and post a new version here and on the Code Gallery.
Hope you like this XAML Editor extension.
Have a great day,
Just a grain of sand on the worlds beaches.
Filed under: C#, Cider Designer, CodeProject, Extension, IntelliSense, | https://www.codeproject.com/Articles/67289/Visual-Studio-XAML-Editor-IntelliSense-Presen | CC-MAIN-2019-13 | refinedweb | 555 | 64.3 |
Nice.
It would be nice if we could just say systemctl start minidlna and have it work. Could you please drop the User= line from the service file or fix it some other way. E.g. the official minidlna package creates a new `minidlna` user. That code could just be copied wholesale to this package if desired.
Search Criteria
Package Details: readymedia-transcode-git 581.290ef09-1id3tag
- sqlite3 (sqlite)
- git (git-git) (make)
Required by (1)
- minidlnagui (requires minidlna)
Sources (4)
Latest Comments
jforberg commented on 2016-10-12 01:14
Nice.
Anonymous comment on 2013-08-14 05:12
Installing pkg-config solved my problems.
Anonymous comment on 2013-08-13 21:11
checking for sqlite3_prepare_v2 in -lsqlite3... yes
./configure: line 9454: syntax error near unexpected token `LIBAVFORMAT,'
./configure: line 9454: `PKG_CHECK_MODULES(LIBAVFORMAT, libavformat)'
After #'ing out the the PKG_CHECK_MODULES for LIBAVFORMAT, LIVAVUTIL, LIBAVCODEC, and MagickWand... it completes. Alas then upon make,
metadata.c:33:29: fatal error: wand/MagickWand.h: No such file or directory
#include <wand/MagickWand.h>.
In configure.ac, before building I tried directly #INCLUDE_DIR "/usr/include/ImageMagick-6", to no avail.
stativ commented on 2013-08-06 07:18
rndstr: x264 is a dependency of ffmpeg.
rndstr commented on 2013-08-04 10:40
the dependency `x264' is missing
/usr/bin/ld: warning: libx264.so.133, needed by /usr/lib/gcc/x86_64-unknown-linux-gnu/4.8.1/../../../../lib/libavcodec.so, not found (try using -rpath or -rpath-link)
after installing x264 it works.
stativ commented on 2013-07-05 08:33
You can try the standard "transcode_video" script. That one unfortunately has "DVD quality" output, but it is well tested.
The transcode_video-hq is a quick try on creating a script that tries to keep the quality as high as possible, but it is computationally intensive and it may require bandwidth too big for the TV to actually play some files. My Samsung TV refuses to play some files with this script too. The "client is full??" message in the log confirms it. I'm sure that someone with more experience in using ffmpeg would be able to come up with a better script, though.
tydell commented on 2013-07-04 22:50
It is very clearly what you wrote but I must say I have an issue with that. When I set container to all in minidlna.conf then I can't play any video on my tv (Sony Bravia kdl46nx720).
I try to play mp4 files (h264/aac) that my bravia supports very good. I need to transode this files to get subtitles in my movies (tv doesn't support external subs). I have:
transcode_video_containers=all
transcode_video_transcoder=/usr/share/minidlna/transcodescripts/transcode_video-hq
ffmpeg works with srt and ass subs (tested in terminal) so I edited properly transcode_video-hq to load subtitles.
Movie doesn't start, I get "Unable to play media" on my tv. In minidlna.log I get: ? | https://aur.archlinux.org/packages/readymedia-transcode-git/ | CC-MAIN-2017-43 | refinedweb | 489 | 67.15 |
One of the main features of Java is the applet. Applets are dynamic and interactive programs. Applets are usually small in size and facilitate event-driven applications that can be transported over the web.
An applet is a Java code that must be executed within another program. It mostly executes in a Java-enabled web browser. An applet can be embedded in an HTML document using the tag <APPLET> and can be invoked by any web browser. Parameters can be passed to an applet using the tag <PARAM> in the HTML document. Applets can also be executed using the appletviewer utility provided in the J2SDK kit.. A simple program using applet looks like:
A Java applet must be a public class. Thus, the Applet class can be accessed when the applet is run in a web browser or in the Appletviewer. The applet code will be compiled even if the class is not declared as public, but the applet will not run. An applet code looks as shown below:
import java.applet.*;
public class SampleApplet extends Applet
{
//applet code
}
Like any other Java program, the applet's class name must match with the name of the file in which it is written.
Applets do not contain the main () that is required to run a Java application and thus they cannot run on its own; however, usually applets run in a container that provides the missing code, The main features of applet include the following:
• It provides a GUI
• facilitates graphics, animation and multimedia
• provides a facility for frames
• enables a event handling
• avoids a risk and provides a secure two-way interaction between web pages.
Note that it is possible to execute applets using the Java interpreter (using the main () method) if the class is extended with Frame.
An applet can reside anywhere on the web and can be downloaded on any computer. Applets have limited access to the resources of the client into which they are installed from an Internet server. For this reason, applets avoid the risk of viruses or breaking the data integrity problems at the client. Applets provide security by reverifying the generated byte code and no memory space is allocated till the reverification process completes. Generally, a virus cannot be hidden in uninitialized memory. If the reverification process is not complete, the applet will be rejected. Further, applets cannot do the following:
• Read or write client file system (disks) unless specified explicitly; in such cases, the Applet is allowed only in certain directories
• Access the source code of the applets; the applet's source code can be accessed only from the original server
• Execute local programs/libraries/ DLLs on the client
• Opening network connections other than to a HTTP server: applets only talk to the server that they live on
• Finding information about the user such as user name, directories and applications installed
Applets are very useful for the presentation and demonstration of a concept in an effective manner. For example, an applet designed for explaining the bubble sort algorithm shows visually how the bubble is moved during each pass of the algorithm, Usually, applets interact with the AWT controls and it is necessary to import the awt package (java.awt*) and also the event package (java.awt.event.*) for event handling. Input/Output streams are not commonly used for applets for the purpose of I/O. Figure illustrates the byte code of an applet running at a client.
In Table the main methods of Applet class.
import java.awt.*;
import java.applet.*;
/* <applet code="NewApplet" width=500 height=200> </applet>*/
public class NewApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString("New Applet Program", 20, 100);
}
}
The statement below draws the string New Applet Program at the pixel position (20, 100
g.drawString("New Applet Program", 20, 100);
To execute Java Applet, appletviewer is used. We pass the source filename as an argument to appletviewer because it will read the <applet> tag given in comment part of the source file. From there, it will find which class has to execute from the attribute code, what will be the width and the height of applet window, read from width and height attribute of <applet> tag respectively. The screenshot below explains the compilation and execution of a Java Applet.
The screenshot below shows the starting of an App | http://ecomputernotes.com/java/awt-and-applets/what-is-applet | CC-MAIN-2020-05 | refinedweb | 723 | 51.07 |
The type independent portion of reader. More...
#include <DataFile.hh>
The type independent portion of reader.
Constructs the reader for the given file and the reader is expected to use the schema that is used with data.
This function should be called exactly once after constructing the DataFileReaderBase object.
Closes the reader.
No further operation is possible on this reader.
Initializes the reader to read objects according to the given schema.
This gives an opportunity for the reader to see the schema in the data file before deciding the right schema to use for reading. This must be called exactly once after constructing the DataFileReaderBase object.
Move to the next synchronization point after a position.
To process a range of file entries, call this with the starting position, then check pastSync() with the end point before each use of decoder(). | https://avro.apache.org/docs/current/api/cpp/html/classavro_1_1DataFileReaderBase.html | CC-MAIN-2021-39 | refinedweb | 140 | 67.15 |
Building Pluggable Python Applications
. This post will show one way you can keep your core application reasonably small and add new functionality using plugins.
One of the main advantages of using plugins is that they can be developed separately from the main application and be added or removed without the core of the application needing to think too much about them. This also means that plugins can be tested separately from the main application. It also means developers can add significant features to an application quickly without merging them into the main application. However, the main drawback is that plugin creators needs follow the constraints imposed by the core system and how the plugins are called.
In this post, we will create a toy example of how a pluggable application works using the
pluggy library. The library is created by the
pytest team, and you probably have used its functionality already when you have added extensions to PyTest such as coverage support.
How Pluggy works
How pluggy works is by first specifying your plugin specification and letting plugins use that specification to create extensions to your application. The plugins are called when the main applications call plugin hooks which correspond to the functions defined in the plugin specification. An example would be a
process_file hook that the main application calls when a file should be processed for information. The application then passes the file as a parameter to the hook, and the plugin picks up the file and does whatever the plugin is written to do.
To know which plugins to call, Pluggy has a plugin manager that keeps track of all of the plugins available. There are two ways to register the plugins in an application. Either it is done manually by calling a register call and pointing to the plugin, or it is done automatically through setup.py entrypoint. In this post, we only go through the manual registration process, but you can read more about automating the registration from Pluggys documentation.
Pluggy has many features such as setting calling orders, blocking plugins, calling hooks retroactively if they are loaded later during runtime, etc. I mention these to point out that the library is very mature and if you don’t have a good reason for it, you probably are better off using Pluggy than rolling your own plugin manager. However, this post will keep it simple and show how to build a small toy application using plugins.
Building a pluggable application
We will write a tool that will collect jokes from plugins and display them on screen. The main application itself will not be responsible for getting any jokes; however, that will be the plugin’s job. To keep things simple, all plugins will be included in the main codebase, but they could just as well be written as separate Python packages as well.
Let’s start with the dependencies that will need to be installed in order to build this. Building this example application, Poetry is used as the package manager, but you can use what best fits you. The packages that we are going to need are:
requests # This is needed for the plugins
pluggy
Next up, we create the base of our application:
# main.pyclass App:
def display_jokes(self, amount: int) -> None:
results = [[]]
jokes = [joke for plugin in results for joke in plugin]
for joke in jokes:
print(joke)if __name__ == "__main__":
app = App()
app.display_jokes(2)
This code does almost nothing, and that is the point. We will leave the heavy lifting to the plugins in this case. But to get those plugins working, we first need to create our plugin specification. Let’s make that now.
# hookspec.pyfrom typing import Any, Callable, List, TypeVar, castimport pluggy # type: ignoreF = TypeVar("F", bound=Callable[..., Any])
hookspec = cast(Callable[[F], F], pluggy.HookspecMarker("python_plugin_example"))class PluginExampleHookSpec:
"""
Python Plugin Example Hook Specification
""" @hookspec
def retrieve_joke(self, amount: int) -> List[str]:
"""
Fired when retrieving jokes Args:
amount: How many jokes should be returned Returns:
A string containing a joke
"""
That’s it; without the typing and comment, this is five lines of code. The main lines of interest here are the hookspec assignment and the function decorator. The hookspec variable is created by calling the HookspecMarker with the name of the application as the parameter. So if your application is called “awesomefire” in your setup.py or pyproject.toml file, that is what you should enter as the marker parameter as well. Each of the hook functions you want to define should then be decorated with the @hookspec decorator to mark them as hooks. In this example, we have a single retrieve_joke function that takes one parameter amount that indicates how many results we would like to get back from the plugin. The documentation and typing, while optional, is highly encouraged as otherwise, plugin developers will have to guess what is being passed to them when the hook is called.
Now that we have our specifications, we also need to create an implementation function that plugins can hook into our specifications.
# hookimpl.pyfrom typing import Any, Callable, TypeVar, castimport pluggy # type: ignoreF = TypeVar("F", bound=Callable[..., Any])hookimpl = cast(Callable[[F], F], pluggy.HookimplMarker("python_plugin_example"))
Plugins will later use the
hookimpl variable to hook into the plugin system. Again, the name of the application is passed as the main parameter to the
HookimplMarker. Now that we have our plugin system set up let's set up our application to use it.
# main.pyimport pluggy # type: ignorefrom python_plugin_example.hookspec import PluginExampleHookSpecclass App:
def __init__(self) -> None:
self.pm: pluggy.PluginManager = pluggy.PluginManager("python_plugin_example")
self.pm.add_hookspecs(PluginExampleHookSpec) def display_jokes(self, amount: int) -> None:
results = self.pm.hook.retrieve_joke(amount=amount)
jokes = [joke for plugin in results for joke in plugin]
for joke in jokes:
print(joke)if __name__ == "__main__":
app = App()
app.display_jokes(2)
The two new lines added to the
__init__ method create a plugin manager and registers the plugin hook specification. Again, the plugin manager parameter should be the same as the application name. This plugin manager can then be used to register plugins and call hooks. In the
display_jokes function, we have also added a hook call to call all plugins and collect all of the jokes returned by them. Pluggy always returns plugin results as a list, and as the
retrieve_joke joke function also returns a list, we flatten everything down to a single list and finally print all of the jokes one by one. Now let's create our plugins. We will make two of them, one returning dad jokes and the other Chuck Norris jokes. We will get all of the jokes through APIs to not need to come up with the jokes ourselves. The plugin code looks like this.
# plugins/icanhazdadjokes.pyfrom typing import Listimport requestsfrom python_plugin_example.hookimpl import hookimplDAD_JOKE_API_ENDPOINT = "<>"class ICanHazDadJokePlugin:
@hookimpl
def retrieve_joke(self, amount: int) -> List[str]:
headers = {
"Accept": "application/json",
}
values = []
for i in range(amount):
response = requests.get(DAD_JOKE_API_ENDPOINT, headers=headers)
values.append(response.json().get("joke", "")) jokes = [f"👨 Dad joke: {value}" for value in values]
return jokes# plugins/chucknorris.pyfrom typing import Listimport requestsfrom python_plugin_example.hookimpl import hookimplCHUCK_NORRIS_API_ENDPOINT = "<>"class ChuckNorrisPlugin:
@hookimpl
def retrieve_joke(self, amount: int) -> List[str]:
values = []
for i in range(amount):
response = requests.get(CHUCK_NORRIS_API_ENDPOINT)
values.append(response.json().get("value", "")) jokes = [f"🤠 Chuck Norris: {value}" for value in values]
return jokes
The main parts to take note of here are the use of the
@hookimpl decorator and the function name. The decorator marks a function as being something that can be called by a hook to distinguish it from other functions. The function
retrieve_joke must match the hook specification that we created earlier and have the same attributes as it. If there is an attribute mismatch, Pluggy will complain, and your code will not work. The application code itself is relatively straightforward; we use the Request library to fetch jokes from APIs, turn the results into a list, and return the list. Now that we have our plugins written let's register those in our main application.
# main.pyimport pluggy # type: ignorefrom python_plugin_example.hookspec import PluginExampleHookSpec
from python_plugin_example.plugins.chucknorris import ChuckNorrisPlugin
from python_plugin_example.plugins.icanhazdadjoke import ICanHazDadJokePluginclass App:
def __init__(self) -> None:
self.pm: pluggy.PluginManager = pluggy.PluginManager("plugin_example")
self.pm.add_hookspecs(PluginExampleHookSpec) self.pm.register(ChuckNorrisPlugin())
self.pm.register(ICanHazDadJokePlugin()) def display_jokes(self, amount: int) -> None:
results = self.pm.hook.retrieve_joke(amount=amount)
jokes = [joke for plugin in results for joke in plugin]
for joke in jokes:
print(joke)if __name__ == "__main__":
app = App()
app.display_jokes(2)
The two new lines here are the
self.pm.register calls that add the plugins to the plugin manager. Note that what is passed to the register are class instances and not the class itself.
And that is it. We now have an application that uses plugins to fetch jokes from the internet. The fetching logic of those jokes is fully decoupled from the main application code that only takes care of outputting the results in this case.
> python main.py
👨 Dad joke: Geology rocks, but Geography is where it’s at!
👨 Dad joke: My pet mouse ‘Elvis’ died last night. He was caught in a trap..
🤠 Chuck Norris: Chuck Norris only applies his car brakes for people with red hair & beards.
🤠 Chuck Norris: Chuck Norris does not need a toothbrush when he brushes his teeth
This is a simple example but could easily be extended to include more hooks and more plugins. So feel free to download the source for it and add your hooks and plugins. The source can be found on GitHub. | https://anders-innovations.medium.com/building-pluggable-python-applications-d6e0d1b71ca6?source=user_profile---------3---------------------------- | CC-MAIN-2021-39 | refinedweb | 1,603 | 54.93 |
!
- Member Since
- Jan 22, 2010
- Location
- Victoria, BC
- 20,911
- Specs:
- Mid-2012 MBP (16GB, 1TB HD), Monoprice 24-inch second monitor, iPhone 5s 32GB, iPad Air 2 64GB OS X - Apps and GamesReplies: 1Last Post: 06-19-2013, 11:15 PM
Using "Preview" to import pictures questionBy welshred in forum OS X - Operating SystemReplies: 3Last Post: 04-17-2013, 08:08 AM
GoPro Hero video - can I import using "Apple iPad Camera Connection Kit"?By callagga in forum iPad Hardware and AccessoriesReplies: 1Last Post: 07-24-2012, 07:05 PM
Import .mts files from HD camera in iMovie or use Toast?By NewAppleMacGuy in forum Movies and VideoReplies: 3Last Post: 01-30-2011, 04:57 PM
import issue: only showing imovie 08:last import ... unable to locate previous importBy DAIDAI in forum Movies and VideoReplies: 0Last Post: 12-25-2008, 03:03 PM | http://www.mac-forums.com/forums/movies-video/208228-imovie-import-camera-import-mpeg-2-a.html | CC-MAIN-2016-07 | refinedweb | 144 | 54.97 |
lag. This also gives great opportunity to run production scripts to flash new firmware or automate other tasks.
import sys, re
import subprocess
import time
import serial.tools.list_ports
def grep(regexp):
for port, desc, hwid in serial.tools.list_ports.comports():
if re.search(regexp, port, re.I) or re.search(regexp, desc) or re.search(regexp, hwid):
yield port, desc, hwid
# Discover all COM ports and show them
port_list_initial = serial.tools.list_ports.comports()
for port, desc, hwid in port_list_initial:
print('-', port, desc)
print('\nWaiting for new USB to SERIAL device to be plugged in...\n')
# Wait for new device to be plugged in and show it
while True:
port_list_poll = serial.tools.list_ports.comports()
for p in port_list_poll:
if p not in port_list_initial:
print('-', p)
input('\nAll done, press enter to quit')
sys.exit(1)
else:
time.sleep(0.5) # Don't poll too often
Also code is uploaded to GitHub | https://www.kurokesu.com/main/2019/02/01/which-usb-to-com-port-is-the-most-recent-one/ | CC-MAIN-2019-26 | refinedweb | 151 | 61.83 |
If I want use a picture from the web?
logo = new ImageItem(null, Image.createImage("????")
Thanks!
Post your Comment
Image Item Using Canvas Example
Image Item Using Canvas Example
This example is will show you how to create the image at the top center of the screen. The following are the methods used
Image Icon Using Canvas Example
Image Icon Using Canvas Example
This example is used to create the Image on different location using Canvas
class. In this example to create the image we are using
Simple Line Canvas Example
Simple Line Canvas Example
This is a simple example of drawing lines using canvas class in J2ME. In this example we are
creating three different lines at different
Image Icon Using Canvas Example
Image Icon Using Canvas Example
This example is used to create the Image on different location using Canvas
class. In this example to create the image we are using
Line Canvas MIDlet Example
Line Canvas MIDlet Example
In this example, we are going to draw to different lines which cross to each other on
the center of the mobile window using Canvas class. "
Creating Canvas Form Example
Creating Canvas Form Example
This example shows that how to use the Canvas Class in a Form. In this example
we take two field in which integer number passed from the form
Draw Font Using Canvas Example
Draw Font Using Canvas Example
This example is used to draw the different types of font using Canvas class.
The following line of code is used to show the different style
Immutable Image using Canvas Class
Immutable Image using Canvas Class
This is the immutable image example which shows how to create the immutable
image using canvas. In this example ImageCanvas class
Creating Menu Using Canvas Class
Creating Menu Using Canvas Class
This example shows how to create the menu and call the canvas class to show
the toggle message. The Toggle message will appear when
J2ME Canvas Example
J2ME Canvas Example
A J2ME Game Canvas Example
This example illustrates how to create a game using GameCanvas class.
In this example we are extending GameCanvas class
J2ME Canvas KeyPressed
in J2ME using
canvas class. After going through the given example, you will be able to show
different output against different keypressed actions. This example...
J2ME Canvas KeyPressed
Item Events in Java
Item Events in Java
Introduction
In this section, you will learn about handling item events in java. This
demonstrates that the event generated when you select an item
Draw String Using Canvas
Draw String Using Canvas
This example is used to draw string on different location which...(){}
}
class TextCanvas extends Canvas{
public
Draw Clip Area Using Canvas
Draw Clip Area Using Canvas
This Example is going to draw a clip with SOLID line...)
and to draw the dotted line we are using DOTTED keyword, as given below
Chart Item Event in Flex4
Chart Item Event in Flex4:
Chart uses the ChartItemEvent when you perform the
operation click on the chart Item. This event is the part of chart package...
sensitivity is greater than 3 then the ChartItemEvent will not work. In this
example
J2ME Image Item Example
J2ME Image Item Example
This application illustrates how to create the image and imageItem using
Image and ImageItem class respectively. In this example we are going to create
delete an item from database
delete an item from database how to delete an item from the database using jsp
Canvas Layout Container
the
canvas container using x and y properties of each components. These x and y...
distances from canvas edges and canvas center. This can be done using properties...
Canvas Layout Container
Item renderer in flex
Item renderer in flex Hi......
please tell me about
How to create item renderers in flex?
give an example for that
List in J2ME
;
J2ME Canvas List Example will explain you, how to create list of items. In
this example we are going to create a simple list of text, that will show the
selected item on the same screen. In the example you can see that we have
J2ME Canvas Repaint
J2ME Canvas Repaint
In J2ME repaint is the method of the canvas class, and is used to repaint the
entire canvas class. To define the repaint method in you midlet follow
Java JComboBox Get Selected Item Value
example into which I shall get the combo box
selected item value and stored...Java JComboBox Get Selected Item Value
In this section we will discuss about how to get the selected item value form JComboBox.
javax.swing.JComboBox
Canvas Layout Container in Flex4
of Canvas Layout
Container is <mx:Canvas>.
In this example the colored area shows the Canvas
container.
Example:
<?xml version="1.0...Canvas Layout Container in Flex4:
The Canvas layout Container is used
Text Example in J2ME
Text Example in J2ME
In J2ME programming language canvas class is used to paint and draw the
diagrams. Using the same canvas class we are going to draw a box around the text
J2ME Vector Example
. In this
example we are using the vector class in the canvas form. The vector class contains
components that can be accessed using an integer index. The following... J2ME Vector Example
J2ME Frame Animation
it in the canvas class.
In this example we are creating a frame using Gauge class. When the command
action call the "Run" command ,which display the canvas form. In
the canvas form we are drawing three blocks, when form's action
Rectangle Canvas MIDlet Example
Rectangle Canvas MIDlet Example
The example illustrates how to draw the different types of rectangle in J2ME.
We have created CanvasRectangle class in this example
awt list item* - Swing AWT
awt list item* how do i make an item inside my listitem not visible Hi friend,
import java.awt.*;
import java.awt.event.... information.
Thanks
Image from webNanuss June 25, 2012 at 9:23 PM
If I want use a picture from the web? logo = new ImageItem(null, Image.createImage("????") Thanks!
Post your Comment | http://www.roseindia.net/discussion/22434-Image-Item-Using-Canvas-Example.html | CC-MAIN-2014-52 | refinedweb | 1,002 | 58.21 |
Enable data upload
#include <curl/curl.h>
CURLcode curl_easy_setopt(CURL *handle, CURLOPT_UPLOAD, long upload);
The long parameter upload set to 1 tells the library to prepare for and perform an upload. The CURLOPT_READDATA(3) and CURLOPT_INFILESIZE(3) or CURLOPT_INFILESIZE_LARGE(3)(3) as usual.
If you use PUT to a HTTP 1.1 server, you can upload data without knowing the size before starting the transfer if you use chunked encoding. You enable this by adding a header like "Transfer-Encoding: chunked" with CURLOPT_HTTPHEADER(3). With HTTP 1.0 or without chunked transfer, you must specify the size.
0, default is download
Most
TODO
Always
Returns CURLE_OK | https://www.carta.tech/man-pages/man3/CURLOPT_UPLOAD.3.html | CC-MAIN-2018-51 | refinedweb | 106 | 52.26 |
Howdy,
I'm having some trouble figuring out this problem after searching for a
good chunk of the day on the
web for some answers. Here goes.
I have a Java class that I am importing for use in my Jython script.
Simple enough. The Java class looks
something like this (with all other gory details stripped):
public class MyObject
{
public Object value;
public Object value()
{
return value;
}
}
Example usage:
x = new MyObject()
x.value = new ArrayList() (...ArrayList is just used as an example)
Now, in my Jython script, I try to do the following:
from abc_package import MyObject
from xyz_package import UserProfile # Another Java class
myObj = MyObject()
uProfile = UserProfile()
myObj.value = uProfile
When the script is executed, I get the following error:
TypeError: can't assign to this attribute in java instance: value
After fiddling around with various print's and browsing through some
documents, I finally understand
(I think) what the problem is. Jython is recognizing the myObj.value as
a method object instead of an
instance attribute. I've been looking for ways to get around this, but
after playing around with
myObj's dictionary, it seems I can't have the 'value' recognized as a
method object or instance attribute,
depending on the context. What's worse is that I can't modify the
MyObject code so I can rename, say,
the value attribute. Anybody encounter this sort of problem before and
manage to solve it within
Jython?
-Terry | http://sourceforge.net/p/jython/mailman/message/11764063/ | CC-MAIN-2015-27 | refinedweb | 243 | 50.06 |
How Fast is Spring?
Performance has always been one of the top priorities of the Spring Engineering team, and we are continually monitoring and responding to changes and to feedback. Some fairly intense and precise work has been done recently (in the last 2-3 years) and this article is here to help you to find the results of that work and to learn how to measure and improve performance in your own applications. The headline is that Spring Boot 2.1 and Spring 5.1 have some quite nice optimizations for startup time and heap usage. Here’s a graph made by measuring startup time for heap constrained apps:
As you squeeze the available heap, and application generally isn’t affected on startup, until it reaches a critical point. The characteristic "hockey stick" shape of the graphs shows the point at which garbage collection loses the fight and the app no longer starts up at all. We see from the graphs that it is quite possible to run a simple Netty app in 10MB heap with Spring Boot 2.1 (but not with 2.0). It is also a bit faster in 2.1 compared to 2.0.
Most of the detail here refers specifically to measurements and optimizations for startup time, but heap memory consumption is also something that is very relevant because constraints on heap size generally lead to slower startup (see the graph above). There are other aspects of performance that we could (and will) focus on, particularly where annotations are being used for HTTP request mapping, for example; but those concerns will have to wait for another, separate write up.
When all things are considered, remember that Spring was designed ab initio to be lightweight, and actually does very little work unless you ask it to. There are many optional features, so you don’t have to use them. Here are some quick summary points:
Packaging: an exploded jar with the application’s own main is always faster
Server: there is no measureable difference between Tomcat, Jetty and Undertow
Netty is a bit faster on startup - you won’t notice in a large app
The more features you use, the more classes are loaded
Functional bean definitions provide an incremental improvement
A minimal Spring Boot app with an HTTP endpoint starts in <1sec and uses <10MB heap
Some links: - older benchmarks (back to Spring Boot 1.3), fat jar data
/static benchmarks in the same repo - newer, explores classes loaded correlation
/flux benchmarks in the same repo - WebFlux - blog on functional beans in Spring Cloud Function
Spring Fu: - benchmarks for functional beans and GC pressure - functional beans and AOT (same code as the "allocations" project but sample apps not benchmarks)
TL;DR How do I make my app go faster?
(Copied from here.) You are mostly going to have to drop features, so not all of these suggestions will be possible for all apps. Some are not so painful, and actually pretty natural in a container, e.g. if you are building a docker image it’s better to unpack the jar and put application classes in a different filesystem layer anyway.
Classpath exclusions from Spring Boot web starters:
Hibernate Validator
Jackson (but Spring Boot actuators depend on it). Use Gson if you need JSON rendering (only works with MVC out of the box).
Logback: use
slf4j-jdk14instead
Use the
spring-context-indexer. It’s not going to add much, but every little helps.
Don’t use actuators if you can afford not to.
Use Spring Boot 2.1 and Spring 5.1. Switch to 2.2 and 5.2 when they are available.
Fix the location of the Spring Boot config file(s) with
spring.config.location(command line argument or System property etc.). Example for testing in IDE:
spring.config.location=.
Switch off JMX if you don’t need it with
spring.jmx.enabled=false(this is the default in Spring Boot 2.2)
Make bean definitions lazy by default. There’s a new flag
spring.main.lazy-initialization=truein Spring Boot 2.2 (and there’s a
LazyInitBeanFactoryPostProcessorin this project you can copy).
Unpack the fat jar and run with an explicit classpath.
Run the JVM with
-noverify. Also consider
-XX:TieredStopAtLevel=1(that will slow down the JIT later at the expense of the saved startup time).
A more extreme choice is to re-write all your application configuration using functional bean definitions. This includes all the Spring Boot autoconfiguration you are using, most of which can be re-used, but it’s stll manual work to identify which classes to use and register all the bean definitions. If you try this approach you might see a 2x improvement in startup time, but not all of that will be because of the functional bean definitions (estimates usually end up in the range of 10% startup time premium for functional beans, but there may be other benefits). Look at the
BuncApplication in the micro apps to see how to start Spring Boot without the
@Configuration class processor.
Excluding
netty-transport-native-epoll also boosts the startup time by 30ms or so (Linux only). This is a regression since Spring Boot 2.0, so once we understand it a bit better we can probably eliminate it.
Some Basic Benchmarks
Here is a subset of the static benchmarks from. Each app is started with a new JVM (separate process) per application startup, and has an explicit classpath (not fat jar). The app is always the same, but with different levels of automatic (and in some cases manual) configuration. The "Score" is startup time in seconds, measured as the time from starting the JVM to seeing a marker in the logger output (at this point the app is up and accepting HTTP connections).
Benchmark (sample) Mode Cnt Score Error Units Beans Classes MainBenchmark actr avgt 10 1.316 ± 0.060 s/op 186 5666 MainBenchmark jdbc avgt 10 1.237 ± 0.050 s/op 147 5625 MainBenchmark demo avgt 10 1.056 ± 0.040 s/op 111 5266 MainBenchmark slim avgt 10 1.003 ± 0.011 s/op 105 5208 MainBenchmark thin avgt 10 0.855 ± 0.028 s/op 60 4892 MainBenchmark lite avgt 10 0.694 ± 0.015 s/op 30 4580 MainBenchmark func avgt 10 0.652 ± 0.017 s/op 25 4378
Actr: same as "demo" sample plus Actuator
Jdbc: same as "demo" sample plus JDBC
Demo: vanilla Spring Boot MVC app with one endpoint (no Actuator)
Slim: same thing but explicitly
@Importsall configuration
Thin: reduce the
@Importsdown to a set of 4 that are needed for the endpoint
Lite: copy the imports from "thin" and make them into hard-coded, unconditional configuration
Func: extract the configuration methods from "lite" and register bits of it using the function bean API
Generally speaking, the more features are used, the more classes that are loaded, and also the more beans are created in the
ApplicationContext. The correlation is actually very tight between startup time and number of classes loaded (much tighter than versus number of beans). Here’s a graph compiled from that data and extended with a range of other things, like JPA, bits of Spring Cloud, all the way up to the "kitchen sink" with everything on the classpath including Zuul and Sleuth:
The data for the graph can be scraped from the benchmark report if you run the "MainBenchmark" and the "StripBenchmark" in the static benchmarks (the table above is old data from a time when they were both in the same class). There are instructions about how to do that in the README.
Garbage Collection Pressure
While it is true, and measureable, that more classes loaded (i.e. more features) is directly correlated with slower startup time, there are some subtleties, and one of the most important and also the slipperiest to analyse is garbage collection (GC). Garbage collection can be a really big deal for long running applications, and we have all heard stories of long GC pauses in large applications (the bigger your heap the longer you are likely to wait). Custom GC strategies are big business and an important tool for tweaking long-running, especially large applications. On startup there are some other things happening, but those can be related to garbage collection as well, and many of the optimizations in Spring 5.1 and Spring Boot 2.1 were obtained by analysing those.
The main thing to look out for is tight loops with temporary objects being created and discarded. Some code in that pattern is unavoidable, and some is out of our control (e.g. it’s in the JDK itself), and all we can do in that case is try not to call it. But these hordes of temporary objects create pressure on garbage collection and swell the heap, even if they never actually make it onto the heap per se. You can often see the effect of the extra GC pressure as a spike in heap size, if you can catch it happening. Flame graphs from async-profiler are a better tool because they are allow more fine-grained sampling than most profiling tools, and because they are visually very striking.
Here’s an example flame graph from the HTTP sample app we have been benchmarking, with Spring Boot 2.0 and with Spring Boot 2.1:
The red/brown GC flame on the right is noticeably smaller in Spring Boot 2.1. This is a sign of less GC pressure as a result of a change in the bean factory internals. The Spring Framework issue behind one of the main changes is here if you want to look at the details.
Recognizing that GC pressure is an issue is one thing (and async-profiler is the best tool we have found), but locating its source is something of an art. The best tool we have found for that is Flight Recorder (or Java Mission Control) which is part of the OpenJDK release, although it used to be only in the Oracle distribution. The problem with Flight Recorder is that the sampling rate is not really high enough to capture enough data on startup, so you have to try and build tight loops that do something you are interested in, or suspect might be contributing to the problem, and analyse those over a longer period (a few seconds or more). This leads to additional insight, but no real data on whether a "real" application will benefit from changing the hotspot. Much of the code in the spring-boot-allocations project is this kind of code: main methods that run tight loops focusing on suspected hotspots that can then be analyzed with Flight Controller.
WebFlux and Micro Apps
We might expect some variations between apps using a Servlet container and those using the newer reactive runtime from Netty introduced in Spring 5.0. The benchmark figures above are using Tomcat. There are some similar measurements in a different subdirectory of the same repo. Here are the results from the flux benchmarks:
Benchmark (sample) Mode Cnt Score Error Units Classes MainBenchmark.main demo ss 10 1.081 ± 0.075 s/op 5779 MainBenchmark.main jlog ss 10 0.933 ± 0.065 s/op 4367 MiniBenchmark.boot demo ss 10 0.579 ± 0.041 s/op 4138 MiniBenchmark.boot jlog ss 10 0.486 ± 0.020 s/op 2974 MiniBenchmark.mini demo ss 10 0.538 ± 0.009 s/op 3138 MiniBenchmark.mini jlog ss 10 0.420 ± 0.011 s/op 2351 MiniBenchmark.micro demo ss 10 0.288 ± 0.006 s/op 2112 MiniBenchmark.micro jlog ss 10 0.186 ± 0.006 s/op 1371
All the apps have a single HTTP endpoint, just like the apps in the static benchmarks (Tomcat, Servlet). All are a bit faster than Tomcat, but not much (maybe 10%). Note that the fastest one ("micro jlog") is up and running in less than 200ms. Spring is really not doing very much there, and all the cost is basically getting the classes loaded for the features needed by the app (an HTTP server).
Notes:
The
MainBenchmark.main(demo)is full Boot + Webflux + autoconfiguration.
The
bootsamples use Spring Boot but no autoconfiguration.
The
jlogsamples exclude logback as well as Hibernate Validator and Jackson.
The
minisamples do not use Spring Boot (just
@EnableWebFlux).
The
microsamples do not use
@EnableWebfluxeither, just a manual route registration.
The mini jlog sample runs in about 46MB memory (10 heap, 36 non-heap). The micro jlog sample runs in 38MB (8 heap, 30 non-heap). Non-heap is really what matters for these smaller apps. They are all included on the scatter plot above, so they are consistent with the general correlation between startup time and classes loaded.
Classpath Exclusions
Your mileage my vary, but consider excluding:
Jackson (
spring-boot-starter-json): it’s not super expensive (maybe 50ms on startup), but Gson is faster, and also has a smaller footprint.
Logback (
spring-boot-starter-logging): still the best, most flexible logging library, but all that flexibility comes with a cost.
Hibernate Validator (
org.hibernate.validator:hibernate-validator): does a lot of work on startup, so if you are not using it, exclude it.
Actuators (
spring-boot-starter-actuator): a really useful feature set, so hard to recommend removing it completely, but if you aren’t using it, don’t put it on the classpath.
Spring Tweaks
Use the
spring-context-indexer. It’s a drop in on the classpath, so very easy to install. It only works on your application’s own
@Componentclasses, and really only likely to be a very small boost to startup time for all but the largest (1000s beans) applications. But it is measureable.
Don’t use actuators if you can afford not to.
Use Spring Boot 2.1 and Spring 5.1. Both have small, but important optimizations, especially regarding garbage collection pressure on startup. This is what enables newer apps to start up with less heap.
Use explicit
spring.config.location. Spring Boot looks in quite a lot of locations for
application.properties(or
.yml), so if you know exactly where it is, or might be at runtime, you can shave off a few percent.
Switch off JMX:
spring.jmx.enabled=false. If you aren’t using it you don’t need to pay the cost of creating and registering the MBeans.
Make bean definitions lazy by default. There’s nothing in Spring Boot that does this, but there’s a
LazyInitBeanFactoryPostProcessorin this project you can copy. It is just a
BeanFactoryPostProcessorthat switches all beans to
lazy=true.
Spring Data has some lazy initialization features now (in Lovelace, or Spring Boot 2.1). In Spring Boot you can just set
spring.data.jpa.repositories.bootstrap-mode=lazy- for large apps with 100s of entities improves startup time by more than a factor of 10.
Use functional bean definitions instead of
@Configuration. More detail later on this.
JVM Tweaks
Useful command line tweaks for startup time:
-noverify- pretty much harmless, has a big impact. Might not be permitted in a low trust environment.
-XX:TieredStopAtLevel=1- potentially degrades performance later, after startup, since it restricts the JVM ability to optimize itself at runtime. Your mileage my vary but it will have a measureable impact on startup time.
-Djava.security.egd=file:/dev/./urandom- not really a thing any more, but older versions of Tomcat used to really need it. Might have a small effect on modern apps with or without Tomcat if anyone is using random numbers.
-XX:+AlwaysPreTouch- small but possibly measurable effect on startup.
Use an explicit classpath - i.e. explode the fat jar and use
java -cp …. Use the application’s native main class. More detail on this later.
Class Data Sharing
Class Data Sharing (CDS) was a commercial only feature of the Oracle JDK since version 7, but it has also available in OpenJ9 (the open source version of the IBM JVM) and now in OpenJDK since version 10. OpenJ9 has had CDS for a long time, and it is super easy to use in that platform. It was designed for optimizing memory usage, not startup time, but those two concerns are not unrelated.
You can run OpenJ9 in the same way as a regular OpenJDK JVM, but the CDS is switched on with different command line flags. It’s super convenient with OpenJ9 because all you need is
-Xshareclasses. It’s probably also a good idea to increase the size of the cache, e.g.
-Xscmx128m, and to hint that you want a fast startup with
-Xquickstart. These flags are always on in the benchmarks if they detect the OpenJ9 or IBM JVM.
Benchmark results with OpenJ9 and CDS:
Benchmark (sample) Mode Cnt Score Error Units Classes MainBenchmark.main demo ss 10 0.939 ± 0.027 s/op 5954 MainBenchmark.main jlog ss 10 0.709 ± 0.034 s/op 4536 MiniBenchmark.boot demo ss 10 0.505 ± 0.035 s/op 4314 MiniBenchmark.boot jlog ss 10 0.406 ± 0.085 s/op 3090 MiniBenchmark.mini demo ss 10 0.432 ± 0.019 s/op 3256 MiniBenchmark.mini jlog ss 10 0.340 ± 0.018 s/op 2427 MiniBenchmark.micro demo ss 10 0.204 ± 0.019 s/op 2238 MiniBenchmark.micro jlog ss 10 0.152 ± 0.045 s/op 1436
That is quite impressive in some cases (25% faster than without CDS for the fastest apps). Similar results can be achieved with OpenJDK: includes CDS (with a less convenient command line interface) since Java 10. Here’s a scatter plot of the smaller end of the classes loaded versus startup time relationship, with regular OpenJDK (no CDS) in red and OpenJ9 (with CDS) in blue:
Java 10 and 11 also have an experimental feature called Ahead of Time compilation (AOT) that lets you build a native image from a Java application. Potentially this is super fast on startup, and most apps that can successfully be converted are indeed very fast to start up (by a factor of 10 for the small apps in the benchmarks here). Many "real life" applications cannot yet be converted. AOT is implemented using Graal VM, which we will come back to later.
Lazy Subsystems
We mentioned lazy bean definitions and the idea of a
LazyInitBeanFactoryPostProcessor being generally of interest above. The benefits are clear, especially for a Spring Boot application with lots of autoconfigured beasn that you never uese, but also limited because even if you don’t use them sometimes they needto be created to satisfy a dependency. Those limitations could possibly be addressed by another idea that is more of a research topic, and that is to break down application into modules and initialize each one separately on demand.
To do this you would need to be able to precisely identify a subsystem in your source code and mark it somehow. An example of such a subsystem would be the actuators in Spring Boot, which we can identify mainly by the package names of the auto configuration classes. There is a prototype in this project: Lazy Actuator. You can just add it to an existing project and it converts all the actuator endpoints into lazy beans which will only be instantiated when they are used, saving about 40% of the startup time in a micro application like the canonical one-endpoint HTTP sample app in the benchmarks above. E.g. (for Maven):
<dependency> <groupId>org.springframework.boot.experimental</groupId> <artifactId>spring-boot-lazy-actuator</artifactId> <version>1.0.0.BUILD-SNAPSHOT</version> </dependency>
To make this kind of pattern more mainstream would probably take some changes in the core Spring programming model, to allow the subsystems to be identified and dealt with in special ways at runtime. It also increases the complexity of an application, which might not really be worth it in a lot of cases - one of the best features of Spring Boot is the simplicity of the application context (all beans are created equal). So this remains an area of active research.
Functional Bean Definitions
Functional bean registration is a feature added to Spring 5.0, in the form of a few new methods in
BeanDefinitionBuilder and some convenience methods in
GenericApplicationContext. It allows for completely non-reflective creation of components by Spring, by attaching a
Supplier to a
BeanDefinition, instead of a
Class.
The programming model is a little bit different than the most popular
@Configuration style, but it still has the same goal: to extract configuration logic into separate resources, and allow the logic to be implemented in Java. If you had a configuration class like this:
@Configuration public class SampleConfiguration { @Bean public Foo foo() { return new Foo(); } @Bean public Bar bar(Foo foo) { return new Bar(foo); } }
You could convert it to functional style like this:
public class SampleConfiguration implements ApplicationContextInitializer<GenericApplicationContext> { public Foo foo() { return new Foo(); } public Bar bar(Foo foo) { return new Bar(foo); } @Override public void initialize(GenericApplicationContext context) { context.registerBean(SampleConfiguration.class, () -> this); context.registerBean(Foo.class, () -> context.getBean(SampleConfiguration.class).foo()); context.registerBean(Bar.class, () -> context.getBean(SampleConfiguration.class) .bar(context.getBean(Foo.class))); } }
There are multiple options for where to make these
registerBean() method calls, but here we have chosen to show them wrapped in an
ApplicationContextInitializer. The
ApplicationContextInitializer is a core framework interface, but it has a special place in Spring Boot because a
SpringApplication can be loaded up with initializers through its public API, or by declaring them in
META-INF/spring.factories. The
spring.factories approach is one that easily allows the application and its integration tests (using
@SpringBootTest) to share the same configuration.
This programming model is not yet mainstream in Spring Boot applications, but it has been implemented in Spring Cloud Function and is also a basic building block in Spring Fu. Also the fastest full Spring Boot benchmark apps above ("bunc") are implemented this way. The main reason for this is that functional bean registration is the fastest way for Spring to create bean instances - it requires virtually no computation beyond instantiating a class and calling its constructors natively.
The existing functional bean implementations in libraries and apps had to manually copy quite a bit of code from Spring Boot, and convert it to the functional style. For small applications this might be practical, but the more features from Spring Boot you use, the less convenient it will be. Recognizing this we have started work on various tools that could be used to automatically convert
@Configuration to
ApplicationContextInitializer code. You can do it at runtime with reflection, and this turns out to be surprisingly fast (proving that not all reflection is bad), or you could do it at compile time, which promises to be optimal in turns of start up time but is technically a little bit harder to implement.
The Future applications. There are still optimizations to be made in the core framework, as well as in Spring Boot probably. Keep an eye out on the Spring Blog for more new research and new releases, and more topical analysis of performance hotspots and tweaks you can make to avoid them. | https://spring.io/blog/2018/12/12/how-fast-is-spring | CC-MAIN-2020-50 | refinedweb | 3,866 | 63.39 |
repose - a RESTful django framework
Why repose? Why another framework?
This is not the first time I've written a framework for creating a RESTful interface from django. The first attempt, called rest_api was modelled on the django admin interface (django.contrib.admin), and was used in a work project extensively.
There were lots of bits I didn't like about it. Some of this I didn't even realize until I came across django-rest-framework: which uses django forms for validation.
I decided to take this even further.
Repose is a form-based rest-api framework.
That is, the intention is that you will use django's forms to create and render your views, even if they are JSON or XML.
Installation
You'll want to install repose into your virtualenv.
Usage
Repose uses the django class-based-views structure. In fact, the views within repose all inherit from django.views.generic.View.
Repose provides a handful of pre-built views, but the general idea is that you will probably want to sub-class them.
The simplest way to use a repose view is to install it in your urls.py as follows:
from repose.views import ModelDetailView from models import ModelName urlpatterns = patterns('', url(r'^path/$', ModelDetailView.as_view(model=ModelName), name="modelname_detail"), )
This will automatically create a ModelForm (which also includes the 'id' field, allowing the client to know about relationships without having to embed them).
You can supply your own Form, and/or View classes:
from repose.views import ModelDetailView from models import ModelName from forms import ModelNameForm class ModelNameView(ModelDetailView): form = ModelNameForm
You may also override some specific methods in your View class to change behaviour. The most common is likely to be get_queryset, which enables you you change which subset of objects request.user is able to access. For the detail view classes, you can also override get_object.
There are some useful Mixins that do this type of thing in mixins.py | https://bitbucket.org/schinckel/django-repose/src/6843241b295b?at=0.2.2 | CC-MAIN-2015-35 | refinedweb | 328 | 58.89 |
Catharsis is a complete framework for developing web applications. The question is, has she (Catharsis) something essentially better than others, what could promote her to an everyday usage? Answer must come from you.
All source code can be found here.
Latest stories about the Catharsis framework you can find:
David O'Sullivan will guide you through
You will touch all the fundaments which Catharsis architecture provides. These pieces than allow you easy and fast own development and application extending.
Enjoy these new stories. Thanks David.
Catharsis 1.2 - 9.6.2009: see below
ASP.NET MVC 1.0, NHibernate 2.1. BETA 1
After two month after first release I've realized, that there are still some gaps in the
MVC design pattern understanding. If you would like to get another view on
MVC, to see some comparison with
MVP and that all in the world of
ASP.NET MVC and mainly how it works in
Catharsis framework Architecture - try to follow this link. This description is intended as a support for Catharsis, not as an academic and only valid explanation...
ASP.NET Web form pages are dead, or at least out of the date. Do you really know all of the 23 (or how many) page life-time events? And do You need all of them?
Even in Microsoft they realized, that ASP.NET need a big change and purification (in Greek 'purification' == 'Catharsis') The result is
ASP.NET MVC, the lightweight of web-forms with everything you need and lot of new features, which can change your way of thinking about request and response (and url-routing is really a very small piece of that wonderful puzzle called
MVC).
Among other problems in Microsoft world of web-forms, there is depression of the OOP programming, caused mainly with
DataSets,
DataTables,
DataAdapters ...
How could you think in object, if
DataTable generated by designer has thousands of rows of code, which you cannot change, but above all: you cannot derive from
DataTable! is this an OBJECT? And did you ever tried to create lte’s say object called
User with property
CurrentRole and property collection
Roles using DataTables? (
DataSet with related tables? Magically connected by relations? No ability to use auto identity for inserting ...) Get out of here. Now.
NHiberante 2.0 (even 1.2) can correct your sad ideas, because of narrowing the OOP world. And maybe it also can improve your designing habits when working with relational-database. Inheritance, polymorphism ... and fancy lazy mode (it’s not OOP but how effective)
Well, we have ASP.NET MVC (today Preview 5) and NHibernate 2.0 (final) and lot of good practices known. The missing part is the pot, which will allow us mix it and prepare delicious meal for our users.
I do believe, that this article will have many descendants. So, do not waste time and place and just briefly about Catharsis: She is the 'Web-Application Framework' gathering best-practices... based on ASP.NET MVC, NHibernate 2.0.
Catharsis has real multi-tier architecture, with a separating of concern as the framework essence.
Catharsis is strongly OOP! Using 1) inheritance as a key feature for code reuse and 2) polymorphisms as the only way to communicate among layers (objects are working with interfaces! without knowing who is implementing them)
Powerful features are:
CurrentRoleproperty (user has roles but access is evaluated only against currently selected role).
.resx) with ability to add new languages on the run!
For all of that Catharsis has a Guidance. Every needed piece of code you'll find on. When you'll see it, you will never use anything else to generate Word or Excel files directly from your web application!
MVC - I do expect that you are well oriented in
ASP.NET MVC. Wonderful place to start is and you should have seen all videos from Scott Hanselman – not they are really cool, but first of all they are very clear and nice to understand.
Current version used in Catharsis is
ASP.NET MVC 1.0
NHibernate – I do expect you are familiar with
NHibernate 2.1 (BETA 1 - LinFu proxies). The nice place to start is (or examining Catharsis code)
Before you can start using Cathrasis.Guidance you have to install:
And finally you can choose to install
Catharsis.Guidanceas MSI (probably preferred way)
Catharsis.Guidancesolution, Open it, click on a project Guidance, select register.
From the version 0.9.1 there is The 'ProjectBase' namespace instead of 'Catharsis'. The aim is clear - to quickly start to use Catharsis framework in your company ...
Finally I suggest you install provided SQL scripts (create tables and insert few objects) or restore backup. It will allow us run solution very quickly. Scripts are needed for new solution (they create infrastructural tables). If you are running example, then you should use backup
(Source codes and MSI are available here.)
If you have installed all needed stuff, let's start with a new solution.
Open Visual Studio 2008 and select Create new project. In the menu you can see now item: Guidance, which contains one solution - Catharsis.
Name new solution like '
YourCompany.Product' for example and create it. On the wizard screen you can change some settings, important is connection string.
When you click finish,
Catharsis.Guidance will create new solution with all needed layers, referenced libraries and needed classes to handle roles, users, localization ...
If you've created Database as mentioned above, and provided correct connection string in a setup of a new solution, you should be very near to a first run of your new Web application.
Select '
Firm.Product.Web' project as startup and Default.aspx is as startup page and press F5...
If everything went right, you should see the HomePage screen:
I have to say, that MVC native solution for web controls is not well designed.
HtmlHelper as the extension method for creating anchors, inputs etc. is simply bad solution. I would like to give you another point of view: Take a look at this article,
,and you'll see how easy it is to correctly manage web controls even in the MVC world
I’d like to point out one fundamental thing on Catharsis, which (when I went through all my articles) was not said. Firstly I do not accept everything what’s coming on the market (even open source one) until I do play with it and feel friendly. (The example of bad experience for me was ‘Linq to Entities’ which I was looking forward as a child).
The pillar of Catharsis, I must mention, is Microsoft .NET C# 3.5! From my point of view and experience the C# is at the moment leading OOP programming language. Anything you need is there and lot of features extends the ability of day to day coding.
The last missing thing in C# is multiple inheritances (but as I heard rumors it will be changed). Despite of that fact the Extensions methods at current version can do lot of useful job. And also LINQ itself as the part of .NET 3.5 brings tremendous simplification. I think that it must be written: MS C# .NET 3.5 is precious diamond! I am looking forward .NET 4.0 as a child …
In a next part we will examine the Homepage, and the built-in stuff.
Enjoy Catharsis.
Catharsis 1.0.1
Catharsis 0.9.5 was released 10.12.2008
Enjoy Catharsis.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/applications/Catharsis.aspx | crawl-002 | refinedweb | 1,246 | 67.55 |
Alexander Graf wrote: > > On 24.07.2009, at 12:59, Jan Kiszka wrote: > >> Alexander Graf wrote: >>> When talking to the kernel about dirty maps, we need to find out which >>> bits were actually set. This is done by set_bit and test_bit like >>> functiontality which uses the "long" variable type. >>> >>> Now, with PPC32 userspace and PPC64 kernel space (which is pretty >>> common), >>> we can't interpret the bits properly anymore, because we think long is >>> 32 bits wide. >>> >>> So for PPC dirty bitmap analysis, let's just assume we're always running >>> on a PPC64 host. Currently there is no dirty bitmap implementation for >>> PPC32 / PPCEMB anyways. >>> >>> Unbreaks dirty logging on PPC. >>> >>> Signed-off-by: Alexander Graf <address@hidden> >>> --- >>> kvm-all.c | 6 ++++++ >>> 1 files changed, 6 insertions(+), 0 deletions(-) >>> >>> diff --git a/kvm-all.c b/kvm-all.c >>> index 824bb4c..bfaa623 100644 >>> --- a/kvm-all.c >>> +++ b/kvm-all.c >>> @@ -357,7 +357,13 @@ int >>> kvm_physical_sync_dirty_bitmap(target_phys_addr_t start_addr, >>> for (phys_addr = mem->start_addr, addr = mem->phys_offset; >>> phys_addr < mem->start_addr + mem->memory_size; >>> phys_addr += TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) { >>> +#ifdef HOST_PPC >>> + /* Big endian keeps us from having different long sizes >>> in user and >>> + * kernel space, so assume we're always on ppc64. */ >>> + uint64_t *bitmap = (uint64_t *)d.dirty_bitmap; >>> +#else >>> unsigned long *bitmap = (unsigned long *)d.dirty_bitmap; >>> +#endif >>> unsigned nr = (phys_addr - mem->start_addr) >> >>> TARGET_PAGE_BITS; >>> unsigned word = nr / (sizeof(*bitmap) * 8); >>> unsigned bit = nr % (sizeof(*bitmap) * 8); >> >> This rather screams for a generic fix. Current code assumes >> sizeof(unsigned long) == 8. That should already break on 32-bit x86 >> hosts. So either do (sizeof(*bitmap) * sizeof(unsigned long)) or switch >> to uint64_t - but for ALL hosts. > > I don't see where that would break. The kernel treats the array as > ulong*, userspace treats it as ulong* and set_bit in kernel does > bitmap[word] |= (1 << bit). So as long as userspace long and kernel long > are the same, it works. > > In fact - it should even work out with little endian and different ulong > sizes. It just breaks on BE. Err, yes, forget it. But let's help me understanding the actual problem: Do you have different ulong sizes in your scenario? Why? Is it a compat issue of 32-bit userland on 64-bit kernel? Jan -- Siemens AG, Corporate Technology, CT SE 2 Corporate Competence Center Embedded Linux | http://lists.gnu.org/archive/html/qemu-devel/2009-07/msg01892.html | CC-MAIN-2015-32 | refinedweb | 380 | 67.35 |
Hi there, I’m new to rails and loving it, but I’ve hit a problem that
I’m hoping to find an elegant solution for. I’ve been trawling thru
this list and the wiki, but can’t quite find the last piece to the
problem I’m trying to solve.
I’m trying to setup a simple Polling app, you know, posing questions and
voting on answers. So far i have something (this is trimmed down) like:
class Question < ActiveRecord::Base
has_and_belongs_to_many :answers
has_and_belongs_to_many :votes
belongs_to :person
end
class Answer < ActiveRecord::Base
has_and_belongs_to_many :votes, :join_table => ‘questions_votes’
end
class Vote < ActiveRecord::Base
belongs_to :person
has_and_belongs_to_many :answers, :join_table => ‘questions_votes’
has_and_belongs_to_many :questions, :join_table => ‘questions_votes’
end
With the following associated join table:
CREATE TABLE questions_votes (
question_id INTEGER,
answer_id INTEGER,
vote_id INTEGER
)
The above allows me to perform the following:
q = Question.find_first
a = q.answers.find_first
v = a.votes
But, if i try and go the other way, from a vote back to an answer, or
from and answer back to a question, I am passed back an array. i.e.
v.questions or v.answers or a.questions are all valid.
But what i really want is the singular of the aboves, i know i could use
find_first, but that really shouldn’t be necessary. I understand why
this is happening, due to the HABTM relationship.
I’ve tried using belongs_to in the child classes, which works fine, i.e.
class Answer < ActiveRecord::Base
belongs_to :question
has_and_belongs_to_many :votes, :join_table => ‘questions_votes’
end
But I’m then duplicating the foreign keys, which also doesn’t quite seem
the most elegant approach either. given that the relationship already
exists in the join table. Would i just be better off creating a new
method on the child classes, something like:
class Answer < ActiveRecord::Base
has_and_belongs_to_many :votes, :join_table => ‘questions_votes’
def find_question
self.questions.find_first
end
end
It still seems like a kludge, and that the model isn’t quite
representing that data in an accurate manner.
Can you suggest a better way of achieving the above? I’m probably
missing something really obvious here. Maybe i just need to create a
new
Model for the relationships?
-vince
–
keys:
This country, with its institutions, belongs to the people who inhabit
it.
Whenever they shall grow weary of the existing government,
they can exercise their constitutional right of amending it,
or exercise their revolutionary right to overthrow it.
– Abraham Lincoln | https://www.ruby-forum.com/t/habtm-questions-answers-and-votes/49001 | CC-MAIN-2019-51 | refinedweb | 402 | 54.22 |
Zen Forms
Forms permit the user to enter data. A Zen control is a component that displays application data and allows the user to edit this data. A Zen form is a specialized group component designed to contain control components. Zen forms have the same style and layout attributes as any Zen group. Also, because they are groups, forms may contain any other type of Zen component.
Like all Zen components, a Zen form must be the child of a Zen page object. This means that if you want to provide a form for a Zen application, you must create a Zen page class that includes a form component inside the <page> container. Two components are available:
“<form>” — A Zen group that contains a specific list of control components. These controls may or may not take their values from a data controller, but their layout is entirely determined by the <form> definition in XData Contents.
“<dynaForm>” — An extension of <form> that dynamically injects control components into a group (or groups) on the Zen page. The list of controls may be determined by the properties of an associated data controller, or by a callback method that generates a list of controls. Layout is automatic, determined by code internal to the <dynaForm>.
There is a Studio tutorial that uses Zen wizards to create a form-based user interface for a simple application. See the chapter “Building a Simple Application with Studio” in the book Using Studio.
For information about data controllers, see the chapter “Model View Controller.”
Chapter topics incluide:
“Forms and Controls”
“User Interactions”
“Defining a Form”
“Providing Values for a Form”
“Detecting Modifications to the Form”
“Validating a Form”
“Errors and Invalid Values”
“User Login Forms”
“Dynamic Forms”
Forms and Controls
The Zen library includes a number of controls for use in forms. Many of these controls are wrappers for the standard HTML controls, while others offer additional functionality. The following figure displays a form that contains a number of controls, including text fields and radio buttons. This is the sample form generated by the class ZENDemo.FormDemo in the SAMPLES namespace.
The following figure lists the form and control components that Zen provides. Most of the classes shown in the figure are controls. All of the classes shown in the diagram are in the package %ZEN.Component, for example %ZEN.Component.form and %ZEN.Component.control. The diagram shows the inheritance relationships for these classes, and highlights the base classes most frequently discussed in this book.
For details about individual controls, see the chapter “Zen Controls.”
User Interactions
The basic interaction between a Zen application user and a Zen form is as follows:
A user interacts with controls on the form
Zen may validate the data as it is entered
A user action indicates that it is time to submit the form
Zen may validate the data prior to attempting the submit
Zen interacts with the user to handle any errors it finds
When all is well, Zen submits data from the form
Any of the following might happen next:
Data from the form may be written to the server
The same Zen page may redisplay
A different Zen page may display
The same Zen page may display, but with components added or changed
Defining a Form
The Zen components “<form>” and “<dynaForm>” each support the following attributes for defining the characteristics of a form.
The OnLoadForm method retrieves the values that appear on the form when it first displays. It can get values from the object whose model ID is provided by the key attribute for the form, or it can assign literal values. The method must then place these values into the input array, subscripted by the name attribute for the corresponding control on the form. It is this name (and not the id) that associates a control with a value. Zen invokes this method when it first draws the form, automatically passing it the following parameters:
The callback must return a %Status data type. The following example shows a valid method signature and use of parameters:
Method LoadForm(pKey As %String, ByRef pValues As %String) As %Status { Set emp = ##class(ZENDemo.Data.Employee).%OpenId(pKey) If ($IsObject(emp)) { Set pValues("ID") = emp.%Id() Set pValues("Name") = emp.Name Set pValues("SSN") = emp.SSN } Quit $$$OK }
To use the above method as the callback, the developer would set OnLoadForm="LoadForm" for the <form> or <dynaForm>.
Providing Values for a Form
A form can initially display with blank fields, or you can provide data for some of the fields. Providing data for a field that the user sees means setting the value property for the associated Zen control component, before you ask Zen to display the form. There are several ways to do this:
Set the value attribute while adding each control to XData Contents.
<text value="hello"/>
Set the onLoadForm attribute while adding the form to XData Contents.
<form id="MyForm" OnLoadForm="LoadForm">
Set value properties from the page’s %OnAfterCreatePage method.
Do ..%SetValueById("Doctor",$G(^formTest("Doctor")))
On the client side, call the setValue method for each control.
Presumably, once the user begins editing the form, any initial values may change.
Detecting Modifications to the Form
A Zen form component tracks whether or not changes have occurred in any control on the form. %ZEN.Component.form and %ZEN.Component.control each offers a client-side method called isModified that tests this programmatically.
A control’s isModified method returns true if the current logical value of the control (the value property) is different from its original logical value (the originalValue property). With each successive submit operation, the originalValue for each control acquires its previous value, so that this answer is always current with respect to the current state of the form.
When you call a form’s isModified method, it invokes isModified for each control on the form, and if any control returns true, isModified returns true for the form.
The <textarea> control returns an accurate isModified status when it contains fewer than 50 characters. When the <textarea> value contains 50 characters or more, the control does not compute an isModified status.
Validating a Form
Each Zen form has a validate method whose purpose is to validate the values of controls on the form. If the form’s autoValidate property is true, validate is called automatically each time the form is submitted. Otherwise, validate may be called explicitly by the application. validate does the following:
Calls a form-specific onvalidate event handler, if defined. If this event returns false, Zen declares the form invalid and no further testing occurs.
Resets the invalid property of all the form’s controls to false, then tests each control by calling the control’s validationHandler method. This method, in turn, does the following:
If the control’s readOnly or disabled properties are true, return true.
If the control’s required property is true and the control does not have a value (its value is ""), return false.
If the control defines an onvalidate event, execute it and returns its value. Otherwise, call the control’s isValid method. isValid can be overridden by subclasses that wish to provide built-in validation (such as the dateText control).
As the validate method tests each control, the form builds a local array of invalid controls.
After the validate method is finished testing the controls, it returns true if the form is valid.
If the form contains one or more controls with invalid values, it is invalid. validate performs one of the following additional steps to handle this case:
If the form defines an oninvalid event handler:
Execute the handler. This provides the form with a chance to handle the error conditions. The value returned by the oninvalid event is then returned by the form’s validate method. The oninvalid handler has an argument named invalidList that receives a JavaScript array containing the list of invalid controls. For example:
<form oninvalid="return zenPage.formInvalid(zenThis,invalidList);" />Copy code to clipboard
Where the formInvalid method looks like this:
ClientMethod formInvalid(form,list) [ Language = javascript ] { return false; }Copy code to clipboard
When the form has no oninvalid event handler:
validate sets the invalid property to true for each invalid control (which changes their style to zenInvalid); gives focus to the first invalid control; and displays an error message within an alert box. The message displayed in the alert box is built from a combination of the form’s invalidMessage property along with the value returned from each invalid control’s getInvalidReason method.
It is standard practice not to invoke validation logic for null values.
Errors and Invalid Values
Should an error occur while a form is being submitted, or should the form fail validation, Zen redisplays the page containing the form. The user has the opportunity to re-enter any incorrect values and submit the page again. All of this is extremely easy to set up when adding the <form> or <dynaForm> component to the Zen page.
The SAMPLES namespace class ZENTest.FormTest allows you to experience error handling with Zen forms as follows:
Start your browser.
Enter this URI:
Where 57772 is the web server port number that you have assigned to Caché.
Ensure that the Name field is empty.
Clear the Status check box.
Click Submit.
The form’s validate method detects the invalid fields and highlights them with pink.
The following alert message displays in the browser.
To generate this message, the form has assembled the following snippets of text. Zen offers default values for these items, so there is no need for you to do anything for the default message to appear. However, if you wish you can customize them to any extent:
The message begins with the form’s invalidMessage text.
For each control that has its required attribute set to true, but contains no entry, the message lists the control’s label followed by the control’s requiredMessage text.
For each control that contains an invalid value, the message lists the control’s label followed by the control’s invalidMessage text.
Click OK to dismiss the alert message box.
The invalid controls remain highlighted until the user edits them and resubmits the form.
Processing a Form Submit
The request to submit the contents of a form can be triggered in one of two ways:
The user clicks a “<submit>” button placed within the form.
The application calls the submit method of the form object in response to a user event:
%form.submit
When a form is submitted, the values of the controls in the form are sent to the server and the %OnSubmit callback method of the page containing the form is called. Note that the %OnSubmit callback method is that of the page that contains the form, not of the form itself or of any component on the form.
%OnSubmit receives an instance of a special %ZEN.Submit object that contains all the submitted values. Note that there is no page object available during submit processing. Zen automatically handles the full details of the submit operation, including invoking server callbacks and error processing. All forms are submitted using the HTTP POST submission method.
Note that using the setting ENCODED=2 disables the <form> component, because ENCODED=2 removes all unencrypted parameters from the url.
If you are interested in details of how Zen executes a submit operation, the following table lists the internal events in sequence, organized by user viewpoint, browser-based execution, and server-side execution. Most of the communication details are handled by the CSP technology underlying Zen. For background information, see the “Zen Client and Server” chapter in Using Zen.
User Login Forms
An application login page presents a special case of a Zen form. To create application login and logout pages, see the section “Controlling Access to Applications” in the “Zen Security” chapter of Developing Zen Applications.
Dynamic Forms
A <dynaForm> is a specialized type of form that dynamically injects control components into a group (or groups) on the Zen page. Layout is determined automatically by code internal to the <dynaForm>. The list of controls may be determined by the properties of an associated data controller, or by a callback method that generates a list of controls.
<dynaForm> has the following attributes:
The callback method identified by the OnGetPropertyInfo attribute prepares additional controls to inject onto the form when it is displayed. If this method is defined in the page class, Zen invokes it when it first draws the form, automatically passing it the following parameters:
%Integer — the next index number to apply to a control on the generated form. As the callback method injects additional controls on the form, it must increment this index value, as shown in the example below.
As array of %String passed by reference.
%String — the current data model ID, for cases where the contents of a dynamic form vary by instance of the data model object. The method can get values from this object, or it can assign literal values.
To define additional controls, the method must place values into the input array, using two-part subscripts as follows:
The first subscript is the value of the name attribute that was assigned to the corresponding control on the form. It is this name (and not the id) that identifies the control and associates it with a value. For example, the following array position stores the 1–based index of the control’s ordinal position on the form:
pInfo(name)
The second subscript is the name of a property on the control object. %type is a control property whose value identifies the type of the control. The names of other properties are listed in the “Zen Controls” chapter, either in the “Control Attributes” section or in topics about specific controls. For example, the following array position stores the value for the attr attribute of the name control:
pInfo(name,attr)
The callback must return a %Status data type. The following example shows a valid method signature and use of parameters and array subscripts:
Method GetInfo(pIndex As %Integer, ByRef pInfo As %String, pModelId As %String) As %Status { Set pInfo("Field1") = pIndex Set pInfo("Field1","%type") = "textarea" Set pInfo("Field2") = pIndex + 1 Set pInfo("Field2","label") = "Field 2" Quit $$$OK }
To use the above method as the callback, the developer would set OnGetPropertyInfo="GetInfo" for the <dynaForm>.
If the last control on the generated form comes from an embedded property with n fields, your callback must increment past these generated controls by adding n to the index number at the beginning of the method, before assigning the index to any controls. This convention is not necessary when the last generated control on the form comes from a simple data type, such as %String, %Boolean, or %Numeric. The previous example shows the simple case, in which the method uses and increments the index provided. | https://docs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY=GZCP_FORMS | CC-MAIN-2021-04 | refinedweb | 2,479 | 52.19 |
[0.9] Python Ext Builder
Announcing the Python JSB Builder 0.9
Download Python Builder here
The python builder has it's own google hosted project, so that people's suggestions can be incorporated, at
Notes / Futures:
If your Python installation doesn't have them already, you'll need to install elementtree or cElementTree. If you cannot install elementree system-wide you must set the PYTHONPATH environment variable so that Python can still find the package where ever it's installed.
The script runs on any Python version starting from 2.3. It should also run on Windows but that's not tested or supported. It's designed to be run on Unix style machines like: MacOSX, Linux, *BSD and Solaris. Since Python is installed on many Unix systems by default it should run flawlessly on almost any webserver.
If you have administrative rights on the system and you want the build process to be very fast, you can install Python's just-in-time compiler called Psyco. This speeds up execution time (mostly jsmin) by more then 10 times.
It can use various styles of (aggressive) minimization strategies. Like: jsmin, shrinksafe,
a packer (packing is compression, and for production it's much better to use gzip then packers!!!!) and very soon yui-compressor support.
If you have issues, find bugs, feature requests, please use the issue tracker and post in this thread.
ChangeLog
I'm part of the Ext Community
- 0.1: first public version (April 6, 2007)
- 0.2: added options and jsmin, fallback on elementtree (April 14, 2007)
- 0.3: reduced size by running rhino compressor on source files
- 0.4: intermediated release, fixes to much to list here
- 0.5: added options again, more error messages
- 0.6: added jspacker
- 0.7: fix for python2.3
- 0.7.1: added psyco support (greatly speedsup jsmin)
- 0.8: added yui-compressor (for javascript, css will follow soon)
- 0.9: fixed import of elementtree for python2.5 (thanks aconran!)
Maintaining: Translations and some Examples
Developing on: ExtJS Python Builder / Gozerbot
Places: Ido.nl.eu.org / My ExtSamples / Trbs on Wiki / IRC
To get this up and running with Python 2.5.2 I had to change the import statement.
From:
Code:
from elementtree.ElementTree import ElementTree as ET
Code:
from xml.etree.ElementTree import ElementTree as ETAaron Conran
@aconran
- I'm part of the Ext Community
Maintaining: Translations and some Examples
Developing on: ExtJS Python Builder / Gozerbot
Places: Ido.nl.eu.org / My ExtSamples / Trbs on Wiki / IRC
Target directory is not a ExtJS svn checkout directory
I checkout ExtJS from
And launch build_ext_packages.py like:
build_ext_packages.py -CSJP "C:\Work\JS\extjs-3.x"
And I've got: "Target directory is not a ExtJS svn checkout directory"
C:\Work\JS\extjs-3.x IS my SVN checkout root directory Jagszent
dɐɳiel@ʝɐgszeɳt.de <- convert to plain ASCII to get my email address does not mirror the Ext SVN. It only includes the released versions (the ZIP files you can download on this site) and has a different directory structure. If you want to build new versions off this, use as root directory.Daniel Jagszent
dɐɳiel@ʝɐgszeɳt.de <- convert to plain ASCII to get my email address
Hi trbs,
do you have any plans to update py-builder to use new *.jsb2 project files of Ext 3.x branch?Jozef Sakalos, aka Saki
Education, extensions and services for developers at new
News: Grid MultiSearch Plugin, Grid MultiSort Plugin, Configuring ViewModel Hierarchy | https://www.sencha.com/forum/showthread.php?12105-0.9-Python-Ext-Builder | CC-MAIN-2015-32 | refinedweb | 583 | 67.65 |
How to display maps in the Map control
Display customizable maps in your app by using the Map control.
The MapControl and most of the classes described in this topic belong to the Windows.UI.Xaml.Controls.Maps namespace.
Important
Your app has to be authenticated before it can use many features of the Map control and map services. For more info, see How to authenticate your Maps app.
Adding the Map control to a XAML page
Display a map on a XAML page by adding a MapControl.
The MapControl requires a namespace declaration for the Windows.UI.Xaml.Controls.Maps namespace in the XAML page or in your code.
If you drag the control from the Toolbox, this namespace declaration is added automatically.
If you add the MapControl to the XAML page manually, you have to add the namespace declaration manually at the top of the page.
xmlns:Maps="using:Windows.UI.Xaml.Controls.Maps"
If you add the MapControl in your code, you have to add the namespace declaration manually at the top of the code file.
using Windows.UI.Xaml.Controls.Maps;
If you want the MapControl to fill all the available space in the default Grid, clear the alignment and margin settings. To clear these settings quickly, right-click on the control, and then select Layout | Reset All.
Provide the authentication token for the MapControl by setting the value of its MapServiceToken property.
Here's a simple example of the MapControl on a page.
<StackPanel HorizontalAlignment="Stretch" Margin="8,8,8,8" VerticalAlignment="Stretch" > <TextBlock TextWrapping="NoWrap" Text="Map control" FontSize="36" Margin="8,0,0,16"/> <Maps:MapControl x: </StackPanel>
Specifying the location to display on the map
Specify the location to display on the map by specifying the Center property of the MapControl in your code or by binding the property in your XAML markup.
Tip Since a string can't be converted to a Geopoint, you can't specify a value for the Center property in XAML markup unless you use data binding. (This limitation also applies to the MapControl.Location attached property.)
This example displays a map with the city of Seattle as its center.
using Windows.Devices.Geolocation; protected override void OnNavigatedTo(NavigationEventArgs e) { MapControl1.Center = new Geopoint(new BasicGeoposition() { Latitude = 47.604, Longitude = -122.329 }); MapControl1.ZoomLevel = 12; MapControl1.LandmarksVisible = true; }
void MainPage::OnNavigatedTo(NavigationEventArgs^ e) { BasicGeoposition seattleBG = { 47.604, -122.329 }; auto gp = ref new Geopoint(seattleBG); this->MapControl1->Center = gp; this->MapControl1->ZoomLevel = 12; this->MapControl1->LandmarksVisible = true; }
This example displays the following map.
Configuring the map
Configure the map and its appearance by setting the values of the following properties of the MapControl.
Map.
Map appearance
- Specify the type of map - for example, a road map or an aerial map - by setting the Style property with one of the MapStyle constants.
- Set the color scheme of the map to light or dark by setting the ColorScheme property with one of the MapColorScheme constants.
Showing information on the map
Show information on the map Nokia HERE watermark is displayed on the map by setting the WatermarkMode property with one of the MapWatermarkMode constants.
- Display a driving or walking route on the map by adding a MapRouteView to the Routes collection of the Map control. For more info and an example, see How to get and display routes and directions.
For info about how to display pushpins, shapes, and XAML controls in the MapControl, see How to display pushpins, shapes, and controls on a map.
Changing the map
Call one of the overloads of the TrySetViewAsync method to move the Center of the map to a new location.
When you call the TrySetViewAsync method, you can also specify optional new values for the following properties of the MapControl:
You can also specify an optional animation to use when the view changes by providing a constant from the MapAnimationKind enumeration.
Call the TrySetViewBoundsAsync method to display the contents of a GeoboundingBox on the map. Use this method, for example, to display a route or a portion of a route on the map. For more info, see How to get and display routes and directions.
- Display a route on the map by providing the BoundingBox of the MapRoute.
- Display a portion of a route on the map by providing the BoundingBox of the MapRouteLeg.
Getting info about locations on the map
Get info about locations on the map by calling the following methods of the MapControl.
- Call the GetLocationFromOffset method to get the geographic location that corresponds to the specified point in the viewport of the Map control.
- Call the GetOffsetFromLocation method to get the point in the viewport of the Map control that corresponds to the specified geographic location.
- Call the IsLocationInView method to determine whether the specified geographic location is currently visible in the viewport of the Map control.
Handling changes to the map
Determine whether the map is loading or completely loaded by handling the control's LoadingStatusChanged event.
Handle changes that happen when the user or the app changes the settings of the map by handling the following events of the MapControl.
Handling user interaction with the map
Handle user input gestures on the map by handling the following events of the MapControl. Check the values of the Location and Position properties of the MapInputEventArgs to get info about the geographic location on the map and the physical position in the viewport where the gesture occurred.
Related topics
How to display maps and directions in the built-in Maps app
How to display pushpins, shapes, and controls on a map
How to get locations and addresses
How to get routes and directions
How to authenticate a Maps app | https://docs.microsoft.com/en-us/previous-versions/windows/apps/dn642089(v=win.10) | CC-MAIN-2019-22 | refinedweb | 951 | 52.6 |
Closed Bug 1276438 Opened 5 years ago Closed 3 years ago
document
.body implemented on the incorrect interface
Categories
(Core :: DOM: Core & HTML, defect)
Tracking
()
mozilla60
People
(Reporter: sephr, Assigned: bzbarsky)
References
(Blocks 1 open bug)
Details
(Keywords: dev-doc-complete, Whiteboard: [tw-dom] btpp-backlog)
Attachments
(7 files)
User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36 Steps to reproduce: document.body is implemented on the HTMLDocument interface, instead of the Document interface as required by the latest W3C HTML5 spec. For example, the following code should return true: (new DOMParser).parseFromString("<html xmlns=''><body/></html>","application/xhtml+xml").body !== null Chrome, Edge, IE, Safari, and Opera all correctly implement document.body on the Document interface and return true with that example. Additionally, Firefox's implementation of document.body (on HTMLDocument) refuses to work with non-HTMLDocument documents. For example, run the following (the result should also be true): (Object.getOwnPropertyDescriptor(Document.prototype, "body") || Object.getOwnPropertyDescriptor(HTMLDocument.prototype, "body")).get.call((new DOMParser).parseFromString("<html xmlns=''><body/></html>","application/xhtml+xml")) !== null Chrome, Edge, IE, Safari, and Opera also all return true for that example. Actual results: The examples above return false. Expected results: The examples above should both return true. document.body should be moved to the Document interface. It should function equivalently to this workaround at : if (!Object.getOwnPropertyDescriptor(Document.prototype, "body")) Object.defineProperty(Document.prototype, "body", { enumerable: true , configurable: true , get: function() { return this.evaluate( "/*[local-name()='html'][namespace-uri()='']" + "/*[local-name()='body'][namespace-uri()='']" , this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue; } , set: function(replacement) { var body = this.body; body.parentElement.replaceChild(replacement, body); } });
Summary: document.body implemented on incorrect interface → document.body implemented on the incorrect interface
Oh sorry, incorrect wording for "actual results". s/The examples above return false/Firefox throws an error/
Component: Untriaged → DOM
Product: Firefox → Core
Of course we're not trying to implement W3C HTML5 spec, but sure, WhatWG spec has the same. However the whole setup for different *Document interfaces is unclear - I mean it is unclear whether the HTML spec is web compatible and/or whether it is something we want to have. But in this particular case, looks like we could move .body to Document. Need to then make sure the value of .body is calculated the same way in different browsers in all the special case, like what if the document is an SVG document, or some random XML document etc.
Whiteboard: [tw-dom]
Chrome and Safari implement it equivalently to my workaround, essentially being the XPath 2.0 query "/html:html/html:body". IE and Edge implement it similar to the XPath 2.0 query "//html:body[namespace-uri(root())='']" (meaning the first <body> that appears anywhere in a document with the root node in the HTML namespace, including when the root node is the body element itself) For example, the following examples will return `null` in all browsers other than Firefox: (new DOMParser).parseFromString("<html><body/></html>","application/xml").body // null (correct) (new DOMParser).parseFromString("<svg xmlns=''><foreignObject><html xmlns=''><body/></html></foreignObject></svg>","application/xhtml+xml").body // null (correct) I think there are a couple other things like document.head that should also be moved/ported to Document. Oddly enough, Firefox treats application/xhtml+xml documents as HTMLDocuments when navigated to in the browser (so I can use document.body in a XHTML5 document, but only when navigated to), but treats them as Documents when parsed through DOMParser. Is that a bug or intentional behavior? If so, I'll file a separate issue for that.
Whiteboard: [tw-dom] → [tw-dom] btpp-backlog
Assignee: nobody → bzbarsky
Status: UNCONFIRMED → ASSIGNED
Ever confirmed: true
There are two changes here: 1) We allow setting .body even if the root element is not an <html:html>. This is what the spec says to do, and what we used to do before the changes in bug 366200. No tests for this yet, pending getting resolved. 2) We use GetBody(), not GetBodyElement(), to look for an existing thing to replace. This matters if there are <frameset>s involved.
Attachment #8945689 - Flags: review?(nika)
The "body" part of responsexml-document-properties.htm is not really per current spec text, and fails in every non-Firefox browser, and in Firefox after this change. tracks this issue to some extent, but if all browsers are going to align here anyway, we should just adjust the test and move on.
Attachment #8945690 - Flags: review?(nika)
> No tests for this yet, pending getting resolved. Tests are being added in
Comment on attachment 8945692 [details] [diff] [review] part 6. Stop using nsIDOMHTMLDocument::GetBody Review of attachment 8945692 [details] [diff] [review]: ----------------------------------------------------------------- ::: toolkit/components/find/nsWebBrowserFind.cpp @@ +433,5 @@ > + > + if (doc->IsHTMLOrXHTML()) { > + Element* body = doc->GetBody(); > + NS_ENSURE_ARG_POINTER(body); > + NS_ADDREF(*aNode = body->AsDOMNode()); This is kinda gross. Kinda feels like we should have something like do_AddRef(aNode, body->AsDOMNode()); which is short for *aNode = do_AddRef(body->AsDOMNode()).take(); That's definitely beyond the scope of this patch though ^.^
Attachment #8945692 - Flags: review?(nika) → review+
Comment on attachment 8945693 [details] [diff] [review] part 7. Get rid of nsIDOMHTMLDocument::GetBody Review of attachment 8945693 [details] [diff] [review]: ----------------------------------------------------------------- beautiful ^.^
Attachment #8945693 - Flags: review?(nika) → review+
> This is kinda gross. I agree. We should drop nsIDOMNode use from nsWebBrowserFind, ideally. ;)
Pushed by [email protected]: part 1. Move the implementation of the .body getter from nsHTMLDocument to nsIDocument. r=mystor part 2. Move the implementation of the .body setter from nsHTMLDocument to nsIDocument. r=mystor part 3. Align the .body setter with the spec a bit better. r=mystor part 4. Move the .body getter from HTMLDocument to Document. r=mystor part 5. Get rid of IsCurrentBodyElement. r=mystor part 6. Stop using nsIDOMHTMLDocument::GetBody. r=mystor part 7. Get rid of nsIDOMHTMLDocument::GetBody. r=mystor
Status: ASSIGNED → RESOLVED
Closed: 3 years ago
status-firefox60: --- → fixed
Resolution: --- → FIXED
Target Milestone: --- → mozilla60
I've updated the docs to make it clear the is implemented on Document: And added a note to the Fx60 rel notes: Let me know if that's OK. Thanks!
Flags: needinfo?(bzbarsky)
Keywords: dev-doc-needed → dev-doc-complete
For what it's worth, document.body can return a <frameset>, not just a <body>. The docs at only mention the latter; not sure whether this is on purpose. I fixed the note on the compat table to be a bit clearer about what behavior actually changed. Thank you for the documentation updates!
Flags: needinfo?(bzbarsky)
(In reply to Boris Zbarsky [:bz] (no decent commit message means r-) from comment #19) > For what it's worth, document.body can return a <frameset>, not just a > <body>. The docs at > only > mention the latter; not sure whether this is on purpose. That's a good point. I've updated it to match the description on the actual property page. > I fixed the note on the compat table to be a bit clearer about what behavior > actually changed. > > Thank you for the documentation updates! And thanks for your help, much appreciated.
Component: DOM → DOM: Core & HTML | https://bugzilla.mozilla.org/show_bug.cgi?id=1276438 | CC-MAIN-2021-10 | refinedweb | 1,188 | 52.56 |
[ Usenet FAQs | Search | Web FAQs | Documents | RFC Index ]
From: [email protected] (Britt ) Newsgroups: news.newusers.questions Subject: FAQ on making and using a .signature file Date: 21 Nov 1996 21:13:47 GMT Message-ID: <[email protected]> Reply-To: [email protected] Summary: A short informational on getting your .signature to work. Keywords: sig .sig signature .signature footer Archive-name: usenet/signature-faq News-newusers-questions-archive-name: signature-faq Last-modified: 1996/5/27 Author: [email protected] - with tips gathered from posts and submissions and credited wherever possible Comment: Available for FTP from rtfm.mit.edu in usenet/news/newusers/questions from agora.rdrop.com /pub/users/tierna and by email from [email protected] FAQ on making and using a .signature file by Britt Klein Last updated: 27 May 1996 (NOTICE: To send a reply in email to the writer of this post, use the "r" key. Personal correspondence and complete reposts without comment should _not_ be posted to the newsgroups.) Available for FTP from rtfm.mit.edu in usenet/news/newusers/questions by email from [email protected], and by ftp from agora.rdrop.com in /pub/users/tierna. What follows are the bare basics on how to create a .signature file and get it to append to your news posts and email. It *should* work for most shell account users. Mail programs covered are Elm, Pine, mail and mailx, and mailtool. Anything in quotes is a prompt-line command and should work verbatim. (Also, the terminology herein is quite near the lowest level of enduser. This is on purpose, as the last thing new users need is to be confused by too much technicalese.) This is formulated for *nix-based systems, outside of that realm I'm out of my level of expertise big-time. I never claimed to know everything, just enough to get around. Also, the best information I have on Netscape is that there is no way to have it automatically append a .signature file. You'll have to manually read it in. (And that's _all_ I know of Netscape.) Yes, DO email for clarification or further information or advice. I've troubleshot this function on shell accounts many times and might be able to help if you have trouble. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - THE ABSOLUTE BASICS: Get thee to thy home directory and therein edit thyself a file. Name it `.signature'. Remember that inews and other news systems (the ones that make up the majority of the news software on Usenet, actually) will cut off everything after the fourth line, so it's good to stay below that limit. Also, don't use ANSI. It might look good on your screen, but zillions of people across the Net will see it as nothing more than a bunch of control characters and very likely underestimate your intelligence. If you've never used an editor, I suggest pico, as it's infinitely user-friendly. ("pico .signature") Save it. Make sure the .signature file is world readable ("chmod 644 .signature"). Now, your news posting software _should_ look for and automatically append it to your posts. If you're using Elm or Pine for email, they ought to do same. Some versions of mail and mailx will, also. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ELM: If you are using Elm and it doesn't automatically read on the end of your messages, go to your .elm directory ("cd .elm") and edit your elmrc to get the pointers looking for a .signature file (often the problem is that line is commented out with a #, delete it). This assumes your Elm, as mine, supplies a .elm directory and elmrc file when invoked. If not, the following section should be the answer: - - - - - 1. If you do not yet have a .elm/elmrc file, create one with the following steps: elm (start elm) o (options) > (save) q (quit elm) 2. Edit the .elm/elmrc file with your favorite text editor (newer versions create a .elm directory and put the file `elmrc' into it. If that doesn't happen, you'll need to create it at this point, then edit), and insert the two lines localsignature = $HOME/.signature remotesignature = $HOME/.signature according to the comment lines in that file (Remember, to have those lines read, take out the #'s at the beginning.) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PINE: Torsten Dreier kindly supplied the information on getting things working in Pine: In your home directory you should have a file called '.pinerc'. Check with 'ls -alg'. This file is the pine configuration. Edit it and search for the section 'feature list'. To this section add the command 'signature-at-bottom' which will move the signature in replies to the end of the original (quoted) text. Zoli <[email protected]> also supplied the following information: Pine handles news exactly as email - so this works for both; on the other hand, recent versions do not require manually editing .pinerc: the feature-list (and other) settings can be changed from within its main menu via Setup-Config - not only this avoids messing up .pinerc, but also provides a neat context-sensitive help. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MAIL and MAILX: Thomas Okken <[email protected]> gives the following assistance for people who use mail or mailx but still want a .signature on their email: The FAQ says that some versions of mail and mailx will automatically append the .signature file. My experience is only with systems where this does *not* work, so I thought I'd contribute the solution I found. I have tried and used this with BSD mail on SunOS 4.1.1 and with mailx on HP-UX 9.01; it should work with lots of other systems too. Here's what to do: Make a file called "addsig" and put it in your private bin directory or some other convenient place. (Convenient = out of the way; it will work automatically, after all.) My home directory is "/users/tokken", so the file I create is called "/users/tokken/bin/addsig". This is what the file should look like: #!/bin/csh if (-f /users/tokken/.signature) then (cat - ; echo -- ; cat /users/tokken/.signature) | /usr/lib/sendmail $* else /usr/lib/sendmail $* endif Replace "/users/tokken/.signature" with "/your/home/dir/.signature". Make the file "addsig" executable (chmod +x addsig). Finally, edit your .mailrc file, or make a new one, and add this line: set sendmail=/users/tokken/bin/addsig Of course, "/users/tokken/bin/addsig" should be changed to whatever you called the file created earlier. That's it! From now on, your signature will be appended to mail you send with BSD mail or mailx. Note: this will not work if your system mailer is not "/usr/lib/sendmail". It could also be "/usr/bin/sendmail", but you'd best ask your system administrator if "addsig" does not work. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - NOTE: Newsposting software normally does *not* show your .signature when it asks about sending. The only sure way to know is to post to a TEST newsgroup to see. Don't append manually thinking it's not there until you know for certain. And remember, to test your .signature, send email to yourself or a friend, and send your posts to alt.test or misc.test with the Subject: ignore so you don't clutter up areas not meant for such things. That way you'll not get floods of email chiding you for improper newsgroup use. Worldwide test groups send automatic replies to posts unless you include the words "ignore" or "no reply" in the body of the message. (Recommended reading: Professor Timo Salmi's FAQ on test posts periodically posted to news.newusers.questions.) - Britt -- And so it came to pass |\ _,,,---,,_ |\ _,,,---,,_ that on Yom Kippur at /,`.-'`' -. ;-;;,_ /,`.-'`' -. ;-;;,_ one hour past noon did |,4- ) )-,_. ,\ ( `'-' |,4- ) )-,_. ,\ ( `'-' Boots beget Alef and '---''(_/--' `-'\_) '---''(_/--' `-'\_) Beth, Gimel and |\ _,,,---,,_ |\ _,,,---,,_ Daleth; and the /,`.-'`' -. ;-;;,_ /,`.-'`' -. ;-;;,_ family rejoiced |,4- ) )-,_. ,\ ( `'-' |,4- ) )-,_. ,\ ( `'-' and it was good. '---''(_/--' `-'\_) '---''(_/--' `-'\_)
Send corrections/additions to the FAQ Maintainer:Send corrections/additions to the FAQ Maintainer:
Last Update May 13 2007 @ 00:24 AM | http://www.faqs.org/faqs/usenet/signature-faq/ | crawl-001 | refinedweb | 1,357 | 67.96 |
Analyze a graph to deduce the dependency order. More...
#include "mmn_analyze_graph.h"
#include "mmn_graph_rep1.h"
Go to the source code of this file.
Analyze a graph to deduce the dependency order.
Definition in file mmn_analyze_graph.cxx.
Given a graph with n.size() nodes and arc.size() arcs, deduce dependencies.
If returns true, then dep is an ordered list of dependencies allowing us solve a minimisation problem one node at a time. If it returns false, then the graph cannot be decomposed into a sequence of single or pairwise dependencies. If dep[i].n_dep==1 for all i, then the graph is a tree, and reversing the order of dep gives a means of traversing from the root to the leaves. The original order gives a method of visiting every node only after any child/leaf nodes have been visited first.
Definition at line 19 of file mmn_analyze_graph.cxx. | http://public.kitware.com/vxl/doc/development/contrib/mul/mmn/html/mmn__analyze__graph_8cxx.html | crawl-003 | refinedweb | 148 | 60.72 |
Detailed Study of Input-Output and Files in Python: Python Open, Read and Write to File
Our previous tutorial explained about Python Functions in simple terms.
This tutorial we will see how to perform input and output operations from keyboard and external sources in simple terms.
In this Python Training Series, so far we have covered almost all the important Python concepts.
What You Will Learn:
Watch the VIDEO Tutorials
Video #1: Input-Output and Files in Python
Video #2: Create & Delete a File in Python
Note: Skip at 11:37 minute in the below video to watch ‘Create & Delete a File’.
Input-Output in Python
Python provides some built-in functions to perform both input and output operations.
#1) Output Operation
In order to print the output, python provides us with a built-in function called print().
Example:
Print(“Hello Python”)
Output:
Hello Python
Output:
#2) Reading Input from the keyboard (Input Operation)
Python provides us with two inbuilt functions to read the input from the keyboard.
- raw_input()
- input()
raw_input(): This function reads only one line from the standard input and returns it as a String.
Note: This function is decommissioned in Python 3.
Example:
value = raw_input(“Please enter the value: ”); print(“Input received from the user is: ”, value)
Output:
Please enter the value: Hello Python
Input received from the user is: Hello Python
input(): The input() function first takes the input from the user and then evaluates the expression, which means python automatically identifies whether we entered a string or a number or list.
But in Python 3 the raw_input() function was removed and renamed to input().
Example:
value = input(“Please enter the value: ”); print(“Input received from the user is: ”, value)
Output:
Please enter the value: [10, 20, 30]
Input received from the user is: [10, 20, 30]
Output:
Files in Python
A file is a named location on the disk which is used to store the data permanently.
Here are some of the operations which you can perform on files:
- open a file
- read file
- write file
- close file
#1) Open a File
Python provides a built-in function called open() to open a file, and this function returns a file object called the handle and it is used to read or modify the file.
Syntax:
file_object = open(filename)
Example:
I have a file called test.txt in my disk and I want to open it. This can be achieved by:
#if the file is in the same directory f = open(“test.txt”) #if the file is in a different directory f = open(“C:/users/Python/test.txt”)
We can even specify the mode while opening the file as if we want to read, write or append etc.
If you don’t specify any mode by default, then it will be in reading mode.
#2) Reading Data from the File
In order to read the file, first, we need to open the file in reading mode.
Example:
f = open(“test.txt”, ‘r’) #To print the content of the whole file print(f.read()) #To read only one line print(f.readline())
Example: 1
Output:
Example: 2
Output:
#3) Writing Data to File
In order to write the data into a file, we need to open the file in write mode.
Example:
f = open(“test.txt”, ‘w’) f.write(“Hello Python \n”) #in the above code ‘\n’ is next line which means in the text file it will write Hello Python and point the cursor to the next line f.write(“Hello World”)
Output:
Now if we open the test.txt file, we can see the content as:
Hello Python
Hello World
Output:
#4) Close a File
Every time when we open the file, as a good practice we need to ensure to close the file, In python, we can use close() function to close the file.
When we close the file, it will free up the resources that were tied with the file.
Example:
f = open(“test.txt”, ‘r’) print (f.read()) f.close()
Output:
#5) Create & Delete a File
In python, we can create a new file using the open method.
Example:
f = open(“file.txt”, “w”) f.close()
Output:
Similarly, we can delete a file using the remove function imported from the os.
Example:
import os os.remove(“file.txt”)
Output:
In order to avoid the occurrence of an error first, we need to check if the file already exists and then remove the file.
Example:
import os if os.path.exists(“file.txt”): os.remove(“file.txt”) print(“File deleted successfully”) else: print(“The file does not exist”)
Using python input/output functions, we can get the input from the user during run-time or from external sources like text file etc. Hope you will be clear about Input-Output and Files in Python from this tutorial.
Our upcoming tutorial will explain about the various Types of Oops available in Python!!
PREV Tutorial | NEXT Tutorial | https://www.softwaretestinghelp.com/python/input-output-python-files/ | CC-MAIN-2021-21 | refinedweb | 822 | 70.33 |
CodePlexProject Hosting for Open Source Software
Can a GET request bind to a strongly typed object? I get the below error. This seems like something I can figure out, but I didn't see any examples. This post seems related
The service operation 'GetMatch' will never receive a value for the input parameter 'query' of type 'MatchQuery'. Ensure that a request HttpOperationHandler has an output parameter with a type assignable to 'MatchQuery'.
Here is code from my Resource...
public class MatchQuery
{
public int WinnerId { get; set; }
public int LooserId { get; set; }
}
[WebGet(UriTemplate = "GetMatch?WinnerId={WinnerId}&LooserId={LooserId}")]
public HttpResponseMessage GetMatch(MatchQuery query)
{
......
}
I added a HttpOperationHandlerFactory and a Handler, but now I'm getting the following error.
The request HttpOperationHandler 'MatchQueryHandler[winnerId, looserId, out matchQuery]' of service operation 'Get' will never receive a value for input parameter 'winnerId' of type 'Int32'. Ensure that a request HttpOperationHandler
that executes prior to the 'MatchQueryHandler' HttpOperationHandler has an output parameter with a type assignable to 'Int32' or that the output parameter has the name 'winnerId' and provides a string value that can be parsed as a 'Int32'.
I did fine the GridHandler example in the unit tests and followed it, but I must have missed something.
I had a conflicting method in my Resource. Once I removed it, it started working.
Hello ssuing, Could you please show me your MatchQueryHandler and handler factory code?
I'm not sure how to implement those handlers.
Thank you very much.
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://wcf.codeplex.com/discussions/254525 | CC-MAIN-2016-50 | refinedweb | 281 | 58.38 |
Looking for help :
I run abc.py with normal output as I expect, but get error in abc.pyc. Below is what I have done. Would you tell me what I have mistaken ? Thank you very much !!
import datetime
test_time = open('test.time', 'w')
test_time.write('oh, today is\n')
test_time.close()
test_time = open('test.time', 'a')
timing = datetime.date.today()
#
print timing, type(timing) # 2008-03-09 <type 'datetime.date'>
# convert <type 'datetime.date'> to a string first
# since write() expects a string
test_time.write(str(timing))
test_time.close()
# test the file's contents
for line in file('test.time'):
print line,
running in termial
~/abc$ ./abc.py
2008-03-10 <type 'datetime.date'>
timing is
2008-03-10
I created abc.pyc
>>> import py_compile
>>> py_compile.compile("abc.py")
However, when running with abc.pyc
:~/abc$ ./abc.pyc
: command not found�
./abc.pyc: line 2: ���Gc@s�ddkZedd�Zeid�ei�edd�Zeii�ZeGe�GHeie: command not found
./abc.pyc: line 3: d�D]: command not found
./abc.pyc: line 4: syntax error near unexpected token `i����Ns'
./abc.pyc: line 4: `Z
e
Gq�WdS(i����Ns test.timetws'
So what is wrong ? | https://www.daniweb.com/programming/software-development/threads/113040/problem-in-running-pyc | CC-MAIN-2016-44 | refinedweb | 194 | 74.25 |
ArUco relative marker position and rvec/tvec inversion
I am trying to write a program with aruco+openCV. Program detects two ArUco markers, invert the second one and compose them together. Result is another tvec and rvec. I am summing tvec and first markers tvec, multiplying rvec and first markers rvec. And trying to show that with projectPoints and cv.imshow. My tvec/rvec invert operation code:
def inversePerspective(rvec, tvec): R, _ = cv2.Rodrigues(rvec) R = np.matrix(R).T invTvec = np.dot(-R, np.matrix(tvec)) invRvec, _ = cv2.Rodrigues(R) return invRvec, invTvec
In another question user Tetragramm helped me to understand the basics. You can find the question in:...
And I thought I should test my functions. In relative position function:
def relativePosition(rvec1, tvec1, rvec2, tvec2): rvec1, tvec1 = rvec1.reshape((3, 1)), tvec1.reshape((3, 1)) rvec2, tvec2 = rvec2.reshape((3, 1)), tvec2.reshape((3, 1)) # Inverse the second marker, the right one in the image invRvec, invTvec = inversePerspective(rvec2, tvec2) print(rvec2, tvec2, "\n and \n", inversePerspective(invRvec, invTvec)) info = cv2.composeRT(rvec1, tvec1, invRvec, invTvec) composedRvec, composedTvec = info[0], info[1] composedRvec = composedRvec.reshape((3, 1)) composedTvec = composedTvec.reshape((3, 1)) return composedRvec, composedTvec
I executed code once and showed 2 markers that near to each other. Normally I should expect that in print function, it should print almost the same matrices. The output was:
rvec: [[-0.08162009] [-0.07777238] [-1.46936788]] tvec: [[-0.05844654] [ 0.01511464] [ 0.00109817]] and [[-0.08162009] [-0.07777238] [-1.46936788]] [[-0.05844654] [ 0.01511464] [ 0.00109817]]
It means that my invert code is ok. And I am using composeRT to compose two rvec/tvecs. Is there anything I did wrong ? My current code is in github and I really accept any kind of help. I am searching for days and days. Thanks in advance for the answers, here is the codebase:...
Edit: I print wrong test code. I corrected that. | https://answers.opencv.org/question/191153/aruco-relative-marker-position-and-rvectvec-inversion/ | CC-MAIN-2021-25 | refinedweb | 323 | 71.21 |
Someone let me know where im going wrong. I need basic examples please .
Heres my code.
public class Grades
{
String ssn;
String name;
String grade;
Grades(String s, String n, String g)
{
ssn = s;
name = n;
grade = g;
}
}
class Student{
public static void main(String args[])
{
Grades John = new Grades(351-63-2182, John, A);
Grades Kris = new Grades(432-35-2562, Kris, B);
System.out.println(John + " " + Kris);
}
}
When i attempt to compile this code i get an error. Any help possible would be much appreciated.
Thanks!
Your constructor accepts three Strings. You're passing in 351-63-2182, John, A. You probably mean to pass in "351-63-2182", "John", "A".
Also, note that when printing objects (when you do System.out.println(John + " " + Chris);) it will convert them to Strings using their toString() method. Since you have not overrid the toString() method, it will use the toString() method from the object class, which prints memory.
Hotjoe Java forums: ()
Forum Rules
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center | http://forums.devx.com/showthread.php?151020-Help-printing-out-2-dim-array-row&goto=nextoldest | CC-MAIN-2017-34 | refinedweb | 179 | 75.91 |
On Thu, Jan 29, 2009 at 11:43:27AM -0800, Benjamin Kosnik wrote: > > Attached is also a testcase that verifies this, but we'd probably > > need a new tcl function to check if glibc is used and has recent > > enough headers to allow the testcase to pass. > > Or you could just wrap the proposed new testcase with #ifdef > __CORRECT_ISO_CPP_STRING_H_PROTO for now. I can't, because the testcase is testing compiler errors. If I wrap it inside #ifdef __CORRECT_ISO_CPP_STRING_H_PROTO, the errors still won't be generated. What we could do is: proc check_effective_target_correct_iso_cpp_string_wchar_protos { } { return [check_no_compiler_messages correct_iso_cpp_string_wchar_protos assembly { #include <stdint.h> #include <wchar.h> #if !defined(__CORRECT_ISO_CPP_STRING_H_PROTO) || !defined(__CORRECT_ISO_CPP_WCHAR_H_PROTO) ISO C++ correct string.h and wchar.h protos not supported. #else int i; #endif }] } in target-supports.exp and use { dg-do compile { target correct_iso_cpp_string_wchar_protos } } in the testcase. This is untested though. > > :) > > I would find that acceptable. I would like to see something checked in > to the libstdc++ testsuites to track this. > > Longer term, we may want to generalize this and flip a new _GLIBCXX_ > type define and use that in libstdc++ instead of __CORRECT_ISO_CPP_* if > configure probe finds the C++ includes for string.h/wchar.h has the > corrected decls. I believe some (later sun?) other libcs also do > something like what you've proposed for libc. It's been a while since I > last looked. > > For the moment though, let's do the expedient thing so that the > libc/libstdc++ bits are synchronized at check-in and we can move > forward. Ok. Jakub | https://gcc.gnu.org/pipermail/gcc-patches/2009-January/255410.html | CC-MAIN-2021-21 | refinedweb | 253 | 59.7 |
tailor 0.2.3+2
TailorDB #
Tailor is a lightning-speed persistent key-value store for Dart. Using a synchronous, convenient API and a caching system, it is able to write 50k objects, read 500k, and delete 200k, all in a single second.
Caching: Pros and Cons #
Tailor conducts its core operations off of a cached copy of the database. It asynchronously checks for changes to the cache every 250 milliseconds (this value can be changed). If changes have been made, it pushes the cache to a file. You can also manually initiate a push.
It is done this way because writing to files is expensive, so avoiding this cost allows core operations to be really fast.
However, there is some practical issues with this caching. First, the database can only be as big as the available short-term storage. Second, there is a possibility of data loss if you don't manually initiate the pushes, because there might be a gap between a write and a scheduled flush.
If these issues are too much, I'd highly recommend Hive for a more stable alternative.
Features and Performance #
- You can use Tailor synchronously or asynchronously: the core methods (normally synchronous) are available in async form.
- Tailor has strong AES-GCM encryption built in. Just use
var db = TailorDB(file: fileHere, encryption: true, passkey: keyHere)and pass a key. You can generate a key using the
genKey()method.
- Tailor uses a LinkedHashMap structure internally, so insertion order is preserved.
Usage #
Take a look at the example below and the TailorDB docs to understand
usage. Tailor is essentially a persistent map, with Strings as the main data
type. Keys are all
String, and Values are
String,
List<String>, or
Map<String,String>.
import 'package:tailor/tailor.dart'; void main() { var db = TailorDB( file: File(join(Directory.current.path, 'example', 'db.json')), encryption: true, //Encryption is enabled. passkey: '6hUzyvUiXsf652tPHXLW2K-Fx6ZHEU_r', //This is a key for encryption. refreshInterval: 200, //This is how often the cache will be written to storage (in ms). ); db.clear(); db.add(key: 'String', value: 'value'); db.add(key: 'List', value: ['here', 'are', 'values']); db.add(key: 'Map', value: {'key1': 'value1', 'key2': 'value2'}); print(Map.fromIterables(db.keys, db.values)); } // Check out the persistent storage in the db.json file in the example folder! // There's a lot more methods than these. Removing, getting, and tons of utilities/checks // are also available. Take a look at the TailorDB dartdocs!
Normal and Flutter Usage #
- In the constructor, you may notice a file parameter. This is because Tailor requires a JSON file to write to.
- Normally, you can just specify the path to where the db should be (
File('pathtodb/db.json')). If that is inconvenient you can create it in the current directory (
File(join(Directory.current.path, 'db.json')).
- In Flutter, you will need the path provider library. Use it to get a library directory (
var dir = await getLibraryDirectory()). Then, create a JSON file there (
File(join(dir.path, 'db.json')).
- Note: the above uses methods from the dart:io and path libraries. These methods from dart:io and path are bundled with this library; you don't need to import them separately. If you need to import only the core library (and not dart:io/path methods), use
import 'package:tailor/tailor.dart' show TailorDB.
Bugs #
Please file feature requests and bugs at the issue tracker.
0.2.3 - 0.2.3+2 #
- Made option for writeCache(): can be synchronous or async
- Improved benchmarks (test folder)
- README updates
- Cleaned up exports (and API reference)
0.2.2 #
- Made write operations asynchronous to avoid blocking app
0.2.1+1 #
- Better test suite, deleted unfair benchmark
- Include explanation of caching system
- Updated stats in README to include persistent-write
- Made links function properly in README
0.2.1 #
- Added option to change persistent push rate
- Increased default persistent push rate
- Added checks for Map equality to push mechanism
0.1.2 - 0.1.2+1 #
- Relicensed from AGPL to MPL 2.0
- Slightly improved accuracy of tests
- Updated README with more links
0.1.1 - 0.1.1+4 #
- Initial version, created the entire repo
- Wrote viable database which is confirmed to run really fast
- Added encryption, tests, and example
- Refined README
example/tailor_example.dart
import 'package:tailor/tailor.dart'; void main() { var db = TailorDB( file: File(join(Directory.current.path, 'example', 'db.json')), encryption: true, passkey: '6hUzyvUiXsf652tPHXLW2K-Fx6ZHEU_r'); db.clear(); db.add(key: 'String', value: 'value'); db.add(key: 'List', value: ['here', 'are', 'values']); db.add(key: 'Map', value: {'key1': 'value1', 'key2': 'value2'}); db.writeCache(); print(Map.fromIterables(db.keys, db.values)); } //Check out the persistent storage in the db.json file in the example folder!
Use this package as a library
1. Depend on it
Add this to your package's pubspec.yaml file:
dependencies: tailor: ^0.2:tailor/tailor.dart';
We analyzed this package on Mar 27, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:
- Dart: 2.7.1
- pana: 0.13.6
Health suggestions
Format
lib/src/business/encryption.dart.
Run
dartfmt to format
lib/src/business/encryption.dart.
Format
lib/src/tailor_base.dart.
Run
dartfmt to format
lib/src/tailor_base.dart.
Format
lib/tailor.dart.
Run
dartfmt to format
lib/tailor.dart. | https://pub.dev/packages/tailor | CC-MAIN-2020-16 | refinedweb | 885 | 52.15 |
One is the Loneliest Number (Matt Gertz)
Anthony D.
(This post assumes that you’ve read my previous post on Windows Media at – I will be modifying that code in this post.)
After posting my media player blog sample a couple of weeks ago, I got a few questions from a reader called Saleem on how to adapt it to take multiple files as arguments when launching the app. After a few exchanges, I figured that it made sense for me to write up a post on command line arguments, since it’s actually a really fascinating topic.
The first “given” in this problem is that your application is set to be a single-instance application. A single instance application is an app which only ever has one instance loaded into memory (hence the title of this blog) – when you double-click a file which is registered to that application, it looks for an existing instance and uses it if available before trying to create a new instance. Windows Media Player itself is a single instance application – double-clicking a .WMA file while the player is open will use the existing instance rather than creating a new one, so that you don’t get two media players competing for the sound card. J
To make your application single-instance, you’ll need to click a checkbox the project properties. Right-click on the project in the Solution Explorer and choose “Properties,” and in the “Application” tab put a check in the “Make single instance application” checkbox.
While you’re on that tab, you should also click the “View Application Events” button – that will bring up a file called “ApplicationEvents.vb”. That file defines the event handlers for the application itself (not the main form). Don’t touch anything in that file yet; we’ll get to it later.
Now, the goal of our application will be to allow the user to specify multiple playlists to be randomized — they should all get mixed up together, but arcs (songs that are required to play together) should be preserved. In my last post, I hard-coded the original playlist path; I now want to modify the app so that it gets the names of the playlists from playlists I invoke. There are two ways that this might happen:
(1) Using the command line: the user opens a command shell and calls the application with a list of playlist files as arguments. In this case, the filenames are passed as arguments to the application and are available in the Load event of the form (as well as elsewhere). However, a subsequent call from the command line would then trigger the StartupNextInstance event of our single-instance app, and I’ll have to examine the new command line in that handler to get each of those new filenames.
(2) Selecting a bunch of file files and pressing “Enter” (or choosing “Open” from the context menu): in this case, the app is launched with one of the files specified on a command line (usually the last selected), and then Windows attempts to relaunch the app with the names of the other files. So, in the case where three files are invoked, the first filename is available in the Form_Load event via the My.Application.CommandLineArgs, and then StartupNextInstance gets called twice for each of the two remaining filenames. Those arguments get retrieved from the EventArgs object passed to the event handler.
So, in order to handle filenames coming from two different sources, I’m going to need to centralize my randomization code from the last post so that both entry points can use it. Also, I’m going to need to reverse the order in which I do the randomization. That is, instead of picking a random file from an existing playlist and appending it (or its arc, if any) to a new playlist, I’ll instead go through the old playlist in track order and copy each track (or its arc, if any) to a random location in the new playlist. If I didn’t do that, then the new playlist won’t be truly random since music from the second playlist will always follow music from the first playlist, etc.
The first thing I’m going to do is move all of my randomization code out of Form1_Load (which I’ve renamed to VBJukeboxForm_Load) and into a new method called MergePlaylist(). The resulting handler will just call MergePlaylist() for each argument that it finds in the command line:
Private Sub VBJukeboxForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
‘ Make sure we have a random series
Microsoft.VisualBasic.Randomize()
‘ Initialization
Player.settings.autoStart = False ‘ Playlist should not automatically play when added to the player
Me.SavePlaylistBt.Enabled = False ‘ Don’t enable the “save playlist” button until there’s something to save
‘ This playlist is initially empty, and we’ll fill it with songs.
‘ You could give the user the option of picking the name
‘ by reading it from a label control.
newplaylist = Me.Player.newPlaylist(“Smart Shuffled Playlist”, “”)
‘ Merge in the old playlists that were passed via the command line
For Each Argument In My.Application.CommandLineArgs
MergePlaylist(Argument)
‘ Point player at the new playlist so it can be played
Player.currentPlaylist = newplaylist
End Sub
Note that I’ve added a button called SavePlaylistBtn to the form. The user will click that button to save the sorted playlist to the library if desired. It will be disabled until there are actually songs in the new playlist. The button’s click handler is very simple:
Private Sub SavePlaylistBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SavePlaylistBtn.Click
‘ Save new playlist to library and Music\Playlists
Player.playlistCollection.importPlaylist(newplaylist)
End Sub
Now, I need to merge in playlists for the case where StartupNextInstance is used to “relaunch” the application (or, rather, connect to the existing instance of the app with new filenames). I’ll insert the following code in the ApplcationEvents.vb file we opened previously, into the My namespace:
Partial Friend Class MyApplication
Private Sub MyApplication_StartupNextInstance( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs _
) Handles Me.StartupNextInstance
For Each s As String In e.CommandLine
My.Forms.VBJukeboxForm.MergePlaylist(s)
End Sub
Note that in this case the filenames are passed in by the EventArgs object – we don’t have to query for them from the application, unlike in the Load handler.
MergePlaylist is very much like the code I wrote for the last post, except that we always take songs from the front of the old list and find a random spot to insert them into the new list:
Sub MergePlaylist(ByVal Argument As String)
Dim oldplaylist As WMPLib.IWMPPlaylist
‘ Make sure that the argument points to an actual file
If My.Computer.FileSystem.FileExists(Argument) Then
‘ Get the file inforation and make sure it’s a playlist
Dim fileData As FileInfo = My.Computer.FileSystem.GetFileInfo(Argument)
If fileData.Extension = “.wpl” Then
‘ Create a copy of the playlist to merge in so that we don’t damage the original.
‘ Note that playlists get initialized with URLs.
oldplaylist = Me.Player.newPlaylist(“Original Sorted Playlist”, “” & Argument)
‘ Get the number of songs to merge in
Dim numberOfSongs As Integer = oldplaylist.count
‘ The value songsRemaining will keep track of the number of songs left to copy,
‘ which in turn helps us keep track of the range for valid random numbers.
For songsRemaining As Integer = numberOfSongs – 1 To 0 Step -1
‘ Pick the next song from whatever remains in the old list:
Dim mediaItem As WMPLib.IWMPMedia = oldplaylist.Item(0)) AndAlso CInt(sPartOfSet) = 1 Then
‘ It’s a number. We may have an arc of songs here.
‘ If we run into anything unexpected then just do a normal copy.
Dim currentSongToCopy As Integer = 0
Dim currentMediaItem As WMPLib.IWMPMedia = mediaItem
Dim sCurrentPartOfSet As String = sPartOfSet
‘ OK, we’re probably good to go, unless we coincidentally got the beginning of another arc instead
‘ due to discontinuous numbers. Worse thing that happens in that case is that we just copy a different arc, and we’ll
‘ pick up these pieces later.
Dim iPartOfSet As Integer = 0
Dim placeToInsert As Integer = FindInsertionLocation()
While sCurrentPartOfSet <> “” AndAlso IsNumeric(sCurrentPartOfSet) _
AndAlso CInt(sCurrentPartOfSet) = iPartOfSet + 1
Insert(placeToInsert + iPartOfSet, currentMediaItem)
oldplaylist.removeItem(currentMediaItem)
iPartOfSet = iPartOfSet + 1 ‘ Copied one song
‘ Check next song if there are any remaining
If currentSongToCopy = oldplaylist.count Then Exit While
currentMediaItem = oldplaylist.Item(currentSongToCopy)
sCurrentPartOfSet = currentMediaItem.getItemInfo(“WM/PartOfSet”)
End While
If iPartOfSet > 0 Then
‘ We may have copied more than one song. Update the For loop variable
‘ appropriately to compensate, since For loop will only decrement by one.
songsRemaining = songsRemaining – (iPartOfSet – 1)
Else
‘ Didn’t copy anything yet — must have been a discontinuity.
‘ Just copy the original song, since user apparently doesn’t care.
GoTo NormalCopy
End If
Else
‘ Just copy like normal
NormalCopy: Insert(mediaItem)
oldplaylist.removeItem(mediaItem)
End If
Else
‘ Random file. Could be clever here and check the file info to see if it’s a media file, and if so
‘ insert it via newplaylist.insertItem(FindInsertionLocation(), mediaItem).
‘ But that’s left as an exercise to the reader.
End If
End If
End Sub
That all should look rather familiar from my last post. Note that I’ve used two new methods called “Insert” to do the actual insertion. One takes just a media item and is used when dealing with non-arc songs, and the other also takes a place value and is used for arcs, since we want to keep songs in the arcs together (i.e., if the first song of an arc goes to position 7, the next song must go to position 8 – there’s no randomness needed for that case). The Insert() methods look like this:
Public Sub Insert(ByVal mediaItem As WMPLib.IWMPMedia)
Dim place As Integer = FindInsertionLocation()
Insert(place, mediaItem)
End Sub
Public Sub Insert(ByVal place As Integer, ByVal mediaItem As WMPLib.IWMPMedia)
If place = newplaylist.count Then
‘ Insert at the end of the list
newplaylist.appendItem(mediaItem)
Else
‘ Insert exactly at the index indicated, moving other items down
newplaylist.insertItem(place, mediaItem)
End If
Me.SavePlaylistBtn.Enabled = True ‘ We have something in the playlist
End Sub
Finally, we need to define the FindInsertionLocation() method used by the Insert() and MergePlaylist() methods. Basically, this just involves getting a random number. However, if that resulting random number points to a location within an arc, we need to crawl backward to the beginning of the arc, since we don’t want to interrupt it. Furthermore, the random number should be based on the number of songs already in the list plus one, since you can always append after the existing songs as well as inserting in front of them. Here’s the code:
Public Function FindInsertionLocation() As Integer
If newplaylist.count = 0 Then
‘ List is empty, so media will go at position 0.
Return 0
Else
‘ Get a random location from 0 to n, where n is the current number of songs in the playlist
‘ (*not* 0 to n-1, because given x existing songs,there are x+1 places to insert a new song
‘ — in front of any existing song, plus after them all).
Dim placeToInsert As Integer = Math.Truncate(Microsoft.VisualBasic.Rnd() * (newplaylist.count + 1))
If placeToInsert = newplaylist.count Then Return placeToInsert ‘ Insert at end
Dim mediaItem As WMPLib.IWMPMedia = newplaylist.Item(placeToInsert)) Then
‘ It’s a number. We may have an arc of songs here.
‘ Get the number and rewind to the first one.
‘ If we run into anything unexpected then just do a normal copy.
Dim iPartOfSet As Integer = sPartOfSet
‘ Make sure we don’t go past the beginning of the list!
If placeToInsert – (iPartOfSet – 1) >= 0 Then
‘ Rewind to what should be the beginning of the arc and get the song.
‘ (Hopefully, they’re all there, but I’m not going to count on them being all
‘ all there and initially in the right order. My
‘ default when confused will be to just copy the
‘ originally picked song as if it wasn’t part of an arc.)
Dim currentPlaceToInsert As Integer = placeToInsert – (iPartOfSet – 1)
Dim currentMediaItem As WMPLib.IWMPMedia = newplaylist.Item(currentPlaceToInsert)
Dim sCurrentPartOfSet As String = currentMediaItem.getItemInfo(“WM/PartOfSet”)
‘ Do some error checking here — the attribute had better be “1”
If Not sCurrentPartOfSet = “1” Then Return placeToInsert ‘ Partial arc — just use the original number
‘ Return the beginning of the arc
Return currentPlaceToInsert
End If
‘ Partial arc exists beginning of list — just use the original number
Return placeToInsert
End If
‘ No interesting information in PartOfSet — just use the original nuber
Return placeToInsert
End If
End Function
And that’s pretty much it. Now, to get the app to work properly when opening it from playlists in File Explorer, there are a couple of ways to proceed:
(1) Register WPL files to your application as the default application instead of Windows Media Player, which you can do from the Tools\Folder Options\File Types in Windows XP or the Folders applet in Windows Vista. (Don’t forget to change it back when you’re done playing around.) This can also be done in a setup project you create for your app — use the File Type editor to modify the registration. Note that users generally don’t like it when installers quietly change the file type registration, so plan accordingly.
(2) If you’d rather avoid mangling with the default for the file type, you can take a shortcut by simply dragging a set of playlists to your application’s icon, which will force them to be loaded by your app regardless of how the file type is registered on your system. Running the playlist from the command line will have the same effect, since you’re explicitly specifing your app in that case.
Note that you can even invoke another playlist while your app is already running (via point (1) or (2)) and have that playlist merge into the existing list — very cool indeed.
The final app is attached below – enjoy! (I wrote it using a recent build of VS2008, incidentally, though none of the functionality I used is any different than what’s available in VS2005.) ‘Til next time…
–Matt–* | https://devblogs.microsoft.com/vbteam/one-is-the-loneliest-number-matt-gertz/ | CC-MAIN-2022-05 | refinedweb | 2,381 | 60.85 |
The topic of the day is a simple one: JSON serialization. Here is my question, if you have a data structure like this:
import json import datetime data = { "now": datetime.datetime.now(), "range": xrange(42), }
Why can’t you do something as simple as:
print json.dumps(data)? These are simple Python datetypes from the standard library. Granted serializing a datetime might have some complications, but JSON does have a datetime specification. Moreover, a generator is just an iterable, which can be put into memory as a list, which is exactly the kind of thing that JSON likes to serialize. It feels like this should just work. Luckily, there is a solution to the problem as shown in the Gist below:
Ok, so basically this encoder replaces the default encoding mechanism by trying first, and if that doesn’t work follows the following strategy:
- Check if the object has a
serializemethod; if so, return the call to that.
- Check if the encoder has a
encode_typemethod, where “type” is the type of the object, and if so, return a call to that. Note that this encoder already has two special encodings - one for datetime, and the other for a generator.
- Wave the white flag; encoding isn’t possible but it will tell you exactly how to remedy the situation and not just yell at you for trying to encode something impossible.
So how do you use this? Well you can create complex objects like:
class Student(object): def __init__(self, name, enrolled): self.name = name # Should be a string self.enrolled = enrolled # Should be a datetime def serialize(self): return { "name": self.name, "enrolled": self.enrolled, } class Course(object): def __init__(self, students): self.students = students # Should be a list of students def serialize(self): for student in self.students: yield student
And boom, you can now serialize them with the JSON encoder —
json.dumps(course, cls=Encoder)! If you have other types that you don’t have direct access to, for example, UUID (part of the Python standard library), then simply extend the encoder and add a
encode_UUID method.
Note that extending the
json.JSONDecoder is a bit more complicated, but you could do it along the same lines as the encoder methodology. | https://bbengfort.github.io/2016/01/better-json-encoding/ | CC-MAIN-2021-17 | refinedweb | 373 | 63.9 |
THE SQL Server Blog Spot on the Web
Most of my database model are written with Visio. I don’t want to start a digression whether Visio is good or not to build a simple data model: Visio is enogh for my modeling needs and customers love its colours and the ability to open the model with Office when I need to discuss it with them. When I have finished modeling, I generate the database and everything works fine.
Nevertheless, Microsoft seems not to like the forward engineer capabilities of Visio. The last release that supports forward engineering is the Enterprise Architect version of Visio 2003, which requires Visual Studio 2005 to be installed on the box. Since I am really tired to install old releases of Visio just to perform forward engineer (moreover, the 2003 release does not support the new data types) I decided it was time to follow the standard approach to Microsoft products: “if Microsoft does not help, do not ask, do it by yourself”.
Thus, I wrote an Office add-in that performs forward engineer of a Visio database model to SQL Server. It does not support any other database driver and has some big limitations, since the library that should let programmers have access to the underlying Visio data model is non documented and full of uninplemented interfaces. Thus, I needed to collect information over the web, searching for people who tried the same before me. Nevertheless, for a standard data model it works fine and saves me to the need to install old software on new computers. :)
It has two basic functions, available through a new ribbon:
The add-in is still in beta, it needs Office 2010 and has been written with Visual Studio 2010, .NET 4.0. If you are interested in testing it you can download the first beta here.
The nice part of the story is that, without any previous knowledge of Office programming and no knowledge at all of the Visio internals, it took me roughly one day from the idea and some hints found on the web to the working add-in and it has been a nice arena for me to try VS 2010… I wonder why Microsoft still refuses to add this feature to Visio, they have much better programmers than me, after all I am a BI guy.
Cool Alberto, sounds really interesting!
Hey - I am very interested in not only running this but also maybe even contributing. However, I am unable to install it right now. The exception I receive is:
System.Security.SecurityException: Customized functionality in this application will not work because the certificate used to sign the deployment manifest for SqlBi.Visio.ForwardEngineer or its location is not trusted.
I tried adding the Temporary_Key.pfx as a Trusted publisher both at the machine level and the user lever, as well as adding the folder location to the list of trusted locations in Office.
Any other suggestions?
Scott, this is my first Visio add-in, so I honestly don't know the detaila about installation, all what I have done is to click on "publish" to generate a setup, clearly the stuff is more complicated.
You can try to create a new key for the project, so that you can open the code and update it, in the meantime I will try to understand how to make it "setuppable" searching on the web for some hints.
You are not the only guy who found this problem, so it seems that the fault is definitely mine. :)
BTW: send me an e-mail (alberto dot ferrari at sqlbi dot com), so that we can try to solve the issue together.
Alberto
You Kick ASS!!!!
I received the same error as above and was able to get passed it by rebuilding & publishing on my local machine.
Hey Alberto,
You two do great things. First, you gave SQL types some insight into the metadata we need to keep our eye on in order for this to work. That's importnat when new versions come out because I here some methods of obtaining metadata are depreciated so we DBAs need to look at this code and be able to rework it when we need to. Second, you made it an office add-in. Ubiquitous, universal. I'm a DBA that does app code as well so I appreciate your attempt to bridge a gap Microsoft has left wide open. It's probably one of the reasons tools like Erwin are still out there. In Microsoft's defense though, even Erwin is not perfect for forward engineering as it relies heavliy on the drop and create. I've actually written tools/scripts to handle these scenarios and preserve data (which is why I appreciate your swan dive in to the metadata for the addin you wrote).
Nice plugin. I am not sure I will be able to use it (will need permissions to 1) install visio 2010 and 2, install a beta software) but I suggest you add this to CodePlex as an opensource project. There could be great benefit to an open project for those of us that like using Visio and you will likely get some contributors to improve the plugin (additional databases and new functionality)
I just wanted to thank you for this tool. It did the job and even helped find some errors in my diagram. As far as installing, I just had to build the project in VS 2010 and it ran perfectly.
Intallation failed on Windows 7 indicating that one of the files was not compatible. Has anyone been able to run it on Windows 7?
Great work, excellent tool, just what I was looking for. Runs on Windows 7 64 bit. Just rebuild and publish, then install.
Excellent job Alberto. Thanks for this great tool that's going to be in my toolbox for a long time since MS has intentionally crippled yet another one of its products. This was a snap! All I did was build the project, start Visio 2010 and BAM! New ribbon. Validation worked great once I set the target to SQL Server. Thanks again! BTW: Love the cars your family builds. :)
I cannot get this to install on WIndows 7. Keep getting the error "The following solution cannot be loaded because Microsoft Office support for the .NET Framework 4.0 is not installed: SqlBi.Visio.ForwardEngineer.vsto.". I had only Visio 2010 installed (and Office 2007). but I just installed the full OFfice 2010 and .Net Framework 4.0, and I'm still getting this error? How do I get the Office support for .Net 4.0 installed on my machine so I can install this plug-in?
Okay, I found the Visual Studio 2010 Tools for the Office System 4.0 Runtime in the MSDN subscriber downloads and got past the error about Microsoft Office support for the .NET Framework 4.0 not being installed. Now, I get a different error:
Downloading Files/SqlBi.Visio.ForwardEngineer_1_0_0_2/Microsoft.Office.Tools.Common.v4.0.Utilities.dll.deploy did not succeed.
Clicking on the Details button gives more info:
Name: SqlBi.Visio.ForwardEngineer
From:
************** Exception Text **************
System.Deployment.Application.DeploymentDownloadException: Downloading Files/SqlBi.Visio.ForwardEngineer_1_0_0_2/Microsoft.Office.Tools.Common.v4.0.Utilities.dll.deploy did not succeed. ---> System.Net.WebException: Could not find file 'C:\publish\Application Files\SqlBi.Visio.ForwardEngineer_1_0_0_2\Microsoft.Office.Tools.Common.v4.0.Utilities.dll.deploy'. ---> System.Net.WebException: Could not find file 'C:\publish\Application Files\SqlBi.Visio.ForwardEngineer_1_0_0_2\Microsoft.Office.Tools.Common.v4.0.Utilities.dll.deploy'. ---> System.IO.FileNotFoundException: Could not find file 'C:\publish\Application Files\SqlBi.Visio.ForwardEngineer_1_0_0_2\Microsoft.Office.Tools.Common.v4.0.Utilities.dll ---
Okay, I found the Office Support for .Net 4.0 on MSDN subscriber downloads, and that got rid of the "Microsoft Office support for the .NET Framework 4.0 is not installed" error message, but then it was still failing with an error "Could not find file 'C:\publish\Application Files\SqlBi.Visio.ForwardEngineer_1_0_0_2\Microsoft.Office.Tools.Common.v4.0.Utilities.dll.deploy'."
I finally gave in and downloaded Visual Studio 2010 Pro, rebuilt the project, and republished it and it installed just fine. This Add-in is awesome - just what Visio 2010 needs. The real question is, why the heck can't (or won't) Microsoft provide this functionality in Visio?
Excellent!
It worked without any problems.
Very useful add-in.
Great stuff. Works a treat. Thanks.
This is excellent - installed like a charm, and did everything required from the Visio model.
Thanks so much!
Brilliant ! Worked first time and saved me hours of typing in SQL Server Management Studio. My most valued add-in for Office by a long way. It's also worth highlighting the value of the Validate Data Model option during the development phase to highlight silly errors, and save even more time. Cheers Alberto.
Seems to work great.
Thanks much.
Still can't figure out why MS did away with this.
This is really awesome!!!
Hi!
I wanted to check out your add in today with Visio 2010 Professional, downloaded from the MSDNAA service, running on Windows 7 32bit, but never managed to make the add-in start successfully.
After initial problems to even run the setup script in the "publish" folder, I managed to get it installed via the above mentioned installation of the Visual Studio 2010 Tools for the Office System 4.0 Runtime (x86 version).
One major problem for me is that I can't even check due to which reason the add-in fails to load. I tried to set the environment variables VSTO_SUPPRESSDISPLAYALERTS (on the command line -> "SET VSTO_SUPPRESSDISPLAYALERTS=0") and VSTO_LOGALERTS=1, but that doesn't change anything.
Currently I do not have Visual Studio installed.
Any ideas how to further proceed?
Kind regards
Chris
Hi,
I've managed to install your add-in but I cannot get it to Load.
In the Add-Ins manager, I am seeing the following message at the bottom:
Load Behavior: Not loaded. A runtime error occurred during the loading of the COM Add-in.
This seems to be the same problem Christian is having.
My specs: Vista 32bit, .NET framework 4 and Microsoft Visual Studio 2010 Tools for Office Runtime (x86) installed, Visio 2010 premium (installed as a stand alone rather than as part of an MS Office suite). I've made sure that visio doesn't require add-ins to be signed by a trusted publisher.
I do not have Visual Studio installed.
Anyone else running into this problem, found a work-around, or can one of you who have had success with this Add-In possibly post your install procedure and specs?
Thank you,
Alex
Alex, Christian
Please drop me an e-mail at alberto dot ferrari at sqlbi dot com, I will send you the latest release, which should be installable without the need to recompile it with Visual Studio.
Hopefully this will solve your issues.
Error on the link to your add in.
Matt,
Sorry fot this, the website has some problems, we are working on it, please try later.
Thanks for the feedback.
I was able to get it downloaded. I can't tell you how much I appreciate you building this tool! It's freakin' fantastic! I have missed it so much since Enterprise Architects.
You know, I love Visio to develop simple databases and I have written a Visio add-in that performs the
To @ALL:
Last version, 1.1 is available on the SQLBI site, it should address the installation problems you have faced, I tested on a machine without Visual Studio and Visio only installed, it worked fine.
Have fun
Just a note of thanks! I am currently in a db class making ER diagrams. I could not believe it when Visio could not output SQL. What the heck is MS thinking? Just when I am amazed at win7, they have to make this kind of incomprehensible decision? Hey maybe you could sell your addin to the MS Visio team for $1,000,000 :-). They obviously do not have very bright management! Thanks again!
Great tool, thank you!
Installed an ran perfectly on my Windows 7 (64 bit) machine with 64 bit Visio 2010.
John Tarbox
What can I say Alberto,
You have returned a feature that originally caused me to love Visio prior to Microsoft buying it. I had dispaired that Microsoft removed this feature from the easiest modeling tool I have ever used.
Thank you so much for bringing it back to me!
Cool, Thanks Alberto.
Downloaded & installed it. Looks the business & intend to use it for real in the next few weeks.
Thanks a million! I can't believe that Visio doesn't at least support SQL Server integration. Way to go!
Thanks a lot. Great Tool. Unzipped, rebuild, published and installed on a Windows 7 64-bit Machine. Worked fine!
Downloaded, installed, works perfectly, thanks!
I had to build it myself (got the cert error with the Publish .exe), but that was simple and it worked great! Thanks so much!
Very nice. This saved me the day or so you put into it and all the followup hours.
Brilliant!
Hi Alberto,
what a great tool! If only I could install it. I'm using Win 7 64bit and Office 2010 32 bit, Visio Premium 2010. I get this error during installation. I believe if I rebuild it using Visual Studio 2010, it will work (but VS 2010 is difficult to get for me).
Installing Office customization
There was an error during installation.
From:
System.Security.SecurityException: Customized functionality in this application will not work because the certificate used to sign the deployment manifest for SqlBi.Visio.ForwardEngineer or its location
Same error as above, have enabled non trusted addins and added the location of the install files to trusted location, still no joy.
win7 32bit, visio 2010 32 bit
any advice ?
Very nice!
It doesn't create triggers though...
It doesn't script UDF's, Stored procedures as well as not doing Triggers.
Any chance of getting it to do these also ?
Well done...... good tool.
@Simon,
Unfortunately, the dll I use to gather data from Visio is very limited, most of the interfaces exposed return errors as if it has been developed quickly and without the real will to let programmers interact with the Visio internals. Moreover, it is not documented anywhere.
What we have now is the best I succeeded in finding by myself. Moreover, I don't have any hope that something can change in the future... unless Microsoft will read this post, which is something they don't do.
I would post an item on Connect but, AFAIK, I cannot post suggestions to the Office dev team.
Genious tool Alberto. Will save me lots of work in the future.
Thanks
Frode M.
Good stuff. Saved me a lot of leg work!
Work fine thanks
Awesome!
Anyone added to it yet? I need a couple of features
you saved days of work to me because i did not want to believe that the ddl generation was being stripped off from Visio 2010.
It worked as a breeze, and i did not ever need to install the whole Office 2010 but just the Visio itself.
Keep it running Alberto, you have fans!
You rock! Good job.
Great tool Alberto!! You really saved my ass, i completed a whole about 50 tables ERD using Visio 2010 and i didn't realize it couldn't generate the script until i was done, cab approvals and the like.
I can't thank you enough! You should enable paypal donations or so...
Great tool,
how about creating a project on codeplex in order to make this tool grow?
Brilliant! Thank you very much.
Per the error that a lot of people are getting regarding the trust or certificate in Vista or Windows 7, it's a very simple problem and isn't the developer's fault. Simply right-click the zipfile, click "Unblock", click "OK", unzip, then execute.
BTW - Thank you Alberto! This is definitely what I was looking for an is a viable solution for myself; it will be much used.
As you might already know I have written an add-in for Microsoft Visio 2010 which makes it able to forward
Just wanted to add a note of thanks - I had to re-publish like the others above, but it works well. I appreciate you making this available.
That looks very promising.
Are you going to work on an Add-in for Access 2010 as well?
@dfpp, the project is now on codeplex, in better hands than mine. I think they are developing oer drivers like Oracle and maybe access.
@everybodyelse thanks a lot for all your comments, very rewarding!
You rock Alberto. Pretty weasely of them to take it out of 2010. Apparently MS assumes that data modeling should only happen at the Visual Studio level now? Sigh...
Awesome tool! Thank you so much, you are the greatest. Cheers! Joe
Thanks Alberto for a very useful tool that should never have disappeared from Visio. What were they thinking!!!!
I have installed the addin and looks like it is installed fine. After that I ran the validate data model part where i got few errors. I fixed the error and then ran the forward engineer process to generate the sql file. The forward engineer process works fine with 0 errors in the visio output window but the file is not generated. I have tried to generate the file in the same folder (network) as data model and also on my local drive but somehow the file is not generated though the forward engineer process is finished.
Any idea?
Woww... very nice plugin...very handy...thanx a lot...
Nice Plugin...Thanx.
Your plugin is great but i miss one option. I can set namespace in table properties and I expect it to be used as table schema. is it possible you could add such functionality into the plugin?
Thankx
@Krzysztof,
unfortunately, the table namespace is among the properties that cannot be read using the interface. Thus, the feature cannot be implemented, afaik. But I got used to name my tables as schema.name, the addin will recognize that pattern and create both the schema and the table in the right schema for you,
hope it helps.
Excellent it helped me.
Cudos
Installation was fine. When I go to the trust center, it shows it as unavailable. I try to make it available, but it does not keep the setting. So, I am unable to view the new ribbon. Any ideas? Using Visio Pro 2010 on a Win7 64-bit O/s. Thanks
@Thomas,
Please check the latest release and info on CodePlex, where the project is currently hosted and managed.
I no longer own the source.
Fantastic. Thanks for this great plugin. The fact that it validates the ERD as well is really good.
Thank once again.
Alberto, you have a great idea! Contratulations!
I received the same exception Scott did. Do you know how solve this problem?
Thank you!!!
I'm trying to install the Visio Forward Engineer Addin on my Windows 7 64 bits. The problem is that it says "Visio Forward Engineer has been successfully installed." but the COMM Add-Ins keeps blank.
Am I doing something wrong? :(
Thank you.
Isabel (and everybody else)...
The sources of the tool are on codeplex, I no longer follow the development of the tool. You might have a better luck asking there.
Sorry for that, but I donated the project to public domani because I did not have time to follow it
Exactly what I'm looking for but I need it for Visio 2007. Got the code so I can create my own version? It'd be a huge leg up to not start from scratch as I have not done Visio VBA before either.
Thanks in advance.
I'm one of those bad developers that rarely models or plans their database out. Usually my apps are fairly small and only worked on by me so I can usually figure it out in my head what's needed. However having started a new job, and thinking about presenting myself more professionally I decided to model the database for an app I'm about to build first and the only Office compatible tool I had to hand was Visio 2010. I haven't used it for years but remember it did a forward Engineer way back when. I've just finished my model and started looking around for the Forward Engineer option and cannot believe it's not there, especially seeing as I used the SQL provider and intend to host in MSSQL. Thank god for you sir! I shall give this a try!
I have identified 2 more issues with the add-in:
1. If a table does not have PK (only basic not unique index) the tool create this index like Clustered PK.
2. It does not recognize varchar(MAX) and similar datatypes.
I am using SQL Server 2008 R2 (just in case).
Can you fix it?
I have read the discussion and do know it could be difficult, but anyway I hope it is possible. Otherwise, it is impossible to use it because I cannot trust the add-in at the moment.
Cheers
Thank you so much for building this and donating it to code plex.
Works like a charm :D
from codeplex:
This addin TOTALLY ROCKS! Great error checker EXCELLENT DDL, enforces all the things you look for as a BI expert without having to fire up MS VS 2010! THANKS!
Worked like a charm! Thank you :)
this is awesome...in my last project i did not about this tool and I had to recreate all scripts again after i designed table in VISIO...
I cant install, the exe is corrupted it saids it is not a win32 application
I have meet the same problem Christian was having.
Would you please send me the latest release?
My email is [email protected]
Thank you very much!
@Erica,
Alberto, excellent Plugin
I have installed and used the lastest release on Windows 7 x64 with Visio 2010 and it's really good.
thank you very much
Hello Alberto,
just a silly question. In installed the add in in Office 2010 Dutch version. I see the extra Database section with a couple of features (reverse engineering) however I dont see the the Forward engineer function and data validation function, the one I needed. Do I overlook something?
Thx in advance
Ludwig
A co-worker and I are both trying to run this. He gets the error that it is not a valid win-32 app. He is using 32 bit xp. I am using 64-bit windows 7 and get the error that "A runtime error occured during the loading of the COM Add-in" I do not have Visual Studio 2010 installed on my computer. Do you have a newer version that solves these issues?
Ludwig,
In Visio 2010 "Database" ribbon tab with features such as Reverse Engineer, Refresh, and Manage Database Drivers, is part of Visio Professional; it is not part of this add-in.
-Tom
OUTSTANDING ALBERTO!!!
This is brilliant. Alberto your add-in has saved me days of work. Many, many thanks.
Cool tool!This is what I needed!Thank you, God bless you!
When is v2 coming out? Would love to give it a try even as beta...
I am not planning any further development on this tool. The source code is not on codeplex, I guess there is the place for getting more information.
Thanks.
Hi... i cant create script with nonclustered primary keys. i dont know how.
I have visio 2010.
Can you help me?
Thanks a lot for this - it worked first time on an installed Visio 2010
Great job, thanks.
Alberto, thank you so much for creating this tool. I installed it and worked "out of the box". You ROCK!!!
Utilizei o addin como uma ferramenta de trabalho e estou muito satisfeito. Além do recurso possuir uma praticidade e simplicidade no seu manuseio, ele me auxiliou na validação do meu modelo criado pelo visio. Então deixo aqui o meu agradecimento e parabenização a você, Alberto Ferrari, ao trabaho desenvolvido.
Ps. Você está referenciado no meu estudo.
Suddenly realised I could not even print my SQL from Visio - quick google got me here. Downloaded, installed and used within 5 minutes!
Thank you so much!!
Sarah
I struggled installing this on Windows 7-64bit, Office 2010 installed, Office 2013 installed, Visio 2010 Pro installed, Visio 2013 installed.
FIX: put setup.exe in c:\publish and run from there. Bingo!! It installed and works like a charm.
One other thing ...
FIX: I had to choose install "Just for me".
When I chose install "For everyone", Visio 2010 did NOT present the "Forward Engineer" ribbon tab. | http://sqlblog.com/blogs/alberto_ferrari/archive/2010/04/16/visio-forward-engineer-addin-for-office-2010.aspx | CC-MAIN-2017-39 | refinedweb | 4,170 | 66.54 |
I am trying to send a text message using Twillio API. I have to import the following libraries
import java.util.*;
import com.twilio.sdk.*;
import com.twilio.sdk.resource.factory.*;
import com.twilio.sdk.resource.instance.*;
import com.twilio.sdk.resource.list.*;
You're actually talking about two separate issues: setting your classpath and importing things from the classpath.
Classpath
Your classpath is all of the code you have access to in your sketch. It's generally a list of library jars, as well as the JDK.
So your first step is to add the jars to your Processing sketch. Here is a description of how to add a library to a Processing sketch. This is the same as setting your classpath. Find the Twilio library for Processing, or add the jar to your sketch directory manually.
Note that java.util is part of standard Java, so you don't have to add it to your sketch. It's already there.
Importing
Once you have the appropriate libraries added, you can use the classes and methods on your classpath. You could use their fully qualified name by including the package information like this:
void setup(){ java.util.Date d = new java.util.Date(); }
But that can get annoying, so instead, you can tell Processing where to look for unqualified names by importing them:
import java.util.Date; void setup(){ Date d = new Date(); }
Note that import statements don't actually do anything. They don't "add" a library to your sketch. They just tell your code where to look for classes. And those classes have to be on your classpath first.
What Next
If you still can't get it working, post the specifics of what you've tried and any errors you're receiving, and we'll go from there. | https://codedump.io/share/VuPJx6sfJAp5/1/sending-txt-message-using-twilio-java-and-processing | CC-MAIN-2018-22 | refinedweb | 302 | 66.84 |
SVG (Scalable Vector Graphics) is an XML based language to define vector based graphics.
In JavaFX we can construct images by parsing SVG paths. Such shapes are represented by the class named SVGPath. This class belongs to the package javafx.scene.shape.
By instantiating this class, you can create a node which is created by parsing an SVG path in JavaFX.
This class has a property named content of String datatype. This represents the SVG Path encoded string, from which the image should be drawn.
To draw a shape by parsing an SVG path, you need to pass values to this property, using the method named setContent() of this class as follows −
setContent(value);
To Draw a shape by parsing an SVGPath required shape in JavaFX by parsing an SVGPath. To do so, instantiate the class named SVGPath which belongs to a package javafx.scene.shape. You can instantiate this class as follows.
//Creating an object of the class SVGPath SVGPath svgpath = new SVGPath();
Set the content for the SVG object using the method setContent(). To this method, you need to pass the SVGPath. Using which, a shape should be drawn in the form of a string as shown in the following code block.
String path = "M 100 100 L 300 100 L 200 300 z"; //Setting the SVGPath in the form of string svgPath.setContent(path);
In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene.
Pass the SVGPath (node) object created in the previous step as a parameter to the constructor of the Group class. This should be done in order to add it to the group as follows −
Group root = new Group(svgpath); x method as follows.
public static void main(String args[]){ launch(args); }
Following is a program which generates a shape by parsing SVG path using JavaFX. Save this code in a file with the name SVGExample.java.
import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.SVGPath; import javafx.stage.Stage; public class SVGExample extends Application { @Override public void start(Stage stage) { //Creating a SVGPath object SVGPath svgPath = new SVGPath(); String path = "M 100 100 L 300 100 L 200 300 z"; //Setting the SVGPath in the form of string svgPath.setContent(path); //Creating a Group object Group root = new Group(svgPath); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Drawing a Sphere"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } }
Compile and execute the saved java file from the command prompt using the following commands.
javac SVGExample.java java SVGExample
On executing, the above program generates a JavaFX window displaying a triangle, which is drawn by parsing the SVG path as shown below. | https://www.tutorialspoint.com/javafx/2dshapes_svgpath.htm | CC-MAIN-2019-35 | refinedweb | 484 | 64.3 |
Hello,
i've got some trouble at trying to use the CLAPACK library for Windows
version 3.0 (that i've downloaded from) and i would be very
grateful if you could help me out.
i'm using the Visual C++ 6.0 compiler. it appears to be a linking issue:
__________________________________________________________________________
myAlgo.obj : error LNK2001: unresolved external symbol "int __cdecl
dsygv_(long *,char *,char *,long *,double *,long *,double *,long *,double
*,double *,long *,long *)" (?dsygv_@@YAHPAJPAD10PAN0202200 at Z)
__________________________________________________________________________
(I have previously used GSL on the same platform, without trouble. Now, I
need these generalized eigenvalue problem resolution routines.)
Here are my (vain) trouble shooting attempts:
-i've made my routine calling identical to how it's done in ddrvdg.c (
(which calls the very same subroutine dsygv_ without problem in testing
project xeigtsdt):
#include "blaswrap.h"
#include "f2c.h"
extern /* Subroutine */ int dsygv_([...]);
again error LNK2001
-i've rechecked that all CLAPACK .lib libraries were declared in the
Project Settings->Link->Input: ok
-i've run the batch tests provided using the command line prompter 4NT: ok;
-i've reinstalled and rebuilt the CLAPACK library, scrupulously following
instructions given in the readme file MSWin-Notes.txt: ok
-i've rerun the batch tests: all ok
-i've made all my Project Settings rigorously the same as those for the
xeigtsdt testing project provided in the package (since the latter works):
again error LNK2001
-i've made a new source file myTest.cpp with the mere example code given in
the CLAPACK FAQ-1.9, that i've added directly to the project xeigtsdt, but
again i've got the same type of error (while the same subroutine dgesvd_
is called without problem by derred.c in the same project) :
__________________________________________________________________________
----Configuration: xeigtstd - Win32 Debug----
Linking...
myTest.obj : error LNK2001: unresolved external symbol "int __cdecl
dgesvd_(char *,char *,long *,long *,double *,long *,double *,double *,long
*,double *,long *,double *,long *,long *)"
(?dgesvd_@@YAHPAD0PAJ1PAN122121211 at Z)
Eig_Debug/xeigtstd.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
xeigtstd.exe - 2 error(s), 0 warning(s)
__________________________________________________________________________
Thanks a lot for your help, which will hopefully prove successful. If you
need extra information, please feel free to ask.
St?phane Allaire
LaTIM (Laboratoire de Traitement de l'Information M?dicale), Brest, France | http://icl.cs.utk.edu/lapack-forum/archives/lapack/msg00023.html | CC-MAIN-2014-42 | refinedweb | 381 | 65.52 |
FYI - I'm coding in actionscript 3.0 but didn't see an area to post for that language.
I made a simple character and a block. I'm trying to get it so that if the character will touch the box, it wont let him move to imply a wall/collision.
I've got him moving but the problem is that it doesn't PREdetect the collision. It lets him overlap the block once, then when I try to move again, it wont go anywhere because NOW (that it's too late), he's overlapping and thus colliding. Anyone know how I can very simply edit this code so the player isn't allowed to overlap the block in the first place?
import flash.display.Sprite; import flash.events.KeyboardEvent; var block:Sprite = MovieClip(blockInst); var player:Sprite = MovieClip(playerInst); var speed:Number = 10; stage.addEventListener(KeyboardEvent.KEY_DOWN, playerMovement); function playerMovement(key:KeyboardEvent):void { if (player.hitTestObject(block)) { trace("blocked"); } else { switch (key.keyCode) { case 37 ://Left player.x -= speed; break; case 39 ://Right player.x += speed; break; case 38 ://Up player.y -= speed; break; case 40 ://Down player.y += speed; break; } } }
Yea so this is a problem of collision response. Once a collision is detected what do you do? Well in this case you should move your player back just before the collision point. So if there is a collision, shift back the player's position so that there is not a collision anymore. Get it? | http://www.daniweb.com/software-development/game-development/threads/417767/pre-collision-detection-question | CC-MAIN-2014-15 | refinedweb | 248 | 68.47 |
Hi,
I have two questions which are related to the usage of the "uber-jar" in an IDE like Eclipse:
Question 1) Why the file "uber-jar-6.5.5-sources.jar" does not contain at least the source code of the open source libraries which are included in the uber-jar? Why it is either empty or not provided by Adobe at all?
For example, why it does not contain the source code of "org.apache.jackrabbit.api.security.user.UserManager"?
At least the file "uber-jar-6.5.5-javadoc.jar" contains the Javadoc of the above-mentioned class, but why the file "uber-jar-6.5.5-sources.jar" does not contain its source code? It is an open source project and you can see links to its source repository here:
Therefore I do not understand why Adobe did not include it (and the source code of other open source libraries) in the file "uber-jar-6.5.5-sources.jar".
In case if Adobe does not provide the "sources" file for its uber-jar at all (it is currently unavailable under the Adobe's public repo, as of 4th March 2021), then why Adobe does not provide it?
Question 2) Why the file "uber-jar-6.5.5-javadoc.jar" does not contain at least the Javadoc of some proprietary classes which are not open source? (I don't mean their source code here as these seem to be some proprietary "closed" code of Adobe, but at least their Javadoc should be available.)
For example, why it does not contain at least the Javadoc of all classes which are located in the package "javax.jcr" and its sub-packages, like for example the class "javax.jcr.security.AccessControlManager"?
It makes the life of an AEM developer who uses Eclipse more difficult.
The problem with the file uber-jar-6.5.5-apis.jar is that in Eclipse you can only attach one jar file as a source of the Javadocs for it and also you can attach only one jar file as a source of the source code for it.
For example, I can't specify for the file uber-jar-6.5.5-apis.jar in Eclipse multiple jar files with the source code of the Apache Jackrabbit library and multiple other open source libraries which are included in the uber-jar, if I already use the file "uber-jar-6.5.5-sources.jar" (or any other single jar file) as the source of the source code for it.
I am used to being able to display all possible Javadocs and source codes of all libraries using the keys F2 and F3 in Eclipse. It disturbs my workflow and costs me additional time when I have to search for the Javadoc or source code of a given method/class in other places (e.g. on the Internet for each single open source library which is included in the Adobe's uber-jar).
Does anyone know a solution to the above-mentioned problems? Or even better, will you Adobe fix these issues and make the life of the developers using your product easier?
Thank you in advance for your answers.
Bugs typically go via Support tickets. If this was working once but not anymore (thus rather a regression) it might be possible that it gets a higher priority, but I am not an expert in the details of our support processes.
Hi @Jörg_Hoh, thank you for the answer, I will create a new support ticket for the bug regarding the Javadoc jar.
Regarding the other problem, i.e. the source code of open source projects for the uber-jar (vs. "aem-sdk-api"):
I have now checked that only an empty sources jar "aem-sdk-api-2021.4.5181.20210416T172032Z-210325-sources.jar" (without any source code included) can be downloaded for the "aem-sdk-api" artifact () using Maven. - This is the same situation as for the "uber-jar", for which either no or only an empty sources jar can be downloaded. - I tested it by creating a new, dummy Maven project with a dependency to the above version of the artifact "aem-sdk-api" and by downloading sources for this Maven Dependency.
So, it seems that most probably I will have to post an idea in the ideas section for including the source code of the open source projects in the sources jar for the uber-jar.
When I opened various classes from the "aem-sdk-api" jar, then only a decompiled source code of these classes has been shown (I have currently the CFR configured as my Decompiler in Eclipse), without any comments in that source code. A correct Javadoc jar has been downloaded for the "aem-sdk-api" artifact and I can see the Javadoc of a class from this artifact - but only until I open its decompiled source code. As soon as I decompile its source code on the fly by opening it, I can't see the Javadoc of the given class anymore. - The decompiled source code overrides the attached Javadoc. - This is the same problem with the Decompiler as described earlier by me in case of the uber-jar (see also a copy of that description below).
Could you please share your knowledge how you managed to configure Eclipse so that it integrates the attached Javadoc into the decompiled source code in your case?
You mentioned earlier that you have Procyon configured as the Decompiler. Are you using the "Enhanced Class Decompiler" plugin for Eclipse ()? If not, which other decompiler plugin are you using?
I copy here also a part of my earlier description of my experience with the decompiler, just in case you maybe missed it:
I ask, because I wonder if you use some other decompiler plugin which works better than the one which I installed. When I select Procyon as the decompiler (under Preferences > Java > Decompiler) and afterwards press F3 on the class "org.apache.jackrabbit.api.security.user.UserManager", then an error is being shown "Editor could not be initialized." Only when I select another decompiler (under Preferences > Java > Decompiler), e.g. "CFR", then I can see the decompiled source code of a class from the uber-jar (or from the "aem-sdk-api"), but without any Javadoc. And after decompiling a given class on the fly by opening its source code, I can't see its Javadoc anymore when pressing F2 on that class, until I restart Eclipse. I.e. in my case the decompiled source code overrides the attached Javadoc which is a big downside for me. I wonder if the decompiler plugin which you use or its specific configuration integrate the attached real Javadoc into the decompiled source code, so that afterwards you see the source code together with the Javadoc. - This could be one of the possible explanations why it works in your case and I would like to know how you configured it to work. Could you please share your knowledge on this subject?
I have configured the above-mentioned decompiler according to the recommendations from its Github page () under the heading "How to check the file associations", i.e. I configured the following file associations in my Eclipse:
- Click on “Window > Preferences > General > Editors > File Associations”
- “*.class” : “Class Decompiler Viewer” is selected by default.
- “*.class without source” : “Class Decompiler Viewer” is selected by default.
I have setup Eclipse (version 2020-12) quite some time ago, I don't know all the settings I changed.
But let me illustrate it with an example I have right in front of me.
NamespaceRegistry namespaceRegistry = session.getWorkspace().getNamespaceRegistry();
* I select "NamespaceRegistry" and then select "open implementation".
* In the "Type Hierachy" dialog I select "NamespaceRegistry - javax.jcr".
* Eclipse opens the file "NamespaceRegistry.class", which is part of the "jcr-2.0.jar" Maven dependency (according to the package explorer).
* In this file I see java comments as well as the javadoc.
For the settings:
* Right now I set FernFlower as standard (the way you described), but most likely I need to change it to something which can deal with newer versions of bytecode.
And that works for the majority (all?) of the opensource libraries I use. To be honest, I never thought that this is a problem at all.
Views
Replies
Total Likes | https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/why-the-quot-uber-jar-6-5-5-sources-jar-quot-does-not-contain/m-p/407048 | CC-MAIN-2022-27 | refinedweb | 1,389 | 62.27 |
The general syntax to create a Swift dictionary is
var dict: Dictionary<Key, Value>. This code creates a mutable instance of the Dictionary type called dict. The declarations for what types the dictionary’s keys and values accept are inside the angle brackets (
Key and
Value.
<>), denoted here by
The values stored in a dictionary can be of any type, just like the values in an array. The only type requirement for keys in a Swift Dictionary is that the type must be hashable. The basic concept is that each
Key type must provide a mechanism to guarantee that its instances are unique. Swift’s basic types, such as String, Int, Float, Double, and Bool, are all hashable.
Before you begin typing code, let’s take a look at the different ways you can explicitly declare an instance of Dictionary:
var dict1: Dictionary<String, Int> var dict2: [String:Int]
Both options yield the same result: an uninitialized Dictionary whose keys are String instances and whose values are of type Int. The second example uses the dictionary literal syntax (
[:]).
As with Swift’s other data types, you can also declare and initialize a dictionary in one line. In that case, you can explicitly declare the types of the keys and values or take advantage of type inference:
var companyZIPCode: [String:Int] = ["Big Nerd Ranch": 30307] var sameCompanyZIPCode = ["Big Nerd Ranch": 30307]
Again, these two options yield the same result: a dictionary initialized with a single key-value pair consisting of a String key,
"Big Nerd Ranch", and an Int value,
30307.
It is useful to take advantage of Swift’s type-inference capabilities. Type inference creates code that is more concise but just as expressive. Accordingly, you will stick with type inference in this tutorial.
Time to create your own dictionary. Start with a new macOS playground called Dictionary. Declare a dictionary called movieRatings and use type inference to initialize it with some data.
Listing 10.1 Creating a dictionary
import Cocoa
var str = "Hello, playground"var movieRatings = ["Tron": 4, "WarGames": 5, "Sneakers": 4]
(Since dictionaries are not ordered, the sidebar result may show the key-value pairs in a different order each time your code executes.)
You created a mutable dictionary to hold movie ratings using the Dictionary literal syntax. Its keys are instances of String and represent individual movies. These keys map onto values that are instances of Int that represent the ratings of the movies.
As an aside, just as you can create an array literal with no elements using
[], you can create a dictionary with no keys or values using
[:]. As with arrays, this syntax omits anything the compiler could use to infer the key and value types, so that information would have to be declared explicitly.
Accessing and Modifying Values
Now that you have a mutable dictionary, how do you work with it? You will want to read from and modify the dictionary. Begin by using count to get some useful information about your dictionary.
Listing 10.2 Using
count
var movieRatings = ["Tron": 4, "WarGames":... ["Tron": 4, "WarGames": 5, "Sneakers": 4] movieRatings.count 3
Now, read a value from the movieRatings dictionary.
Listing 10.3 Reading a value from the dictionary
var movieRatings = ["Tron": 4, "WarGames":... ["Tron": 4, "WarGames": 5, "Sneakers": 4] movieRatings.count 3 let tronRating = movieRatings["Tron"] 4
The brackets in
movieRatings["Tron"] are the subscripting syntax you have seen before. But because dictionaries are not ordered, you do not use an index to find a particular value. Instead, you access values from a dictionary by supplying the key associated with the value you would like to retrieve. In the example above, you supply the key
"Tron", so tronRating is set to
4 – the value associated with that key.
Option-click the tronRating instance to get more information (Figure 10.1).
Figure 10.1 Option-clicking
tronRating
Xcode tells you that its type is Int?, but movieRatings has type [String: Int]. Why the discrepancy? When you subscript a Dictionary instance for a given key, the dictionary will return an optional matching the type of the Dictionary’s values. This is because the Dictionary type needs a way to tell you that the value you asked for is not present. For example, you have not rated Primer yet, so
let primerRating = movieRatings["Primer"] would result in primerRating having type Int? and being set to
nil.
A dictionary’s keys are constants: They cannot be mutated. The informal contract a dictionary makes is something like “Give me a value, and a key to store it by, and I’ll remember both. Come back with the key later, and I’ll look up its value for you.” If a key were able to mutate, that could break the dictionary’s ability to find its related value later.
But values can be mutated. Modify a value in your dictionary of movie ratings:
Listing 10.4 Modifying a value
... movieRatings.count 3 let tronRating = movieRatings["Tron"] 4 movieRatings["Sneakers"] = 5 5 movieRatings ["Sneakers": 5, "WarGam...
As you can see, the value associated with the key
"Sneakers" is now
5.
There is another useful way to update values associated with a dictionary’s keys: the updateValue(_:forKey:) method. It takes two arguments: The first,
value, takes the new value. The second,
forKey, specifies the key whose value you would like to change.
There is one small caveat: updateValue(_:forKey:) returns an optional, because the key may not exist in the dictionary. But that actually makes this method more useful, because it gives you a handle on the last value to which the key mapped, using optional binding. Let’s see this in action.
Listing 10.5 Updating a value
... movieRatings["Sneakers"] = 5 5 movieRatings ["Sneakers": 5, "WarGam... let oldRating: Int? = 4 movieRatings.updateValue(5, forKey: "Tron") if let lastRating = oldRating, let currentRating = movieRatings["Tron"] { print("old rating: \(lastRating)") "old rating: 4\n" print("current rating: \(currentRating)") "current rating: 5\n" }
Adding and Removing Values
Now that you have seen how to update a value, let’s look at how you can add or remove key-value pairs. Begin by adding a value.
Listing 10.6 Adding a value
... if let lastRating = oldRating, let currentRating = movieRatings["Tron"] { print("old rating: \(lastRating)") "old rating: 4\n" print("current rating: \(currentRating)") "current rating: 5\n" } movieRatings["Hackers"] = 5 5
Here, you add a new key-value pair to your dictionary using the syntax
movieRatings["Hackers"] = 5. You use the assignment operator to associate a value (in this case,
5) with the new key (
"Hackers").
Next, remove the entry for Sneakers.
Listing 10.7 Removing a value
... if let lastRating = oldRating, let currentRating = movieRatings["Tron"] { ... } movieRatings["Hackers"] = 5 5 movieRatings.removeValue(forKey: "Sneakers") 5
The method removeValue(forKey:) takes a key as an argument and removes the key-value pair that matches what you provide. Now, movieRatings has no entry for Sneakers.
Additionally, this method returns the value the key was associated with, if the key is found and removed successfully. In the example above, you could have typed
let removedRating: Int? = movieRatings.removeValue(forKey: "Sneakers"). Because removeValue(forKey:) returns an optional of the type that was removed, removedRating would be an optional Int. Placing the old value in a variable or constant like this can be handy if you need to do something with the old value.
However, you do not have to assign the method’s return value to anything. If the key is found in the dictionary, then the key-value pair is removed whether or not you assign the old value to a variable.
You can also remove a key-value pair by setting a key’s value to
nil.
Listing 10.8 Setting the key’s value to
nil
... if let lastRating = oldRating, let currentRating = movieRatings["Tron"] { ... } movieRatings["Hackers"] = 5 5
movieRatings.removeValue(forKey: "Sneakers")movieRatings["Sneakers"] = nil nil
The result is essentially the same, but this strategy does not return the removed key’s value. | https://basiccodist.in/dictionary-in-swift/ | CC-MAIN-2022-21 | refinedweb | 1,329 | 56.25 |
Release notes/0.44/fr
Contents
- 1 Inkscape 0.44: en bref
- 2 Performance
- 3 SVG conformance
- 4 Interface
- 5 Tools
- 6 Clipping and masking
- 7 Transformations
- 8 Connectors and automatic layout
- 9 Selective tracing with SIOX
- 10 Snapping
- 11 Sublayers
- 12 Markers
- 13 Extension effects
- 14 Formats
- 15 Miscellaneous shortcuts
- 16 Miscellaneous improvements
- 17 Miscellaneous bugfixes
- 18 Translations
- 19 Internal
- 20 Known problems
- 21 Previous releasesique que d'autres améliorations de l'outil noeud.
- Les extensions sont activées par défaut et fonctionnent sur la plupart des plateformes.
- Un meilleur support du SVG : élément <switch> element, profils de couleur ICC pour les it.
-.
- Drag and Drop of colors onto a fill/stroke indicator sets the fill and stroke of the selected object(s) correspondingly.
-.
Tool style indicators
For each object-creating tool (shapes, Pen/Pencil, Calligraphic, Text), the Controls bar (above the canvas) now includes a style indicator on the right. This indicator shows you which style the newly created object will have.
- The indicator correctly displays whichever style the tool is set to use - the global "last set" style or that tool's fixed style. For example, clicking on a palette swatch (even with nothing selected) changes the "last set" color and, if your tool is set to use the last set color, its indicator is updated, giving you an idea of your "brush" before you start to draw. to an illustration after it is ready.
- New controls: the new object snapping features required their own property widgets, and you can set the snapping sensitivity with a slider, or let it snap regardless of distance (grid only).
- Rearrangements within Document Properties: everything snapping-related was collected on one page; Grid and Guide widgets are on their own, the same page. For better that, and now only a few details are missing from full Gnome-HIG compliance.
- Updated Creative Commons Licenses: Updated CC licenses to the latest 2.5 versions by default in the license tab of the metadata dialog.. We're working on making more actions configurable.
On startup, Inkscape reads its keyboard shortcuts from
share/keys/default.xml. That file is a copy of
inkscape.xml in the same directory, which also contains keyboard emulation profiles for other vector editors:
xara.xml: Xara X/Xara Xtreme/Xara LX keys
You can copy any of these over default.xml to use that profile. In all profiles, those keys which are not used by the corresponding program still have their Inkscape bindings. If you can contribute a profile for some vector editor that we don't yet have, we will appreciate that. The files have a simple XML-based format described in
inkscape.xml.
You can also customize some of your keybindings without overwriting the main
default.xml. If your profile directory (
~/.inkscape on Linux) contains a
keys subdirectory with a
default.xml file, the keybindings from that file will overlay (i.e. add to, and override in case of a conflict) the default bindings. The format of your own
default.xml is the same as that of the main
default.xml.
Menus
- Zoom commands in the View menu are moved to a submenu; the Zoom In and Zoom Out commands are added to that submenu.
- Clone commands are moved into a submenu in Edit menu and given more descriptive names and tips.
- Pattern commands (Objects to Pattern and Pattern to Objects) are moved into a submenu in Object menu, under the new Clip and Mask submenus.
- The contents of the Effects menu are categorized into submenus, and several effects are renamed to use more intuitive names.
Statusbar
- In Selector,.
- In Selector, objects selected in groups are now identified as such, and the group ID is given, for example:
- Rectangle in group g212 (layer content)
- If selected objects have different parents within one layer (for example, if one is selected in a group and another outside it), the number of parents is reported:
- 2 objects of types Rectangle, Path in 2 parents (layer content)
- If objects are in different layers, only the number of layers is reported since this also implies different parents:
- 2 objects of types Rectangle, Path in 2 layers
-
- In Node tool, deleting node(s) by Del/Backspace keys or by Ctrl+Alt+clicking a node now tries to preserve, as much as possible, the current shape of the path. This means that the nodes adjacent to those being deleted have their handles adjusted to approximate the form that the path had before deletion. For example, if you Ctrl+Alt+click a path twice, once to add a new node and then to delete it, the path will not change at all (or change very slightly). The old deletion behavior without adjusting handles is still available via Ctrl+Del or Ctrl+Backspace.
Preserving positions of nodes and handles
- When you switch the type of the selected node to Smooth or Symmetric by pressing Shift+S/Shift+Y, you can now preserve the position of one of the two handles by hovering your mouse over it, so that only the other handle is rotated/scaled to match.
- Similarly, when you join endnodes by pressing Shift+J, you can preserve the position of one of the two nodes by hovering your mouse over it, so that only the other node is moved.
Miscellaneous
-.
Calligraphic pen
Tremor
- Even when using a graphics tablet with pressure sensitivity, the Calligraphy pen's strokes often look too smooth and artificial. To enable a more natural look, the new Tremor parameter is added to the Calligraphy tool in this version. Adjustable in the Controls bar from 0.0 to 1.0, it will affect your strokes producing anything from slight unevenness to wild blotches and splotches. This significantly expands the creative range of the tool.
Pen width
- In all previous versions, pen width depended on zoom in such a way that the strokes appeared the same visible width at any zoom, but were in fact narrower at zoom-in and wider at zoom-out. This behavior makes sense if you want to keep the same "feel" of the pen regardless of zoom; for example, if you zoomed in to make a small fix to your drawing, it's natural that your pen becomes physically smaller but feels the same to you. So, this behavior is kept as the default, but now we also added an alternative mode where your pen width is constant in absolute units regardless of zoom. To switch to this mode, use the checkbox on the tool's Preferences page (you can open it by double-clicking the tool button).
- The Width field in the tool's controls bar now changes from 1 to 100, which corresponds to the range from 0.01 to 1.0 in the previous version. If the "width in absolute units" mode is turned on, the value in this fields gives the width of the stroke in px units. In the default mode, the value of 100 gives 100px wide strokes only at 100% zoom, and strokes are correspondingly narrower or wider at other zoom levels.).
Pen tool
- While drawing a path, you can now move the last node you created by the same keys as in Node tool - that is, arrows, with Shift (for 10x displacement) or Alt (screen pixel displacement) modifiers.
- Also, you can switch the not-yet-finalized (red) segment of the path being drawn from curve to line (Shift+L) or back to curve (Shift+U), again the same shortcuts as in the Node tool.
- By popular demand,. The clipping path is returned to the drawing as a regular object; it is inserted on top of the unclipped object in z-order.
-. The mask is returned to the drawing as a regular object; it is inserted on top of the unmasked object in z-order.
-.
- Objects with clippaths or masks are correctly copied/pasted between documents.
Transformations.
Persistent rotation centers
- The position of the center (axis) of rotation and skewing used by Selector is now remembered for all objects and restored when you select those objects again (even after saving and reopening the document). When you move or scale an object, its rotation center is moved or scaled too, so its position relative to the object always remains the same unless you move it explicitly.
- When you have several objects selected, they use the rotation center of the first selected object. If the first object does not have center set (i.e. if it's in a default central position), then several objects will rotate around the geometric center of their common bounding box (as before).
- Shift+click on the rotation center resets it back to the center of the object's box.
- Consequently, dragging the rotation center is now an undoable action; you can press Ctrl+Z to undo the drag.
- Keyboard rotation by [, ] keys with various modifiers, as well as the Rotate tab in the Transform dialog, work around the selected object's rotation center (for multi-object selection, the rotation center of the first selected object).
- Rotation centers are preserved when duplicating, cloning (including clone tiler), grouping/ungrouping, and converting to path.
Pasting size
A number of commands are added to easily scale selected objects to match the size of the object(s) previously copied to the clipboard. They are all in the Paste Size submenu in Edit menu:
- Paste Size scales the whole selection to match the overall size of the clipboard object(s).
- Paste Width/Paste Height scale the whole selection horizontally/vertically so that it matches the width/height of the clipboard object(s). These commands honor the scale ratio lock on the Selector controls bar (between W and H fields), so that when that lock is pressed, the other dimension of the selected object is scaled in the same proportion; otherwise the other dimension is unchanged.
- Paste Size Separately, Paste Width Separately and Paste Height Separately work similarly to the above described commands, except that they scale each selected object separately to make it match the size/width/height of the clipboard object(s).
Connectors and automatic layout
- There have been numerous bugfixes and several improvements to the behaviour of connectors and the connector tool:
- Connectors moved as part of a selection will now stay attached to other objects in the selection, rather than becoming detached from them.
- By default, the Connector tool will not attach connectors to text objects. There is a new checkbox in the connector preferences to control this setting.
- The margins around avoided shapes (used for autorouting connectors) can now be adjusted via the "Spacing" control on the controls bar.
- Automatic Diagram Layout: A new button is available in the Align and Distribute dialog that performs automatic layout of diagrams involving a network of shapes and connectors. Layout is accomplished using force-directed graph layout based on the Kamada-Kawai algorithm. This algorithm treats edges as if they are springs such that the distance between nodes will be proportional to the path length - number of connectors - between them. Disconnected components (where not every shape is connected) will be arranged around the circumference of a circle.
- There is a new..
- Guidelines are made easier to pick. Now you don't need to position mouse exactly over a guideline to activate it; instead there's a small position tolerance (1 screen pixel on each side of the guideline)..
- In Preferences (Selecting tab), options are added allowing the "Select All" command and Tab key selection to work either in the current layer only or in the current layer and its sublayers.
Markers
-.)
- A new Python effect, Render > LaTeX formula, allows you to type in any LaTeX formula and get a vector object with the TeX rendition of this formula inserted into your document. You need to have latex, dvips, and pstoedit installed and in PATH for this to work.
- A new Python effect, Flatten Path, flattens paths in the current selection, approximating each path with a polyline whose segments meet the specified criteria for flatness.
- A new Python effect, Measure Path, attaches a text label to each path in the selection giving the length of that path (in px units).
- The Radius Randomize effect has a new parameter which enables normal distribution of random displacements instead of uniform as before, which gives a more natural feel to the randomized path.
-.
Miscellaneous shortcuts
-.
- In Selector, Ctrl+Enter enters the selected group (making it a temporary layer). Ctrl+Backspace leaves the current layer and goes one layer up in the hierarchy (but not to root)..
- In the Grid Arrange dialog, row/column spacing can now be negative.
- The installation default is now to scale the rounded rectangle corners with the rectangles themselves (the previous default mode, still available as an option, was to keep rounding radii unchanged when scaling rectangles).
- Added a new
--export-area-canvascommand line parameter that causes the exported PNG to contain the full canvas. This option as well as
--export-area-drawingand
--export-areacan now be used along with
--export-idand
--export-id-onlyfor greater flexibility.
- The
--query-*command line parameters now return the true SVG bounding box of the object instead of the Inkscape coordinate system bbox (with inverted Y axis). The new behavior makes more sense for scripting use of Inkscape.
- The dpi value in the Export dialog has had its range extended; now possible values are from 0.01 to 100000.
-.
- The separate "license" and "contributors" dialogs have been merged into tabs on the About dialog. The about dialog now correctly sizes itself to fit the size of the splash SVG (while remaining resizable), and the rendering area is now cropped to the correct aspect ratio when the dialog is resized. The dialog also now displays the build information in the upper right corner.
- In the Transform dialog / Rotate tab, the icon was flipped horizontally to be in line with the direction of positive rotation; the change was applied to the default (now crispy) and legacy icon sets.
- The scale ratio lock button on the Selector controls bar shows a closed lock when pressed and open lock otherwise (same as the layer lock in the statusbar).
- The Browse button on Export dialog now opens the new file chooser, same as those used by Open and Save..
-.
- Scaling of stroke now works for objects that didn't specify stroke-width; before, they always ended up with the default 1px stroke.
- The bounding box for text and flowed text objects did not include stroke width. This has been fixed.
- Stroke miterlimit on text objects was misinterpreted in absolute units instead of multiplies of stroke width (resulting in miter joins rendered as bevel).
- The unfinished path in Pen tool is now cancelled, not finalized, when you switch away from the Pen tool. Apart from being more intuitively correct, this also fixes a crash when you quit Inkscape with the unfinished path in Pen tool.
- Fonts on Win32 now use the native font mapper, meaning that Inkscape's font list is the same as other Windows programs, and the (potentially) very long delay experienced when using fonts for the first time in each session is gone.
-.
- defective inx file for extensions.
- More document memory is now freed when documents are closed.
- EPS output now correctly includes an %%EOF footer.
-.
- There existed a bug in 0.43's Inkboard code that would cause session invitations to not appear on the invitee's screen. This was the result of a mistake in handling GDK modifier flags, and has been fixed.
Translations
- INX files (containing the UI of the external effects) now allow the user visible strings to be translated. This means that effect dialogs, file type selections, and extension names can all be translated by translators.
- Inkscape is now significantly translated to 15 languages: Basque, Catalan, Czech, French, German, Hungarian, Italian, Lithuanian, Russian, Serbian (Cyrillic and Latin), Simplified Chinese, Slovenian, Spanish and Traditional Chinese. Additionally, 23 more languages have some level of translation. Average translation ratio has increased from 49% to 58% in this release.
- Some new translations of tutorials have been brought by contributors: Czech, Portuguese (Brazilian) and Russian.
Problems with libgc-6.7
- Inkscape will hang or crash when linked with this (newest) version of the Boehm garbage collection library. Make sure you use libgc-6.5 or 6.6 until this is sorted out.
Problems with "Composite" option of X.org
- On Linux, Inkscape may crash if you have the "Composite" option enabled in your X.org configuration. To disable this option, comment out this line in your /etc/X11/xorg.conf:
Option "Composite" "Enable"
- so it becomes
#Option "Composite" "Enable"
- and restart X.
Namespaces may need fixing
- Previous versions of inkscape sometimes silently saved documents with wrong namespace URIs. This has been fixed, but such corrupted documents will no longer load successfully. Such documents may require their namespace declarations to be fixed by hand.. However, but it would be nice if you as affected user would inform the gtk-engines maintainers of any further () | https://wiki.inkscape.org/wiki/index.php?title=Release_notes/0.44/fr&oldid=6804&printable=yes | CC-MAIN-2020-16 | refinedweb | 2,833 | 60.45 |
36560/help-referencing-python-package-filename-consists-period
Hi all,
I have a pretty simple question. I am making use of Django and I have a file which is called models.admin.py
Check out the below syntax, this is what I want to do:
from "models.admin" import *
Maybe it is because of the double quotes that I use - I am ending up with a beautiful error message.
But consider the following case:
from models.admin import *
If I end up doing that then I get another error! This time it is the ImportError: No module named admin"
My question is basically this - Is there any way to import a file in Python which consists of a period in the name?
All help appreciated!
Hi, it's a very simple answer actually.
You can make sure to import a module with a name which is not valid. Make sure you use imp for this purpose.
Let me give you an example:
Let us say you are assuming the file is called as models.admin.py then you can consider doing this:
import imp
with open('models.admin.py', 'rb') as fp:
models_admin = imp.load_module(
'models_admin', fp, 'models.admin.py',
('.py', 'rb', imp.PY_SOURCE)
)
Also, make sure to glance at the official documentation on the imp.find_module and imp.load_module just before you go about implementing it.
Hope this helped!
Using the following logic you can arrive ...READ MORE
To count the number of appearances:
from collections ...READ MORE
We cannot. Dictionaries aren't meant to be ...READ MORE
You can use word.find('o') as well to ...READ MORE
Good question. Django 1.0 was updated recently ...READ MORE
Hi, good question. Easy solution to be ...READ MORE
Hi, there is one scenario where the ...READ MORE
Hi, the solution to this is very ...READ MORE
Hi, the answer is a very simple ...READ MORE
I went through the Python documentation and ...READ MORE
OR | https://www.edureka.co/community/36560/help-referencing-python-package-filename-consists-period?show=36563 | CC-MAIN-2019-30 | refinedweb | 326 | 71.31 |
-
Last edited by Andrew - 28.08.2015
Opened by lalebarde - 28.08.2015
Last edited by Andrew - 28.08.2015
FS#1255 - Change a quote value modify the drawing + link quotes with entities
Change a quote value modify the drawing + link quotes with entities
In other words, makes quotes editable AND linked to entities.
- Today in the properties, the value is read only. Being able to edit the value would modify the linked entity properties to fit the new quote.
- Changing a property would change the linked quotes accordingly. Today, if I change a circle diameter which is quoted, the quote remain where it was and is no more relevant.
In addition, that would be great to be able to use variables in quotes or in properties. These variables would have a namespace associated to blocks or layers or file, and could be shared with other files.
Please use an other character and not the quote. Since unicode several characters are not keyboard accesable anymore. | https://www.qcad.org/bugtracker/index.php?do=details&task_id=1255&string=&type%5B0%5D=2&order=votes&sort=desc&order2=progress&sort2=desc&pagenum=5 | CC-MAIN-2019-51 | refinedweb | 165 | 66.54 |
On Tue, 13 Dec 2005 18:26:51 +0000Matthew Garrett <[email protected]> wrote:> On Tue, Dec 13, 2005 at 10:14:17AM -0800, Randy Dunlap wrote:> > > 7. Most important: What good does the ACPI interface do/add?> > What I mean is that acpi_get_child() in scsi_acpi_find_channel()> > always returns a handle value of 0, so it doesn't get us> > any closer to determining the ACPI address (_ADR) of the SATA> > devices. The acpi_get_devices() technique in my patch (basically> > walking the ACPI namespace, looking at all "devices") is the> > only way that I know of doing this, but I would certainly> > like to find a better way.> > When the PCI bus is registered, acpi walks it and finds the appropriate > acpi handle for each PCI device. This is shoved in the > firmware_data field of the device structure. Later on, we register the > scsi bus. As each item on the bus is added, the acpi callback gets > called. If it's not an endpoint, scsi_acpi_find_channel gets called. > We're worried about the host case. The host number will correspond to > the appropriate _ADR underneath the PCI device that the host is on, so > we simply get the handle of the PCI device and then ask for the child > with the appropriate _ADR. That gives us the handle for the device, and > returning that sticks it back in the child's firmware_data field.> > At least, that's how it works here. If acpi_get_child always returns 0 > for you, then it sounds like something's going horribly wrong. Do you > have a copy of the DSDT?Thanks for the explanation.The 136 KB DSDT is at: .---~Randy-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to [email protected] majordomo info at read the FAQ at | https://lkml.org/lkml/2005/12/13/288 | CC-MAIN-2017-43 | refinedweb | 302 | 74.08 |
Hello all,
My assignment is as follows: Write a program that prompts the user for the number of tellers at Nation’s Bank in Hyatesville that worked each of the last three years. For each worker the program should ask for the number of days out sick for each of the last three years. The output should provide the number of tellers and the total number of days missed by all the tellers over the last three years.
I've got the body right (I think), so it does ask how many tellers and covers a three year period of time, but for the life of me I cannot figure out how to get totals from each tellers days out to one big total outside the loop. I'm sure it's simple math but I would really appreciate any help with the syntax (hope that was the right word). The last total is where I am stumped. Thanks in advance.
// This program finds the number of days a teller was // out of work sick over a three year period. // Christine #include <iostream> using namespace std; int main() { int numTellers; float sickDays, totalsick, total = 0; int teller, year = 0; // these are the counters for the loops cout << "This program finds the number of days a teller \n" "was out of work sick over a three year period\n" << endl; cout << "How many tellers worked at Nation's Bank during each of the \n" "last three years?\n\n"; cin >> numTellers; for (teller = 1; teller <= numTellers; teller++) { totalsick = 0; for (year = 1; year <= 3; year++) { cout << "\nPlease enter the number of days teller " << teller << " was out " "sick in year " << year << "." << endl; cin >> sickDays; totalsick = totalsick + sickDays; } } cout << "\nThe " << numTellers << " tellers were out of work sick for a total \n" "of " << total << " days during the last three years." << endl << endl; return 0; } | https://www.daniweb.com/programming/software-development/threads/475383/calculations-in-for-loop | CC-MAIN-2018-43 | refinedweb | 310 | 71.28 |
#include <proton/import_export.h>
#include <proton/error.h>
#include <proton/engine.h>
#include <proton/sasl.h>
#include <proton/ssl.h>
Go to the source code of this file.
API for the Driver Layer.
The driver library provides a simple implementation of a driver for the proton engine. A driver is responsible for providing input, output, and tick events to the bottom half of the engine API. See pn_transport_input, pn_transport_output, and pn_transport_tick. The driver also provides an interface for the application to access the top half of the API when the state of the engine may have changed due to I/O or timing events. Additionally the driver incorporates the SASL engine as well in order to provide a complete network stack: AMQP over SASL over TCP.
pn_connector - the client API Construct a connector to the given remote address.
Activate a connector when a criteria is met
Set a criteria for a connector (i.e. it's transport is writable) that, once met, the connector shall be placed in the driver's work queue.
Return the activation status of the connector for a criteria
Return the activation status (i.e. readable, writable) for the connector. This function has the side-effect of canceling the activation of the criteria.
Please note that this function must not be used for normal AMQP connectors. It is only used for connectors created so the driver can track non-AMQP file descriptors. Such connectors are never passed into pn_connector_process.
Close the socket used by the connector.
Determine if the connector is closed.
Access the AMQP Connection associated with the connector.
Access the application context that is associated with the connector.
Destructor for the given connector.
Assumes the connector's socket has been closed prior to call.
Access the head connector for a driver.
Access the listener which opened this connector.
Access the next connector.
Service the given connector.
Handle any inbound data, outbound data, or timing events pending on the connector.
Access the Authentication and Security context of the connector.
Assign the AMQP Connection associated with the connector.
Assign a new application context to the connector.
Set the tracing level for the given connector.
Access the transport used by this connector.
Construct a driver
Call pn_driver_free() to release the driver object.
Get the next active connector in the driver.
Returns the next connector with pending inbound data, available capacity for outbound data, or pending tick.
Return the most recent error code.
Return the most recent error text for d.
Free the driver allocated via pn_driver, and all associated listeners and connectors.
Get the next listener with pending data in the driver.
Wait for an active connector or listener
Force pn_driver_wait() to return
pn_listener - the server API Construct a listener for the given address.
Accept a connection that is pending on the listener.
Close the socket used by the listener.
Access the application context that is associated with the listener.
Frees the given listener.
Assumes the listener's socket has been closed prior to call.
Access the head listener for a driver.
Access the next listener. | http://qpid.apache.org/releases/qpid-proton-0.4/protocol-engine/c/api/driver_8h.html | CC-MAIN-2014-42 | refinedweb | 509 | 53.27 |
6. Efficient IPU I/O
When developing applications for the IPU, maximising the I/O performance is important. If an application is I/O-bound, after optimisation of the host data loading, then you can explore further optimisations of the movement of data into the IPU. This chapter will cover two options that can improve I/O performance.
6.1. Prefetch elements
The option to prefetch multiple dataset elements allows TensorFlow and Poplar
to move input data logically closer to the IPU before it is needed. This can
be in the Streaming Memory (DRAM attached to the IPU-Machine, for example an IPU-M2000 or a Bow-2000). A symptom of data
not being available to the IPU when required is large
StreamCopyBegin
programs in the PopVision execution
trace.
You can enable and set prefetch using the
prefetch_depth option on the
IPUInfeedQueue constructor or the IPU Keras
API functions. Setting this option to a value greater than
1 will instruct
TensorFlow and Poplar to move up to
prefetch_depth dataset elements into
a staging area near the IPU.
6.2. I/O Tiles
The option to designate a number of IPU-tiles to be “I/O tiles” allows
TensorFlow to construct the Poplar graph so that the data transfer and the
computation can overlap in time. This is useful when the
StreamCopyMid is
taking a significant proportion of the application’s runtime and blocking
computation.
Note
This will only overlap I/O with computation for a single IPU application or a pipelined application using the grouped schedule. See Section 5.4, Pipelined training for more detail.
You can set the number of I/O tiles to use during execution when configuring
the IPU. This is set using the io_tiles.num_io_tiles
configuration option of the
IPUConfig:
from tensorflow.python import ipu ... config = ipu.config.IPUConfig() config.io_tiles.num_io_tiles = 128 config.io_tiles.place_ops_on_io_tiles = True
You should carefully tune the number of IPU-tiles designated to be I/O tiles because these tiles cannot participate in the computation. This means that a very large number of I/O tiles can cause performance regressions in the main computation. However, too few I/O tiles can cause the transferred tensors to not fit in the available tile memory. Therefore, this may require some experimentation to find the best value for a specific application. | https://docs.graphcore.ai/projects/tensorflow1-user-guide/en/latest/tensorflow/ipu_io.html | CC-MAIN-2022-33 | refinedweb | 387 | 54.93 |
08 February 2013 22:14 [Source: ICIS news]
HOUSTON (ICIS)--Nearly all US producers of polyvinyl chloride (PVC) have announced new price initiatives for March contracts, as bullish sentiment appeared to be rising, sources said on Friday.
On Thursday, Axiall revised its previously announced 3 cents/lb ($66/tonne, €50/tonne) increase for March contracts to 5 cents/lb.
That was after Shintech announced a 5 cents/lb increase for March, in addition to its previously announced 3 cents/lb increase for February, and Dow announced a 5 cents/lb increase for March. ?xml:namespace>
Meanwhile, export prices of PVC are continuing to rise on the back of increased demand and snug supply. Export PVC is assessed by ICIS at $1,010-$1,020/tonne.
Reasons cited by producers for the increases include snugness in supply caused by planned and unplanned outages, strengthening domestic demand for PVC and increased feedstock costs.
The increased demand is due largely to the
According to market sources, Axiall still has not lifted the force majeure it imposed on vinyl chloride monomer (VCM), a precursor to PVC, following a fire at its facility in
Spot and export prices for PVC continued to climb during the week on the back of increased demand and snug supply. Some producers are said to have no material availability for either the spot or export markets.
Major
( | http://www.icis.com/Articles/2013/02/08/9639588/major-us-producers-of-pvc-have-new-price-initiatives-for-march.html | CC-MAIN-2013-48 | refinedweb | 227 | 52.94 |
- Need help to create a map
- Unmanaged dll interop problem.
- convert string to double and count characters
- Urgent Oracle-DBA professionals required
- 2 Crystal Report problem
- Urgent Oracle-DBA professionals required
- Urgent Oracle-DBA professionals required
- How to Bind ComboBox in Grid to some other table?
- Extracting innertext and attribute using XmlSerializer
- Verify if a DLL is used in ASP.NET application or Windows application
- create a variable to hold all forms created in a solution
- Load existing html into table cell
- A string class that don't stretch
- .NET 2005 versus 2003 standard edition
- Copying application folders
- Web Post problems
- taskbar item
- C++ managed wrapper for static C library
- hmmmmmm
- Drag text from windows and drop it in a windows forms Application
- TimesTen with C# or .NET Framework
- End an outside process
- Create MS Projet Objects in C#
- Input Box associated with tree nodes
- Coding - Best practices?
- update dbase (dbf) tables
- How to check the version of an application?
- smtpmail
- notifyicon - blinking\highlighted\animated
- How to remove a user control dynamically
- Puzzled with Thread Safety of classes with static methods when usedin a Web Application
- office open xml
- Controls which resize themselves !
- ContextMenu causing strange Exception
- Find Sql Servers in a local net
- Find out what module is taking so long to compile
- try/catch on dequeue is way slower than my own lock
- need code to peg CPU for 10 seconds
- can the joystick send events to a C# app???
- can the joystick send events to a C# app?
- Regexp matching blocks of text
- Should I use the PictureBox Image or BackgroundImage
- files & folders cache implementation
- Vista - UAC and Click Once
- a strange exception
- Create Instance Of Class Using text name
- Graphics.DrawPolygon with Custom Dash throws Exception
- Processor ID
- Popup window
- How to get the application path :S
- How to get the application path :S
- very very simple question
- Problem moving a file
- Q: FtpWebRequest
- WCF book?
- Problema copia file
- Is there any method konw how a mail send successful when use SmtpClient?
- Ajax controls not working in my C# deeloped web app
- Automatically Add Comment Header to Source Files
- Can the status of a printer be checked programtically in c#
- Can i add com dll in GAC.
- Datagrid and relation between two table.
- Help regarding runtime host.
- how to save a web page using C# windows application
- About C# Generic
- Generic methods and inheritanc on non generic class
- IE 7
- How do NetworkCredential and WebClient work?
- application name
- Comparing different floats fails
- Problem Inheriting UserControl
- Play a Windows Sound
- List View Question
- find method in app
- key translations
- Using WMI from clustering
- SkinCrafter Light Control download from Microsoft doesn't seem to work. Anyone?
- how to get the process owner after querying WMI ?
- Problem with datagrid
- OnPaste event from the clipboard
- Managing xls
- What is wrong?
- How do you create a library of commonly used structs, enumerationsconstants and functions using C#
- naming conventions checker
- Unable to get line-breaks for a JavaScript 'alert' message using ClientScript.RegisterStartUpScript
- Object Styles -- System.Windows.Forms vs System.Web.UI.WebControls
- hmmmmmm
- Keeping controls centered
- How to add web user control to cell
- Structure to Byte Array - Which is better? Marshal Copy or FixedByte Assignment
- I am unable to understand why this use of Substring does not work
- Kernel lock
- Sql Connection
- strange Thread-pool behavior behind WebService
- Way for user to see progress on long running asp.net process
- UponExit() ??
- asynchronous socket problem when connecting to localhost
- .NET C# with Windows Vista Home Basic or Business?
- Application run timing in C#
- Haven't been able to convert to the new strip menus
- .Net Framework
- Csharp simple script interpreter
- How to display the formulas in spreedsheet?
- what is the difference wetween Int32.parse and Convert.ToInt32
- help explain this winform behaviour
- Need help with regular expression
- Poker odds calculator
- ShellExecuteEx
- Excel get_Range
- C# Stack item reversal
- Need help understanding how to call unmanaged dll
- Split Windows
- ResourceManager efficiency
- detect endianness
- unbelievable..?
- How to reverse boolean value
- TypeConverter::ConvertFrom ignores implicit cast
- Trying to get a scripting environment for a WebBrowserClass object
- Debug Monitor Selection
- Casting an enum, skips one for no reason?
- newbe question
- Tool box icons mostly missing....
- Save bmp/jpg/png...to icon (16x16) - Problem..
- DataGridView - Row Selected
- Remote Debugging
- Need to calculate milleseconds until 1:00am...
- PropertyGrid dynamic Dropdown List
- Generics and consatraints.
- Advice on Images and CF2 Please???
- SQL Parameter
- web service timeout!
- the symbol
- How to handle a property?
- Setting LinkLabel cursor?
- How to click a button multipal times
- data from remote computer
- Best methodology for a common db/front end issue
- A quick is this safe singleton question
- Make my own class? Or just use an array?
- Programmatically get printPreviewDialog on a windows form
- error in update command using dataadapter
- good decompiler app
- send message to win32 app to press button control - remote control button
- WebBrowser mouse events How do I capture?
- how do I run an exe from another exe file
- can the joystick send events to a C# app?
- How to develop cad like application
- How to develop cad like application
- Copy DataSet problem
- Implement interface for that class, not dervived classes
- Add items to comboBox how dropdown list resized
- Confusion over Static class and Static method!
- filestream access denied
- ActiveX in DLL
- upgrade to .NET 2.0 but some files are missing
- GUI Thread ComInterop
- alternate controls for ToolStrip and MenuStrip?
- Issue with CollectionEditor handling multiple sub-types
- Not retrieving values
- Install base of .NET 1.1
- Need further comments\tips\hints or feedback for my site
- COM Question (Excel)
- Problem with C# not calling MC++ destrcutor
- Which MySQL Provider.
- Sending Ctrl+C to Apache
- GZipStream...
- Double checked locking
- Save Dailog
- DOS Short Names
- Queueing in Client Server Application
- Service sent a stop cmd????
- Cross thread question .....
- ASP.NET Deleting rows from an unbound gridview
- Case Insensitive String Comparison?
- produce csv containing all sheets.
- Best way to Read Binary Files
- Best way to Read Binary Files
- Exception Handling and Class Inheritence
- How to loop through Hashtable keys without using foreach
- Properties vs Get Set Accessor methods
- Mouse Position While Dragging and Dropping
- Data Relation? Newbe question
- Encoding to ISO-8859-1 problems
- UI freeze and thread problems
- Tracing using a global trace object...
- Program Version Number
- thread safety and syncroot
- How to make web browser editable
- Dynamically accessing the most current version of an assembly
- & in web config
- Exe files on several computers
- Switching mouse event handlers using a function
- Joystick with events: is there any way?
- Problem creating folder in C# Asp.Net
- Reflection & Array Properties
- Installation and Registry association
- How can i get "paste event" from the clipboard?
- All Controls On Form Without Using Recursion
- ole
- COM events in CSharp
- Stupid question...
- Default encoding as UTF-8 in VS.NET 2005
- How to send/recieve Emotion Icons in IM application
- DetailsView - the Very First Record
- Data switch with Dispose()
- Detect Word is running
- Dynamic settings entries with Application Settings.
- Problems logging to AOL and Live Email by using HttpWebRequest
- inherited namespace
- Dock ordering messed up when using my custom controls
- vb.net vs c#
- Is there method to sort my dataset table with one or mulitple colu
- USB Barcode Scanner
- How to get username, password from .NET Windows service installation to actual service code ?
- Vista, C#, and Regsvr32
- align a label in center hor and vertical
- Connect to Excel then format within a cell
- What is ClickOne?
- How to delete all function calls
- Asynchronous method calls on COM components?
- release and debug mix during testing
- Controls add/remove and Dispose
- Debugging a DLL
- DataGridView AND Combobox
- Need to Create a Specific format with XmlTextWriter
- web page menu design
- DataGridCheckBoxColumn
- Threadpool LateBinding
- Intermittent Crash on Startup of app with custom ActiveX control
- How does the AddIn Project register itself?
- Type casting from one namespace to the other.
- Why I am I getting this exception
- Problem with DataGridView and BindingSource
- Router state
- ContextMenuStrip and PreviewKeyDown
- Excel grid in Visual Studio 2005 app
- Embed in word
- .NET property names and translation
- IPAddress and XmlSerializer
- Stop message about unknown publisher.
- merging assembly dll's into one dll
- Dataset Now showing updated Rows.
- Handle the joystick with events (DirectInput and C#)
- VS2K5 doesn't compile/execute latest code
- Get Culture Info from Language Name
- IListSource does not contain any data
- Can't delete Registry.LocalMachine subkey
- THEAD in htmltable
- Unique Identifier
- Weired: Event only working when performing a MessageBox (focus-problem?)
- ValidateChildren on a tab control
- Adding reference of Excel COM won't work
- Process Fails while calling Start
- Clipboard events in windows service
- try catch with return value
- Instance with Inheritance
- Can't delete Registry.LocalMachine subkey
- Can't delete Registry.LocalMachine subkey
- Can't delete Registry.LocalMachine subkey
- filesystemwatcher and determining when it is safe to work on the directory
- C# Label encapsulate to Image
- Coloring item X in a combobox dropdown?
- web service timeout issue. please help.
- Pass DateTime parameter to LocalReport?
- ConfigurationErrorsExecption was unhandled.
- events that fire events that fire events....a bad thing?
- Creating a process owned by system not user
- Need to create a .NET object that will be serialized into a specific XML format
- After user enters a row of data into a DataGrid (.net 1.1), how to auto-update the actual database?
- Application Version
- DataGridView and ComboBoxColumn
- HELP! Select works but cannot write to the DB - SQL Express via C#
- HELP! Select works but cannot write to the DB - SQL Express via C#
- HELP! Select works but cannot write to the DB - SQL Express via C#
- Does typeof or is work when dealing with an interface?
- Inserting class collection data into Access database
- Efficiency of foreach vs for loop
- Self update
- Unusual C# errors (Maybe memory corruption)
- datagridviewcomboboxcell value is not valid
- Saving/restoring strongly-typed DataTable to/from XML
- ClickOnce: How to change the codebase location in code
- XmlNode.SelectSingleNode() Question
- problem creating a sql table
- VB6 to VB .Net
- Programatically uninstall/install a service.
- Update non-keyed table
- C# Threading Issue
- Reflection
- parametize the "is" keyword
- Q: ServiceController and ExecuteCommand
- Regex repeating capture
- Passing a byte[] by ref, and here I thought I knew what was going on.
- Closing Processes
- Q: "Simple" tick problem.
- shared assemby
- Can't delete Registry.LocalMachine subkey
- Event handling between process.
- Obtaining dimensions and coordinates of display window of WebBrowser
- FontStyle class
- Hardware Simulation
- Want to Group By Union Two Query
- site searching
- refer the version
- need a good idea :)
- How can I build an app that can have Add-on built for it??
- GAC vs *.exe.config (and %path%)
- C# ScrollBar and Label
- check record and then run second query to display in data grid
- how to use active directory in .net
- Reasoning behind the EventHandler(object, EventArgs) signature
- Advice on what language to learn VB or C# (and 1.1 vs 3.0)
- How to audit application actions.
- WebBrowser control brings up external IE Window and allows pop-ups
- Tracking login...
- Where is the Team Explorer downloade?
- Can't build my app, VS says files are in use by another process
- regular expression
- Can a Web Servive send it's status to a client?
- binding navigator
- Customer Membership Provider Issues
- Sorting Directories
- Dynamic string format specifier
- C# Developers needed in Houston Texas
- Searching a Specific OU...
- Smart Slicing Routine!!
- Writing into a text file
- INFOPATH 2007 version for WTS/CITRIX
- Breaking the line in tree node
- Best way to fire event
- WinAPI constant search for C#
- If not CAB, then what?
- Program execution question - need guidance
- Slicing Routine!
- Multiple XML Namespace prefixes (in a webservice)
- Events and threads ... whose thread am I on anyway?
- Any non commercial statisticss library?
- General Opinion on a how to?
- formview and dropdownlist
- Passivating a workflow
- STRANGE PROBLEM
- Property sheet and property pages in winforms
- compile csharp file
- Enum type from one of its members
- Get handle from System.IO.SerialPort
- Dynamic cast with generics
- Invalid parameter used
- Label and VScrollBar
- Address String Question
- C# certification exam?
- List of KNOWN VS2005/Vista issues.......
- Red progressbar on Vista.
- Using SAPI from C#?
- string manipulations
- TextBox Question
- bit operations
- No Vista support?
- VS2005 NOT Compatiblke with Vista? Are you serious?!
- Custom login control question
- Looking for a grphical audio analyzer component
- VB.NET, C# Job opening in chennai 2+Years to 4Years Team Lead
- smo create database object
- More regular expression woes
- threads
- ExtractIconEx(iconFullPath, -1, IntPtr.Zero, IntPtr.Zero, 0) does what???
- Is it possible to close a windows folder from C#?
- Class instance variable question
- default-values to class members
- sort a generic linked list?
- embedding a cursor in an application
- Web root directory
- Regular Expression Question
- FileStream
- String Relace
- How do I get a HINSTANCE into my C++ class library from my C# code?
- C# Sending Mail and Moving betwen pages to go to a checkout page
- VISUAL C# and SQL
- loquendo TTS
- modular programming
- Changing attributes at runtime
- CodeDOM, inserting full source code.
- Constructing and sending a SYN header
- predefined preprocessor constants
- Problemas con ClickOnce
- Terminology request!
- Passing enums to a method
- C# and Ogg Vorbis encoder
- Finding property values
- C#/Excel automation add-in not working on MediaCenter?
- UK Regulatory Capture
- Clearing a WebBrowser control
- I am puzzled by static class use
- Assembly code in-line with C#
- Intellisense does not move with the main form
- SqlDataAdapter.Fill and DataRow.RowSate
- Error executing VSSDatabase.Open(..)
- Persistence framework, support for composite key
- IsDecimal or IsNumber
- where can I get some cool code type questions for c#, asp.net and SQL
- Properties
- Properties
- Copy and Pasting RTF to non RTF supported program
- How can I change the ClickOnce update location from the client?
- How can I get column numbers from a Winforms dataGrid
- Converting byte[] to string - removing NULLs??
- C# inheritance broken?
- C# inheritance broken?
- Detecting a fullscreen application
- usercontrol and Application.AddMessageFilter(this)
- How do I know when my work threads have completed their tasks?
- Use of unassigned local variable?
- Adding color to individual rows in a "PropertyGrid"
- display image in crystal.net
- Want to call a custom handler that redirect and receive the http return code (302, 303 or 307)
- Can I use typed dataset with Oracle db?
- FileWatcher
- Data Save
- Tertiary Operator Confusion ( a = b ? c : d)
- HOW START to create a P2P streaming video..
- creating a custom cursor
- Custom tree node - how to
- Delete ManagementObject but exception occur
- Changing a variable before the application exits
- File association
- Non-proportional (non Rectangular) resizing
- Error handling in .net Class Library / Visual Basic
- Error handling in .net Class Library / Visual Basic
- Error handling in .net Class Library / Visual Basic
- Error handling in .net Class Library / Visual Basic
- Error handling in .net Class Library / Visual Basic
- Understanding code-behind and functions.
- Can someone confirm this :o)
- SSH library
- can application have Multiple Main() ??
- Convert MyTextField.Text to "all caps"
- Local variables, method arguments dump.
- Number of members in an Enum
- creating xml document using schema
- Xml root element attributes
- C# can't create Window Forms?
- how do you embed a windows media player control in a user control and have it work in a web page?
- C# SMTP Mail question
- Is there any function to solve the string to values?
- What's the most efficent way to create a dataset table from a join
- What's the most efficent way to create a dataset table from 2 join
- C# application interacting with Dictionary.
- Access public methods in multple copies of the same form
- CAN i use the C# Expression version to connect the SQL 2005
- How to retrieve DLL function detail
- Typed dataset with oracle db ?
- [C#, MS SQL Server] String or binary data would be truncated. But not field length problem.
- Nullable Types
- Exception propogation question
- How to keep a multiline + vertical scrollbar textbox on the LAST line?
- threading using filewatcher object
- Textbox values changed aren't appearing after update
- what takes more system resources?
- Implementing File->Edit Menu
- C# 2.0, Generic Collection?
- Input cursor
- Datagrid Custom Event Question
- Automating Excel from C#, Adding Picture Charts
- FileStream
- How do I make a string longer??
- asynchronous socket communication
- going from one form to another
- binary file question
- How to get all Listeners created by TraceSource
- Project-->Project References Large Project
- composite ui application block
- cSharp ( c# ) SQL and pocket pc
- need help generating a dynamic list control <ul />...
- Casting of generics?
- unable to open project file by the web server
- Deployment & compatibility
- return object of an unknown type
- Stopping screen saver
- creating a ram drive in csharp
- load assembly from different folder
- DataView with more than one table
- consuming managed C# DLL from unmanaged VB6
- DataTable.Select Bug????
- c# website
- Creating DLL for PowerBuilder as external functions
- Composite UI application block - Thread safe?
- How can i send an Email on Page Load event?
- Diclaring class level variable
- How do I remove source control info from project/solution?
- Reading custom attributes
- VS 2003 SP1 debugging
- smallest type
- Setting the version of a PDF file using Crystal Reports and/or C#.
- Reading embeded word object within excel - using c#
- The most important question ever asked (for a million years)
- Differences between OnLoad and Page_Load
- Code to quit an application
- ASP.NET 2.0 CSS Friendly Control Adapters 1.0 - Tutorial MenuExample.css PrettyMenu. How to change a style?
- CheckedListBox Bold Item
- XP look and feel in C# app
- Closures
- GC time
- small treeview question
- Button Images
- Excel always running
- Auto Complete Folder Combobox
- How do convince a DataGridView it's been edited?
- FlowLayoutPanel, why can't I remove the space between my controls?
- ToolStrip Control
- Viewing Custom Events in IDE
- Problem ... .Sockets and Threads (IP Scanning)
- Exception in Constructor
- how do you change the size of the clipping region of a Graphics object
- Combobox begginger question
- System.Web.HttpException / 404 Not Found
- Design Question: onChange Event populating a second list box
- Get Client IP address
- Optimization of framework SDK vs. VS 2005
- How to lock other threads
- FTP SSL Certificate - ServicePoint
- Trapping Http 500 error
- Call C DLL in C# with in/out pointers
- Windows Service Project
- how do you do freehand drawing on a panel
- The blog on Pc trouble shooting skills,Networking,Linux
- Open outlook message window
- Static Class, Updating DataTable and Locking?
- Style Guide, Missing UI Elements
- Design a class using Inheritance
- Is it possible to show fixed digit numbers, 0 padded values in NumericUpDown control ?
- event in static class/method
- c#
- Export res files
- DST Links
- Memory GC - loop
- Simple form calculation
- Weird problem with treeview tooltips - Expert input required :0) please
- Connection string
- Merging of priority queue
- Instant messaging type Function...
- How to delegate IIS's FTP File Upload and Upload Failure Events from C#?
- Get No "Mail From" in the TcpClient
- Dynamic Menustrip
- photo photo photo
- What is up with .NET memory usage?
- How to sort a Gridview in Csharp?
- Adding reference of my project to testing application
- UNREFERENCED_PARAMETER for C#?
- Send Emails through Exchange Server
- Set Form's ClientSize.
- Most efficient way to combine arrays? | https://bytes.com/sitemap/f-326-p-46.html | CC-MAIN-2020-16 | refinedweb | 3,161 | 55.54 |
How to use Auto Complete Box in Windows Phone
This article shows how to use AutoCompleteBox, a Windows Phone control that provides a text box for user input and a drop-down that contains possible matches based on the input in the text box.
Windows Phone 8
Windows Phone 7.5
Pre-requisites
The AutoCompleteBox is defined in the Silverlight Toolkit, whose most recent version you can find here. If the toolkit is not installed already, please follow the installation instructions below.
Installing the Windows Phone Toolkit
For Windows Phone 8, you should try to install wptoolkit from NuGet.
- Installation of the most recent Windows Phone Toolkit (formerly Silverlight toolkit) needs an installation of NuGet.
- After NuGet is installed, the Toolkit has to be installed from the NuGet Package Manager Console in the Tools menu / Library Packge Manger submenu in Visual Studio.
- Type "Install-Package SilverlightToolkitWP" there.
Tip: The toolkit should be installed into your current solution. On my machine with a pre-installed older version (Oct 2011) of the toolkit I had problems. Removing the reference to the old assembly and finding the new one in the packages folder of the solution solved the problems on one machine but not on another...
Starting a New Project
- Create a new project in Visual Studio 2010 from File>>New Project>>Windows Phone Application - Visual C#. Give a desired name of the project.
Using IEnumerable
- We now need to make a class derived from IEnumerable interface. For this, right click the project in Project Explorer window: >>Add>>New Item>>Class (Here, we are using 'SampleWords' as our class name).
- If we derive any class from IEnumerable interface, then it's compulsory to define the function GetEnumerator(). So, our class should look like below:
namespace SampleAutoCompleteBox
{
public class SampleWords : IEnumerable
{
public IEnumerable AutoCompletions = new List<string>()
{
"Lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "Nullam", "felis", "dui", "gravida", "at",
"condimentum", "eget", "mattis", "non", "est", "Duis", "porta", "ornare", "tellus", "at", "convallis", "nibh", "aliquam",
"faucibus", "Vivamus", "molestie", "fringilla", "ullamcorper", "Aenean", "non", "diam", "eu", "sapien", "pretium", "iaculis",
"Quisque", "at", "ante", "libero", "eu", "tincidunt", "urna", "Cras", "libero", "ligula", "hendrerit", "at", "posuere", "at",
"tempor", "at", "nulla", "Aliquam", "feugiat", "sagittis", "dolor", "convallis", "porttitor", "neque", "commodo", "ut", "Praesent",
"egestas", "tincidunt", "lectus", "et", "pharetra", "enim", "semper", "et", "Fusce", "placerat", "orci", "vel", "iaculis",
"dictum", "nulla", "sem", "convallis", "nunc", "in", "viverra", "leo", "mauris", "eu", "odio", "Nullam", "et", "ultricies",
"sapien", "Proin", "quis", "mi", "a", "sapien", "semper", "lobortis", "ut", "eget", "est", "Suspendisse", "scelerisque", "porta",
"mattis", "In", "eleifend", "tellus", "vel", "nulla", "aliquam", "ornare", "Praesent", "tincidunt", "dui", "ut", "libero",
"iaculis", "consequat", "Nunc", "interdum", "eleifend", "rhoncus", "Curabitur", "sollicitudin", "nulla", "sagittis", "quam",
"vehicula", "cursus", "Fusce", "laoreet", "arcu", "vitae", "fringilla", "scelerisque", "nisi", "purus", "laoreet", "ipsum", "id",
"suscipit", "erat", "tellus", "eu", "sapien", "Proin", "pharetra", "tortor", "nisl", "Etiam", "et", "risus", "eget", "lectus",
"vulputate", "dignissim", "ac","sed", "erat", "Nulla", "vel", "condimentum", "nunc", "Suspendisse", "aliquam", "euismod", "dictum",
"Ut", "arcu", "enim", "consectetur", "at", "rhoncus", "at", "porta", "ut", "lacus", "Donec", "nisi", "quam", "faucibus", "tempor",
"tincidunt", "eu", "porttitor", "id", "ipsum", "Proin", "nec", "neque", "nulla", "Suspendisse", "sapien", "metus", "aliquam", "nec",
"dapibus", "consequat", "rutrum", "id", "leo", "Donec", "ac", "fermentum", "tortor", "Pellentesque", "nisl", "orci", "tincidunt",
"at", "iaculis", "vitae", "consequat", "scelerisque", "ante", "Suspendisse", "potenti", "Maecenas", "auctor", "justo", "a", "nibh",
"sagittis", "facilisis", "Phasellus", "ultrices", "lectus", "a", "nisl", "pretium", "accumsan"
};
public IEnumerator GetEnumerator()
{
return AutoCompletions.GetEnumerator();
}
}
}
- Remember, not to forget adding the following 2 using directives
using System.Collections; // for 'IEnumerable'
using System.Collections.Generic; // for 'List'
- Thus, we have declared a list of strings as our sample strings. Now to work on the UI.
Making UI and attaching Auto Complete Box with SampleWords class
- We have to include the namespace inside which we have created the Strings class (SampleWords class according to this example) in the .xaml file in which we need to put AutoComplete box.
- We will add below line of code in the MainPage.xaml (e.g)
xmlns:local="clr-namespace:SampleAutoCompleteBox"
The xmlns:local always point to the top level namespace. So, we have defined SampleWords.cs inside the SampleAutoCompleteBox namespace (same as your project name).
- Create/declare a static resource in the MainPage.xaml file like shown below
<phone:PhoneApplicationPage.Resources>
<local:SampleWords
x:
</phone:PhoneApplicationPage.Resources>
Here, local: will have the class file name in which we have declared the list of stings. We have also defined a key as AutoCompletions so that it can be directly used by it in future.
- Now we will drag and drop the AutoCompleteBox tool from the Toolkit on to the MainPage.xaml design view. By this, the corresponding code will be inserted into the code view.
- We will assign the value StaticResource AutoCompletions to the property ItemsSource as shown below:
<Grid x:
<toolkit:AutoCompleteBox
</Grid>
- Now build the project and run it to see AutoCompleteBox tool running.
<Grid x:
<toolkit:AutoCompleteBox
</Grid>
<toolkit:AutoCompleteBox>
<toolkit:AutoCompleteBox.TextBoxStyle>
<Style TargetType="TextBox">
<Setter Property="MaxLength" Value="10"/>
</Style>
</toolkit:AutoCompleteBox.TextBoxStyle>
</toolkit:AutoCompleteBox>
</Grid>
Chintandave er - sceenshot.
Hi Pooja. A sample screenshot of the UI generated by this code would be give better idea to understand beginner level developers before implementing the whole code.
Nice article though.Chintan.
Chintandave er 07:43, 25 January 2012 (EET)
Croozeus - Sub-edited
@Pooja, the article looks good. I've subedited the article and here are some comments,
Couple of tips related to construction of sentences while writing tutorials,
Looking forward to see more new articles on WP7!//P
croozeus 09:40, 25 January 2012 (EET)
Croozeus - Source code
The zip archive contains some temp files generated by the build system, which are not required and you may want to remove them. For eg. the files in the Debug folder, etc.//P
croozeus 10:09, 25 January 2012 (EET)
Pooja 1650 -Thank you Pankaj & Chintan for your valuable feedback. I will always try to implement your suggestions.
pooja_1650 11:08, 25 January 2012 (EET)
Hamishwillee - Nice job.
From the category page "While we welcome articles about Windows Phone, there are many excellent resources on MSDN and elsewhere. What we need most are articles showing how to port between Windows Phone and other Nokia platforms."
So if you're writing an article on Windows phone please consider:
The above is a general point that I'm hoping you will consider in future - I haven't evaluated whether this could be a comparative article or if there is better documentation elsewhere. I can say that this looks to be well written and does "all the right things" - like having images, downloadable examples, and references to the official API reference. Good job - and thanks to moderators and Champions for giving pooja such good advice.
- whether you can write a comparative article showing how to do the same thing on Qt
- don't duplicate content that is on MSDN. The exception is you're doing it "better" than articles you find elsewhere or covering aspects that they missed. Providing a downloadable example when the original doesn't also adds value.
hamishwillee 03:02, 26 January 2012 (EET)
Influencer - Changed installation instructions
Hi Hamish,
I changed the installation instructions due to the change in distribution model of the toolkit.Thomas
influencer 01:02, 30 October 2012 (EET)
Hamishwillee - @Influencer - thanks VERY much
Hi Thomas
That is great. One of my biggest problems is keeping content up to date. I added your details to "updated" section in the ArticleMetaData which shows this was accurate on that date.
RegardsH
hamishwillee 06:57, 30 October 2012 (EET)
Pooja 1650 - @Hamish - Can you rename article?
Hi Hamish,
Tested the article against WP8, working fine.
So, can you please help in renaming it by How to use Auto Complete Box in Windows Phone?
Thanks,Pooja
pooja_1650 14:44, 27 May 2013 (EEST)
Hamishwillee - FantasticThank you Pooja, great work. I've renamed it (using the "Move" instruction in menu near the eye at the top right of the wiki page). Also did minor editorial change because Sliverlight toolkit has been moved.
hamishwillee 03:07, 28 May 2013 (EEST)
Pooja 1650 - Thanks for guiding
Hi Hamish,
Thanks for the changes and guiding me how to edit any article name.
Regards,Pooja
pooja_1650 07:51, 28 May 2013 (EEST)
Hamishwillee - You're most welcome
I guess I should provide some general advice on updating to next version. If I were to it would be something like:
In addition, doing an update is an opportunity to improve the article more generally, so quick check against Help:Wiki Article Review Checklist.Just FYI!
hamishwillee 09:02, 28 May 2013 (EEST) | http://developer.nokia.com/community/wiki/How_to_use_Auto_Complete_Box_in_Windows_Phone_7 | CC-MAIN-2014-10 | refinedweb | 1,409 | 52.09 |
2008-11-19 09:24:24 8 Comments
In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?
Related Questions
Sponsored Content
19 Answered Questions
[SOLVED] How do I sort a list of dictionaries by a value of the dictionary?
- 2008-09-16 14:27:47
- masi
- 606277 View
- 1538 Score
- 19 Answer
- Tags: python list sorting dictionary data-structures
26 Answered Questions
[SOLVED] How do I enumerate an enum in C#?
- 2008-09-19 20:34:50
- Ian Boyd
- 663582 View
- 3379 Score
- 26 Answer
- Tags: c# .net enums enumeration
24 Answered Questions
[SOLVED] Cast int to enum in C#
15 Answered Questions
[SOLVED] Returning IEnumerable<T> vs. IQueryable<T>
- 2010-05-20 18:13:59
- stackoverflowuser
- 198396 View
- 974 Score
- 15 Answer
- Tags: c# linq linq-to-sql ienumerable iqueryable
38 Answered Questions
[SOLVED] How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
- 2009-01-23 13:39:54
- Agnel Kurian
- 1131080 View
- 2032 Score
- 38 Answer
- Tags: c# .net string character-encoding
57 Answered Questions
26 Answered Questions
[SOLVED] What is the best way to iterate over a dictionary?
- 2008-09-26 18:20:06
- Jake Stewart
- 1308346 View
- 2193 Score
- 26 Answer
- Tags: c# dictionary loops
26 Answered Questions
[SOLVED] Why not inherit from List<T>?
- 2014-02-11 03:01:36
- Superbest
- 144591
@kristianp 2019-03-06 01:58:11
I don't think this is necessarily true, most languages have one or the other, depending on the terminology they prefer.
In C#, however, the clear reason (for me) is that C# HashTables and other members of the System.Collections namespace are largely obsolete. They were present in c# V1.1. They have been replaced from C# 2.0 by the Generic classes in the System.Collections.Generic namespace.
@rix0rrr 2008-11-19 13:03:41
People are saying that a Dictionary is the same as a hash table.
This is not necessarily true. A hash table is one way to implement a dictionary. A typical one at that, and it may be the default one in .NET in the
Dictionaryclass, but it's not by definition the only one.
You could equally well implement a dictionary using a linked list or a search tree, it just wouldn't be as efficient (for some metric of efficient).
@snemarch 2010-09-23 13:52:44
MS docs say: "Retrieving a value by using its key is very fast, close to O(1), because the Dictionary <(Of <(TKey, TValue >)>) class is implemented as a hash table." - so you should be guaranteed a hashtable when dealing with
Dictionary<K,V>.
IDictionary<K,V>could be anything, though :)
@Joseph Hamilton 2011-08-09 17:22:25
@rix0rrr - I think you've got that backwards, a Dictionary uses a HashTable not a HashTable uses a Dictionary.
@Robert Hensing 2013-03-08 09:38:58
@JosephHamilton - rix0rrr got it right: "A hash table is an implementation of a dictionary." He means the concept "dictionary", not the class (note the lower case). Conceptually, a hash table implements a dictionary interface. In .NET, Dictionary uses a hash table to implement IDictionary. It's messy ;)
@Joseph Hamilton 2014-10-14 19:56:03
I was talking about in .NET, since that's what he referenced in his response.
@ToolmakerSteve 2015-03-23 04:41:18
@JosephHamilton: implements (or implementation of) does not even remotely mean the same thing as uses. Quite the opposite. Perhaps it would have been clearer if he said it slightly differently (but with the same meaning): "a hash table is one way to implement a dictionary". That is, if you want the functionality of a dictionary, one way to do that (to implement the dictionary), is to use a hashtable.
@Jim Balter 2018-11-03 17:27:09
@JosephHamilton "I was talking about in .NET, since that's what he referenced in his response." -- you're wrong in any case; the .NET Dictionary class does not use or in any other way reference the .NET Hashtable class (and there is no .NET HashTable class). The answer by rix0rrr is completely right and not backwards in any way.
@Joseph Hamilton 2018-11-05 04:26:17
@JimBalter .Net HashTable -> docs.microsoft.com/en-us/dotnet/api/…
@Joseph Hamilton 2018-11-05 04:26:42
@JimBalter ." docs.microsoft.com/en-us/dotnet/api/…
@Jim Balter 2018-11-05 13:17:04
@JosephHamilton And how is any of that relevant? First, "Hashtable" != "HashTable". Second, "a hash table" != "the .NET Hashtable class". All of this was discussed repeatedly here ... please read more carefully. I won't respond further to your inaccuracies.
@Joseph Hamilton 2018-11-06 15:50:57
@JimBalter lol XD
@gius 2008-11-19 09:27:55
Because
Dictionaryis a generic class (
Dictionary<TKey, TValue>), so that accessing its content is type-safe (i.e. you do not need to cast from
Object, as you do with a
Hashtable).
Compare
to
However,
Dictionaryis implemented as hash table internally, so technically it works the same way.
@Michael Madsen 2008-11-19 09:28:55
For what it's worth, a Dictionary is (conceptually) a hash table.
If you meant "why do we use the
Dictionary<TKey, TValue>class instead of the
Hashtableclass?", then it's an easy answer:
Dictionary<TKey, TValue>is a generic type,
Hashtableis not. That means you get type safety with
Dictionary<TKey, TValue>, because you can't insert any random object into it, and you don't have to cast the values you take out.
Interestingly, the
Dictionary<TKey, TValue>implementation in the .NET Framework is based on the
Hashtable, as you can tell from this comment in its source code:
Source
@Chris S 2009-01-26 12:45:40
And also generic collections are a lot faster as there's no boxing/unboxing
@Chris S 2009-01-26 12:46:52
Not sure about a Hashtable with the above statement, but for ArrayList vs List<t> it's true
@Guvante 2009-04-17 05:29:54
Hashtable uses Object to hold things internally (Only non-generic way to do it) so it would also have to box/unbox.
@Brian J 2013-06-20 17:31:47
If Dictionary is generic, wouldn't it be more accurate to say a hash table is a dictionary? The whole "squares are rectangles, but not all rectangles are squares" thing?
@Michael Madsen 2013-06-20 17:57:22
@BrianJ: A "hash table" (two words) is the computer science term for this kind of structure; Dictionary is a specific implementation. A HashTable corresponds roughly to a Dictionary<object,object> (though with slightly different interfaces), but both are implementations of the hash table concept. And of course, just to confuse matters further, some languages call their hash tables "dictionaries" (e.g. Python) - but the proper CS term is still hash table.
@Brian J 2013-06-20 18:04:45
@MichaelMadsen So to make sure I understand you correctly, a
HashTabledata structure is a Dictionary, which is a hash table (concept), right?
@Michael Madsen 2013-06-20 21:00:16
@BrianJ: Both
HashTable(class) and
Dictionary(class) are hash tables (concept), but a
HashTableis not a
Dictionary, nor is a
Dictionarya
HashTable. They are used in very similar fashions, and
Dictionary<Object,Object>can act in the same untyped manner that a
HashTabledoes, but they do not directly share any code (though parts are likely to be implemented in a very similar fashion).
@Brian J 2013-06-21 14:00:38
@MichaelMadsen Ok. I understand now. Thank you for the clarification.
@Jim Balter 2013-09-02 03:01:05
@BrianJ "If Dictionary is generic, wouldn't it be more accurate to say a hash table is a dictionary?" -- No, because "generic" has a specific meaning in programming languages that has little to do with the English language term. A "generic" class or method is a class or method that has one or more type parameters.
@Matthijs Wessels 2014-02-06 11:52:19
@MichealMadsen, I think the confusion comes from the fact that outside of C# the term Dictionary is also used as an abstract data type for which the
Hash Tableis a solution with specific running times. Also, generic also has a meaning outside of C#, so if you don't know C#, "generic dictionary" could be interpreted as the abstract data structure.
@Mayur Dhingra 2014-02-27 11:17:31
Only public static members are thread safe in a Dictionary whereas all the members are thread safe in a Hashtable.
@sansy 2018-06-06 13:14:25
Dictionary supports more linq statements than Hashtable
@Tom 2018-06-16 00:01:20
@MichaelMadsen: Your comment about Brian J's comment is correct if he were referring to the (uppercase) "Generic" concept of C.S. where a Class or Method can operate on a Type(s) that's not defined until specified by the Caller (which, btw, I believe is also what he actually intended). ….
@Tom 2018-06-16 00:01:31
@MichaelMadsen: …However, it's not accurate if he were referring to (lowercase) "generic" (as in a data structure or algorithm being more flexible / Lower-Level than another one). In that sense, the .NET
HashTableis more (lowercase) "generic" than the .NET
Dictionary, and therefore the former (both in my sentence and in order of development) could probably be re-implemented as a Wrapper of the latter (which, btw, would also be a pretty common Refactoring practice in this scenario) if code size / perf issues were not sig issues which they usu. aren't (outside of Framework-level code).
@Jim Balter 2018-11-03 17:07:06
The comments by Tom above are incorrect and, where they aren't utterly confused, were already addressed by previous comments.
@Siva Sankar Gorantla 2016-07-13 10:45:09
HashTable:
Key/value will be converted into an object (boxing) type while storing into the heap.
Key/value needs to be converted into the desired type while reading from the heap.
These operations are very costly. We need to avoid boxing/unboxing as much as possible.
Dictionary : Generic variant of HashTable.
No boxing/unboxing. No conversions required.
@NullReference 2015-11-12 10:17:45
Another important difference is that Hashtable is thread safe. Hashtable has built-in multiple reader/single writer (MR/SW) thread safety which means Hashtable allows ONE writer together with multiple readers without locking.
In the case of Dictionary there is no thread safety; if you need thread safety you must implement your own synchronization.
To elaborate further:
If you need type safety as well thread safety, use concurrent collections classes in the .NET Framework. Further reading here.
An additional difference is that when we add the multiple entries in Dictionary, the order in which the entries are added is maintained. When we retrieve the items from Dictionary we will get the records in the same order we have inserted them. Whereas Hashtable doesn't preserve the insertion order.
@DiskJunky 2017-09-14 21:56:17
"Some thread safety" is not the same as "Thread safety"
@Oliver 2013-01-15 10:29:53
Since .NET Framework 3.5 there is also a
HashSet<T>which provides all the pros of the
Dictionary<TKey, TValue>if you need only the keys and no values.
So if you use a
Dictionary<MyType, object>and always set the value to
nullto simulate the type safe hash table you should maybe consider switching to the
HashSet<T>.
@Sujit 2012-09-17 11:10:14
Collections&
Genericsare useful for handling group of objects. In .NET, all the collections objects comes under the interface
IEnumerable, which in turn has
ArrayList(Index-Value))&
HashTable(Key-Value). After .NET framework 2.0,
ArrayList&
HashTablewere replaced with
List&
Dictionary. Now, the
Arraylist&
HashTableare no more used in nowadays projects.
Coming to the difference between
HashTable&
Dictionary,
Dictionaryis generic where as
Hastableis not Generic. We can add any type of object to
HashTable, but while retrieving we need to cast it to the required type. So, it is not type safe. But to
dictionary, while declaring itself we can specify the type of key and value, so there is no need to cast while retrieving.
Let's look at an example:
HashTable
Dictionary,
@Ron 2016-07-13 13:43:11
instead of explicitly assigning the datatype for KeyValuePair, we could use var. So, this would reduce typing - foreach (var kv in dt)...just a suggestion.
@Kishore Kumar 2012-05-22 08:07:00
Dictionary<>is a generic type and so it's type safe.
You can insert any value type in HashTable and this may sometimes throw an exception. But
Dictionary<int>will only accept integer values and similarly
Dictionary<string>will only accept strings.
So, it is better to use
Dictionary<>instead of
HashTable.
@Yuriy Zaletskyy 2010-03-09 14:28:06
According to what I see by using .NET Reflector:
So we can be sure that DictionaryBase uses a HashTable internally.
@snemarch 2010-09-23 13:48:10
System.Collections.Generic.Dictionary<TKey,TValue> doesn't derive from DictionaryBase.
@Jim Balter 2018-11-03 17:11:02
"So we can be sure that DictionaryBase uses a HashTable internally." -- That's nice, but it has nothing to do with the question.
@Brant 2010-01-24 21:20:04
Notice that MSDN says: "Dictionary<(Of <(TKey, TValue>)>) class is implemented as a hash table", not "Dictionary<(Of <(TKey, TValue>)>) class is implemented as a HashTable"
Dictionary is NOT implemented as a HashTable, but it is implemented following the concept of a hash table. The implementation is unrelated to the HashTable class because of the use of Generics, although internally Microsoft could have used the same code and replaced the symbols of type Object with TKey and TValue.
In .NET 1.0 Generics did not exist; this is where the HashTable and ArrayList originally began.
@Peter Mortensen 2017-10-23 08:11:09
Can you fix that MSDN quote? Something is missing or wrong; it is not grammatical and somewhat incomprehensible.
@prashant 2009-04-17 04:53:53
One more difference that I can figure out is:
We can not use Dictionary<KT,VT> (generics) with web services. The reason is no web service standard supports the generics standard.
@Siddharth 2015-11-30 11:04:21
We can use generic lists (List<string>) in soap based web service. But, we cannot use dictionary (or hashtable) in a webservice. I think the reason for this is that the .net xmlserializer cannot handle dictionary object.
@user38902 2008-11-19 11:55:47
FYI: In .NET,
Hashtableis thread safe for use by multiple reader threads and a single writing thread, while in
Dictionarypublic static members are thread safe, but any instance members are not guaranteed to be thread safe.
We had to change all our Dictionaries back to
Hashtablebecause of this.
@Triynko 2010-05-14 18:09:20
Fun. The Dictionary<T> source code looks a lot cleaner and faster. It might be better to use Dictionary and implement your own synchronization. If the Dictionary reads absolutely need to be current, then you'd simply have to synchronize access to the read/write methods of the Dictionary. It would be a lot of locking, but it would be correct.
@Triynko 2010-05-14 18:15:40
Alternatively, if your reads don't have to be absolutely current, you could treat the dictionary as immutable. You could then grab a reference to the Dictionary and gain performance by not synchronizing reads at all (since it's immutable and inherently thread-safe). To update it, you construct a complete updated copy of the Dictionary in the background, then just swap the reference with Interlocked.CompareExchange (assuming a single writing thread; multiple writing threads would require synchronizing the updates).
@Dan Neely 2012-01-27 20:49:56
.Net 4.0 added the
ConcurrentDictionaryclass which has all public/protected methods implemented to be thread-safe. If you don't need to support legacy platforms this would let you replace the
Hashtablein multithreaded code: msdn.microsoft.com/en-us/library/dd287191.aspx
@unkulunkulu 2012-03-11 21:34:17
anonymous to the rescue. Cool answer.
@supercat 2013-11-13 23:03:03
I recall reading that HashTable is only reader-writer thread-safe in the scenario where information is never deleted from the table. If a reader is asking for an item which is in the table while a different item is being deleted, and the reader would to look in more than one place for the item, it's possible that while the reader is searching the writer might move the item from a place which hasn't been examined to one which has, thus resulting in a false report that the item does not exist.
@mparkuk 2014-05-01 09:37:04
A Hashtable object consists of buckets that contain the elements of the collection. A bucket is a virtual subgroup of elements within the Hashtable, which makes searching and retrieving easier and faster than in most collections.
The Dictionary class has the same functionality as the Hashtable class. A Dictionary of a specific type (other than Object) has better performance than a Hashtable for value types because the elements of Hashtable are of type Object and, therefore, boxing and unboxing typically occur if storing or retrieving a value type.
For further reading: Hashtable and Dictionary Collection Types
@flesh 2008-11-19 09:28:22
The
Hashtableis a loosely-typed data structure, so you can add keys and values of any type to the
Hashtable. The
Dictionaryclass is a type-safe
Hashtableimplementation, and the keys and values are strongly typed. When creating a
Dictionaryinstance, you must specify the data types for both the key and value.
@alexandrekow 2014-10-29 11:12:30
The Extensive Examination of Data Structures Using C# article on MSDN states that there is also a difference in the collision resolution strategy:
The Hashtable class uses a technique referred to as rehashing.
The Dictionary uses a technique referred to as chaining.
@Altaf Patel 2014-05-28 07:53:11
Dictionary:
It returns/throws Exception if we try to find a key which does not exist.
It is faster than a Hashtable because there is no boxing and unboxing.
Only public static members are thread safe.
Dictionary is a generic type which means we can use it with any data type (When creating, must specify the data types for both keys and values).
Example:
Dictionary<string, string> <NameOfDictionaryVar> = new Dictionary<string, string>();
Dictionay is a type-safe implementation of Hashtable,
Keysand
Valuesare strongly typed.
Hashtable:
It returns null if we try to find a key which does not exist.
It is slower than dictionary because it requires boxing and unboxing.
All the members in a Hashtable are thread safe,
Hashtable is not a generic type,
Hashtable is loosely-typed data structure, we can add keys and values of any type.
@Jim Balter 2018-11-03 17:21:59
"It returns/throws Exception if we try to find a key which does not exist." Not if you use
Dictionary.TryGetValue
@Thetam 2011-04-21 10:32:47
Dictionary<<<>>>
Hashtabledifferences:
Synchronized()method
KeyValuePair<<<>>> Enumerated item:
DictionaryEntry
Dictionary/
Hashtablesimilarities:
GetHashCode()method
Similar .NET collections (candidates to use instead of Dictionary and Hashtable):
ConcurrentDictionary- thread safe (can be safely accessed from several threads concurrently)
HybridDictionary- optimized performance (for few items and also for many items)
OrderedDictionary- values can be accessed via int index (by order in which items were added)
SortedDictionary- items automatically sorted
StringDictionary- strongly typed and optimized for strings
@WAP Guy 2012-02-01 11:24:27
We can use concurrentDictionary(in .NET 4.0) for threadsafe.
@Aleksey Bykov 2013-06-29 22:18:31
@Guillaume86, this is why you use TryGetValue instead msdn.microsoft.com/en-us/library/bb347013.aspx
@Danny Chen 2014-06-25 06:24:45
+1 for
StringDictionary...btw
StringDictionaryisn't the same as
Dictionary<string, string>when you use the default constructor.
@VoteCoffee 2014-10-31 14:28:01
The ParallelExtensionsExtras @code.msdn.microsoft.com/windowsdesktop/… contains an ObservableConcurrentDictionary which is great fir binding as well as concurrency.
@mkb 2016-03-25 12:23:36
awesome explanation, it's really nice you also listed the similarities to lessen the questions that might comes to one's mind
@amit jha 2017-10-05 13:51:23
stackoverflow.com/a/1089142/5035500, net-informations.com/faq/general/dictionary.htm, c-sharpcorner.com/blogs/…
@Marc Gravell 2008-11-19 09:28:04
In .NET, the difference between
Dictionary<,>and
HashTableis primarily that the former is a generic type, so you get all the benefits of generics in terms of static type checking (and reduced boxing, but this isn't as big as people tend to think in terms of performance - there is a definite memory cost to boxing, though). | https://tutel.me/c/programming/questions/301371/tutel.me | CC-MAIN-2019-13 | refinedweb | 3,482 | 63.39 |
In my setup I have two monitors, with second being 120Hz and first being 60Hz. I want to create a Panda window on the second monitor and lock the refresh rate to 120Hz. While I see in the manual how to enable vsync and lock the frame rate, I couldn’t find info how to specify what display to open the Panda window on.
Hi, welcome to the forums!
Perhaps just using the window origin to place it past the end of the first monitor on the virtual desktop will work?
Which operating system are you using?
Hi rdb,
Sorry, I’m running on 64bit Windows 10.
My concern with creating the window on the first monitor and then moving it is that the max refresh rate may be locked to vsync of the first monitor rather than the second one.
Note that the resolutions of the two monitors also do not match, so we don’t end up with an extended display with total of X*2 x Y resolution.
How should I test this?
Thanks.
Update: The framerate meter that comes with Panda seems to indicate that the vsync framerate of the Panda window is updated as the window is moved to a new display. However there seems to be issue with the Panda3D Task timing when I do this.
Here’s what I do and my code to show the problem:
I’m running tests on human perception of pixel shifting at 120Hz (there are different rows displayed each frame, persistence of vision is meant to combine them into one frame).
My code seems to run fine on the 60Hz primary monitor, flickery because the pixel shifting is done at 60Hz, but when I move the window to the second monitor, the pixel shifting stops. It doesn’t stop in the sense that it is not perceivable, but in the sense that only one of the pixel row image is visible, meaning that either the task has been frozen, which a simple debug line show isn’t the case, or that the timing has messed up, which seems to be the case given that a highspeed camera shows that indeed only one row of pixels is shown all the time.
from panda3d.core import * from direct.showbase.ShowBase import ShowBase from direct.task import Task load_prc_file_data("", "vsync true") load_prc_file_data("", "win-size 1280 720") load_prc_file_data("", "textures-auto-power-2 1") load_prc_file_data("", "textures-power-2 up ") base = ShowBase() base.set_frame_rate_meter(True) # def load_image_as_plane(filepath, yresolution = 720): tex = loader.load_texture(filepath) tex.set_border_color(Vec4(0,0,0,0)) tex.set_wrap_u(Texture.WMBorderColor) tex.set_wrap_v(Texture.WMBorderColor) # disable texture filtering, optional tex.set_magfilter(SamplerState.FT_nearest) tex.set_minfilter(SamplerState.FT_nearest) cm = CardMaker(filepath + " card") cm.set_frame(-tex.get_orig_file_x_size(), tex.get_orig_file_x_size(), -tex.get_orig_file_y_size(), tex.get_orig_file_y_size()) card = NodePath(cm.generate()) card.set_texture(tex) card.set_scale(card.get_scale()/ yresolution) card.flatten_light() # apply scale return card image1 = load_image_as_plane("1.png") image1.reparentTo(aspect2d) image2 = load_image_as_plane("2.png") image2.reparentTo(aspect2d) image2.hide() def pixel_shift(task): if image1.is_hidden() == True: image1.show(); image2.hide() else: image2.show(); image1.hide() return task.cont base.task_mgr.add(pixel_shift, "pixel_shift") base.run()
Hmm… This is a bit of a guess, but what happens if you set an explicit clock-rate of 120Hz, either together with or instead of enabling v-sync?
Something like this:
load_prc_file_data("", "clock-mode limited") load_prc_file_data("", "clock-frame-rate 120")
Hi,
In both these cases the two images displaying the different rows seem to be shifted randomly and slower.
Please note that the config.prc setting for vsync is
sync-video, not
vsync.
Thanks, looks like Panda was using the setting from Config.prc instead.
However, this doesn’t fix the issue.
Turning off the main monitor and running the script then seems to run correctly. I think we have a more general bug or issue here relating to multimonitor setups and the task manager. | https://discourse.panda3d.org/t/how-to-use-the-secondary-monitor/26880 | CC-MAIN-2021-04 | refinedweb | 648 | 56.45 |
You see, I spend a lot of time browsing deviantART, and there are some pretty good artists whose work I like specially. So much that I sometimes feel like downloading their entire gallery! But because individually downloading 20 and so pictures is boring, I decided to make a small program to automate that for me. It works in two phases, two functions:
- getImgUrls, which pulls the images' urls from the gallery's HTML source code using a regular expression;
- downloadImgs, that, well... downloads the images one by one onto your filesystem.
As for its usage, I recommend that you import the script into another .py file and use its functions there, for the sake of modularity. Here's an example usage:
- Code: Select all
from deviantARTdownloader import getImgUrls, downloadImgs
# url is the gallery's address / core_name is used to name the images
d = getImgUrls(url="", core_name="blueraincz") # getImgUrls returns a dictionary
# urlDict is a dictionary returned by getImgUrls / imgFormat is the image's format; 'jpg' is the default / path is the path to which the files will be saved
downloadImgs(urlDict=d, imgFormat='jpg', path="/home/myHome/blueraincz") # this downloads the file
Finally, the script is protected by the GNU general public license. Hence, as long as you do not violate the terms of the license, and distribute all sub-products under the GNU general public license, you can do whatever you wish this script.
WARNING: This works in version 2.7. Later versions maybe incompatible with this script. | http://python-forum.org/viewtopic.php?f=11&t=242&p=487 | CC-MAIN-2014-49 | refinedweb | 249 | 58.21 |
6 Apr 11:10 2004
Re: Extensible parser.
<jastrachan@...>
2004-04-06 09:10:10 GMT
2004-04-06 09:10:10 GMT
Very interesting! I think some kind of macro system would be very useful. My biggest fear is macros breaking refactoring support (or at least making it very hard). A few use cases I can imagine for macros... * defining properties along with bound/unbound listener notifications * defining lazily-constructed properties * listener stuff * logging Log.{ About to open file ${foo} } which could hide all the plumbing details of using a particular logging framework. Though maybe a mixin is just as easy for logging? Though apart from the above, I do struggle to imagine when I'd find myself using macros. FWIW I see using AOP to introduce advice into existing objects as far more common - e.g. adding security, transactions, persistence and so forth. On 6 Apr 2004, at 03:25, Bruce Chapman wrote: > Hi all, > > I am a real newby here so forgive any faux pas. > > I have been thinking about this sort of thing for a while, and have > experimented with extending the java compiler by running user code as > part > of the compiler process. > > So here goes with a bit of a brain dump. > > With regard to macro processing > > In the wiki here > there > is a reference to which > has > some useful background info and some ways of classifying macro systems > etc. > > Especially see section 3, An overview of Syntax representations. > > What I would propose is a token based macro system (as opposed to a > syntax > tree based one as proposed by Neil), with the following form, (which > gets > around the problems mentioned in 3.2 of the d-expressions paper) > > A macro "call" looks like this > > Classname ".{" anyTokensParenthesesMatch "}" > > anyTokensParenthesesMatch is a list of tokens with matching > parentheses. I > could write a formal definition but I wont for simplicity. > > The parser would just parse up to the closing "}" > > A macro "call" can exist where a class member declaration, a > statement, or > ( possibly) an expression is required. > > The compiler then instantiates an instance of classname (which must > implement a specific interface - say CodeGenerator.) Once it has > worked out > the fully qualified name. > > - caution JSR14 syntax in following signatures - > > The CodeGenerator is passed the list of tokens and returns a list of > errors. > (may be empty) - List<ParsingError> parse(List<token>) > > -aside - The tokens would have type, value, and a source position. > > If there are errors the compiler displays them. ParsingError would > include > description and the offending token or at least its source position. > > If there are no errors, the CodeGenerator is called to generate the > expanded > macro. > > List<Token> generate(List<Token>) > > The compiler then parses the generated replacement list of tokens in > place > of the orginal macro call construct. If there are errors in there they > are > processed as normal, the tokens will either > - have been copied from the original list of tokens, and so will have > a > source position in the original source. > Or - will have been generated inside the generate method (using a > token > factory passed as an argument but not shown in the signature above) In > this > case the factory can use a stack trace for each token synthesised, to > give a > source position inside the generate method. Of course good macro > generators > won't have syntax errors in their synthetic tokens :) > > Example Usage > ------------- > > class Person { > Properties.{ > readonly String name > readonly Date dateOfBirth > Any address > } > // more vanilla groovy code here > } > > public class Properties implements ClassMemberGenerator { > public Properties() {} // so the compiler can instantiate it !! > List<ParseError> parse(List<Token> args) { .... } > List<Token> generate(List<Token> args, TokenFactory f, Context c) { > ... > } > } > > > > Some advantages of this approach > -------------------------------- > > All macro syntax must maintain some semblance of groovyness in that > only > groovy lexing is used, other than that anything goes (notwithstanding > "{" > matching requirements). Even XML! > > Can use standard lexer (without extension). > > Macro syntax is defined as much or as little as required inside the > generator - no need to generate some formal grammar object (tree) to > be used > by the parser per-se. > > The output of the generate() method is a list of tokens, which is > closer to > how mortal programmers think of their code, Compare this with a syntax > tree > which requires far more specialist ( &internal?) knowledge. > > The existance of the macro call/expansion, and its scope ".{" and > matching > "}" are very EXPLICIT with this syntax. One problem with reading code > that > uses macros is that it can be hard to discern what is macro and what is > formal language, this makes it really obvious, without being verbose. I > would put both of these (obvious and NOT verbose) quite near the top > of any > requirements list for a macro system. > > The macro call scope is natural (obvious), even if you hadn't seen the > syntax before. > > The "classname.{ tokens }" syntax hints that classname is processing > the > tokens in some way, which is not a method call or any other runtime > operation. There are elements (hints of) of a method call syntax > there, but > it quite definitely isn't a method call. > > Avoids the use of some new formal syntax for defining macros. Its all > just > java (or compiled groovy) code. (Neil's proposal does not exhibit this > problem either - but many macro systems do and it is a problem because > it > makes the functionality less accessible to mortals). > > An IDE could easily toggle between displaying the macro call, and its > expansion, by calling the parse and generate methods on the Generator. > You > could maybe even edit the generated code and (because the input tokens > and > output tokens are ===), reverse engineer the change back into the > macro call > (or not if a token synthesised by the token factory was modified or was > attempted to be). > > The macro generation code can use the full power of the JVM and > libraries, > so you could for instance access a database and build a Data access > object. > > The places where a macro call may exist are quite clearly defined. this > helps to keep things explicit (good for code maintainers). > > > > > I have more ideas on this and some more details but I'll leave it > there for > now and see what others think. > > Bruce Chapman > > _______________________________________________ > groovy-dev mailing list > groovy-dev@... > > > James ------- | http://permalink.gmane.org/gmane.comp.lang.groovy.devel/864 | CC-MAIN-2016-26 | refinedweb | 1,038 | 61.77 |
com
13
chandigarh | gurugram | jalandhar | bathinda | jammu | srinagar | vol.139 no.14 | 26 pages | ~4.50 | regd.no.chd/0006/2018-2020 established in 1881 | monday, january14,2019 � late city
BJP SAYS DOORS OPEN INFOCUS: FOOD SAFETY SERENA CHASES HISTORY
FOR PHOOLKA PAGE 2 HOW WAX WORKS PAGE 12 AT AUS OPEN PAGE 15
/thetribunechd /thetribunechd
Politicians should
keep off other
fields: Gadkari
Coining glory SC judge opts out of IN BRIEF
Mumbai, January 13
Union Minister Nitin Gad-
kari on Sunday advised fel-
post-retirement post
low politicians not to inter-
fere in “other fields”.
Justice Sikri says no amidst row over decision on CBI chief
The senior BJP leader was Tribune News Service Verma’s ouster was wrong.
speaking at the valedictory They said though Justice
function of an annual New Delhi, January 13 Sikri had given his consent Pope to parents: It’s OK to
Marathi literary meet at Amid the controversy over for the London assignment, fight, just not in front of kids
Yavatmal, which has been his possible nomination to he was not aware of the gov- Vatican City: Pope Francis offered
embroiled in a controversy the London-based Common- ernment’s decision, adding new parents a bit of advice on
after an invitation to noted wealth Secretariat Arbitral that he had also conveyed Sunday, telling them it’s perfect-
writer Nayantara Sahgal was Tribunal (CSAT) by the that he was not looking for ly normal to fight, but just not in
withdrawn by the organisers. Narendra Modi government, any post-retirement job. He front of the children. “You have
Gadkari said, “Politicians Supreme Court Judge AK is due to retire from the no idea of children’s anguish
should learn not to interfere in Sikri today withdrew his con- Supreme Court on March 6. when they see their parents
other fields. The people in uni- sent for the assignment. Justice AK Sikri Government sources fight.” One of his favourite
versities, educational institu- Sources said Justice Sikri admitted that a process was axioms is that couples should
tions, literature and poetry has conveyed to the govern- PM Modi, Congress leader initiated to take the consent make a habit of saying “Please,
should be dealing with their ment his decision. Mallikarjun Kharge and Jus- of Justice Sikri for the CSAT thank you and sorry”, and
(respective) areas.” Justice Sikri’s consent for tice Sikri had removed Verma appointment, but remained should never go to bed mad. AP
“When I say there should the CSAT assignment, it is from the post of CBI Director tightlipped about the with-
not be any interference, it learnt, was taken in the first by a majority 2:1 verdict, as drawal. They said it required Amending Constitution for
does not mean there should week of December, a month Kharge gave a dissent note. a long drawn process to com- quota ‘harmful’: Pawar
not be any contact between before a Bench headed by Justice Sikri was nominat- plete formalities and the Kolhapur: Experts feel that
the people from the field of lit- Chief Justice of India Ranjan ed to the panel by CJI Gogoi, judge was also not immedi- amending the Constitution to
erature and politicians,” he Gogoi reinstated former CBI who headed the Bench which ately available for the post. increase the reservation limit is
added. “During Emergency, Director Alok Verma to the delivered the ruling on Ver- Interestingly, in a Twitter “harmful” to its basic principles,
the speeches of (Marathi) post, as the latter had chal- ma’s reinstatement. post, former SC Judge NCP chief Sharad Pawar said on
writers like Durga Bhagwat lenged the government’s Government sources said Markandey Katju countered Sunday, days after Parliament
and PL Deshpande drew big- decision to send him on the insinuation linking the the media reports as “fake cleared a Bill to provide 10 per
ger crowds than rallies. Both, His predecessor Dr Manmohan Singh by his side, Prime Minister Narendra Modi releases forced leave in October. CSAT assignment with Jus- news”. He said, “I have spo- cent quota to economically
however, returned to litera- a commemorative coin to mark the birth anniversary of Guru Gobind Singh in New Delhi On January 10, the high- tice Sikri’s participation in ken with Justice Sikri, and backward sections among the
ture after the election.” — PTI on Sunday. TRIBUNE PHOTO REPORT ON BACK PAGE powered selection panel of the panel which decided on will publish true facts.” General Category. PTI
After alliance snub, Cong Punjab loan waiver Al-Badr commander, aide
to contest all 80 UP seats to farmhands likely killed in Kulgam gunfight
Azad: Only grand old party can challenge, defeat BJP Meeting today, beneficiary list in works But for Naikoo and Musa, all top ultras eliminated: Police
Shahira Naim Chandigarh, January 13 Suhail A Shah & launched a search operation. a few months ago. Thousands
Tribune News Service ‘RESULTS WILL BE SURPRISING’ In an election mode, a crucial Majid Jahangir Initially, the police said two of mourners today attended
Lucknow, January 13 meeting of the Punjab Gov- militants had been killed. It Zeenat’s funeral in his
Virtually rejecting the BSP-
SP offer of two seats in Uttar
❝ Congress has its presence from
the north to south and east to west...
ernment on extending its flag-
ship crop loan waiver scheme
Anantnag/Srinagar, January13
Wanted Al-Badr commander
was midnight when the
deceased were identified as
native village Sugan in
Shopian. His father Ghulam
Pradesh, the Congress today results would be surprising. We would to 3.7 lakh farmhands in the Zeenat-ul-Islam (29), a key Zeenat and his aide Shakeel Hassan Shah called his
announced its decision to double if not triple the 2009 tally in UP state is to be held tomorrow. recruiter who escaped several Ahmad Dar. killing a “proud moment”.
contest all 80 Lok Sabha Ghulam Nabi Azad, CONGRESS INCHARGE, UP With the Punjab Khet Maz- times by breaking the securi- The police said apart from Clashes erupted when the
seats in the state, making it a door Union claiming that 85 ~600-CRORE RELIEF ty cordon, ran out of luck late being an IED expert, Zeenat forces restricted the move-
three-cornered contest. per cent of farm labourers are ■ ~600-crore loans of up to Saturday. He was killed along was a key recruiter. “It was ment of mourners. More
Senior Congress leader and seats of Amethi and Rae with full preparation and con- under debt, the exercise to ~50,000 taken by farm with his aide in south Kash- often at funerals of militants, than 10 persons were
incharge of the state, Ghulam Bareli. As a matter of fact, fidence under the leadership identify potential beneficiar- workers from agricultural mir’s Kulgam district. when emotions run high, that injured as the forces fired
Nabi Azad, told reporters that Mayawati described Con- of Rahul Gandhi. “The ies as per the laid down crite- societies may be waived The operational chief of Al- he would pick recruits,” a bullets and pellets. A
this was not an Assembly poll gress and BJP as two sides of results would be surprising. ria has already begun. ■ Pressure is building to extend Badr was one of the few sur- police official said. woman suffered injuries
but a national election in a coin and claimed that there We would double if not triple Officials say loans worth Rs benefit to families of farmers viving militants on the list of when she was allegedly hit
which only the Congress was no benefit in allying with the 2009 results,” said Azad. 600 crore of up to Rs 50,000 who committed suicide the Army’s “22 most wanted” 10 injured in clashes by a security vehicle.
could challenge and defeat the Congress as its votes were In 2009, the Congress had taken by farm workers from released in June last year. His Former Jammu and Kash-
the BJP. There was, however, not transferable. won 21 seats in UP and one agricultural societies are farmers who had taken loans elimination is believed to at time of funeral mir Chief Minister Mehboo-
enough flexibility to accom- Commenting on the BSP- more later in a bypoll, taking expected to be waived. A pro- from cooperative and com- have further weakened the ba Mufti termed the security
modate any capable person SP alliance, Azad said, “We the total number of MPs forma, detailing the profile of mercial banks. militant ranks in Kashmir. Active since 2006, Zeenat forces’ action unfortunate
or secular-minded party on did not break the alliance. from UP to 22. the intended beneficiaries, has The process to cover small Since November, more than was arrested in 2009 in north and disturbing. “Reports of
these 80 seats, he added. During the last six months I Without naming Mayawati, been circulated to the depart- farmers is underway. As six top commanders have Kashmir’s Sopore and jailed aerial firing to stop the crowd
The decision to go it alone gave at least 15 bytes that Azad said those who blamed ment concerned. many as 2.15 lakh small farm- been killed by the forces. for at least four years. In 2015, from participating in the
in the politically significant any party which wanted to the Congress for not doing The Congress had promised ers who had taken loan from “Except for Riyaz Naikoo and he joined the Lashkar-e-Toiba funeral of a local militant are
state of Uttar Pradesh comes defeat the BJP was welcome enough for the marginalised during the Assembly elections cooperative banks will be cov- Zakir Musa, the top militant and then Hizbul Mujahideen. very unfortunate and dis-
a day after BSP’s Mayawati to join the alliance. What can overlook the party’s history that its loan waiver scheme ered in the third phase, while leadership has been eliminat- He was allegedly involved in turbing. Such interference in
and SP’s Akhilesh Yadav we do if some parties do not and constant endeavour to would cover landless farm 50,752 small farmers who had ed,” said police sources. an ambush in February 2017 the religious affairs is unde-
announced their alliance, want to join?” work for the mainstreaming labourers, SCs and Backward taken loan from commercial The gunfight at Kathpora that left three Army jawans sirable and may backfire,
deciding not to field candi- He said the Congress would of the deprived. Classes. So far, the govern- banks will be covered in the Yaripora on Saturday erupted dead and five wounded. He leading to further anger and
dates from the Congress-held contest the 80 seats in UP case of fait accompli page 7 ment has covered marginal next phase. — TNS after dusk when the forces became Al-Badr commander alienation,” she tweeted.
Punjab lad Shubman gets India call Pak civil society livid over ‘Manto’ ban
Prolific 19-yr-old batsman selected for New Zealand tour that begins on Jan 23 Plan protests in cities of Lahore, Karachi, Multan and Peshawar today
Sunny Kaul a young guy whose batting I Smita Sharma exhibitor who applied for
like to watch. He is very
❝ CBFC clearance chose not to
Tribune News Service Tribune news service
Manto is under
Chandigarh, January 13 exciting,” Yuvi had said New Delhi, January 13 respond to a notice and argue
Sixteen years of dreaming about his state-mate. Amid cross-border shelling the worst attack by the their case,” he said.
and working to play for Interestingly, in the nine and animosity, a rare India- state machinery and “Manto is under the worst
India seem to have borne first-class matches he has Pakistan solidarity is on dis- the censor board has attack by the state machinery
fruit for Shubman Gill — played so far, he has not play. Pakistan’s civil society taken the liberty to and the censor board has tak-
the 19-year-old has been aggregated less than 50 groups, journalists and snub and kill sanity in en the liberty to snub and kill
selected in the India team even once. artistes have joined hands to sanity in my country. This is
for the ODI and T20I tour of Gill also had a great role in demand that the Imran Khan
my country. This is an an attack on common sense
New Zealand, which begins India’s success at the ICC government lifts its ban on attack on common and good sense of the peo-
on January 23. U-19 World Cup in New Indian film ‘Manto’. sense and good sense ple,” remarked a livid Ahmed.
The Fazilka boy, who Zealand early last year. The The critically acclaimed of the people. On the support across the
moved to Mohali to hone dashing top-order batsman movie by Nandita Das is a Saeed Ahmed, PAK PLAYWRIGHT border for her film in which
skills, has been in excellent smashed a timely 102 to help celebration of the legendary Nawazuddin Siddiqui plays
form in the Ranji Trophy, India beat Pakistan in the Urdu writer who chose to the protagonist, Nandita Das
with two 100s and five 50s. He An ecstatic Shubman Gill with his father Lakhwinder Singh, who semis and was named the move to Pakistan post-Parti- ing of the movie in Pakistan. Pakistan’. Would the same wrote on Facebook, “It is very
was included in the squad is also his coach, in Mohali on Sunday. TRIBUNE PHOTO: RAVI KUMAR Player of the Tournament. tion in January 1948 after Saeed Ahmed, a playwright, dreadful fate befall the writ- moving to see that so many
after KL Rahul and Hardik Rated highly by the likes having lived in Bombay since who was also a key consultant ers, particularly Manto, in have taken it upon them-
Pandya were suspended. and all with his batting Hyderabad. The second of Rahul Dravid and WV 1936. Having faced nearly six for the movie, started an ‘Naya Pakistan’?” selves to fight the battle. My
“After the 2019 World Cup, prowess and a staggering knock at Hyderabad helped Raman, Gill has the belief trials for his frank and con- online petition on change.org Speaking from Lahore, team and I can take zero cred-
he can make it to the (Indi- average of 77.78 since he Punjab nearly pull off an that he can deliver at the troversial writings, his legacy and has called for protests in Ahmed said while the film was it. I hope the distributor will
an) side,” Yuvraj Singh made his first-class debut improbable chase on the big stage. “When these is much respected by the peo- collaboration with Manto cleared by the Sindh branch of also join the efforts.”
recently predicted about in November 2017 is a testi- last day of their Ranji Tro- guys hold you in good ple of the sub-continent. Memorial Society. the censor board, objections Last week, the Lahore Arts
Gill, hailing him as a “spe- mony to his talent. phy match in December. esteem, you know that you People are coming together In an open letter to PM were raised by the board in Council had reportedly can-
cial talent”. Gill’s selection He has put up two very Chasing 338 for victory, are moving in the right at 4 pm (local time) on Mon- Imran Khan, he wrote,“Saa- Lahore, citing obscenity and celled the Manto festival
in the Indian team only significant scores in the last Punjab, powered by Gill, direction and just need to day to protest in Lahore, dat Hassan Manto faced per- opposition to Partition por- scheduled for January 14-16.
affirmed that belief. one month: 268 against finished at 324/8. carry on,” said Gill. Karachi, Peshawar and Mul- secution, torture and years of trayed in the movie. “Unfortu- This too had triggered
Gill has impressed one Tamil Nadu and 148 against “After a long time there is MORE on PAGE 14 tan, demanding the screen- court trials during ‘Purana nately, the distributor and protests.
Today’s issue is of 26 pages, including six-page Chandigarh Tribune and four-page Life+Style.
02 PUNJAB THE TRIBUNE
CHANDIGARH | MONDAY | 14 JANUARY 2019
New advt policy fetches Picking Jalandhar candidate Won’t shift seat
~27.54 cr for Ludhiana a daunting task for Akali Dal to Sikar: Jakhar
LS POLL Party has won seat only twice in 16 polls Constituency in Rajasthan is
❝
Chandigarh, January 13
The ambitious Outdoor Adver- After the new policy, the
tisement Policy of the Local
Government has started bear-
annual income of the Moga MC
has increased from ~30 lakh to
Deepkamal Kaur
Tribune News Service
NO SITTING SC MLA READY TO CONTEST
PPCC chief’s family stronghold
ing fruit and fetched ~27.54 ~1 crore and the revenue of the Jalandhar, January 13 ■ Theconstituency is a Congress stronghold and the SAD
Ravi Dhaliwal
crore for Ludhiana alone for Pathankot MC has increased The Shiromani Akali Dal will Tribune News Service
has been experimenting by changing its candidate from
the first year in the online auc- face a Herculean task to find Gurdaspur, January 13
tion that concluded yesterday.
from ~20 lakh to ~67 lakh. a suitable face for the Jaland-
the seat each time, but losing dismally
Gurdaspur MP and PPCC
The total revenue from all Navjot Singh Sidhu, LOCAL GOVERNMENT MINISTER har Lok Sabha seat this time.
■ Now when the SAD is lying politically low in the state, no president Sunil Jakhar
the 168 local governments The constituency is a Con- sitting SC MLA in Doaba is ready to contest the Lok Sab- today said he would recon-
last financial year was about of the Pathankot MC had Ludhiana richer by ~289 crore gress stronghold. The SAD, ha polls, be it Tinu from Adampur, Baldev Khaira from test the Gurdaspur seat,
❝
Phillaur or Sukhwinder Sukhi from Banga
~18 crore only. After the new increased from ~20 lakh to after nine years, based on cal- which has won only twice putting to rest rumours I have no intention to
■ The
Congress is likely to repeat its candidate Chaudhary
policy, this year the expect- ~67 lakh. The annual income culations at the current price, from this seat in the last 16 that he wanted to shift to contest from any other
ed revenue was likely to be targets for Amritsar and which would mean an increase elections, has been experi- Santokh Singh from Jalandhar, although sitting MLA Sikar in Rajasthan — the constituency. I am working
between ~150 and ~175 Mohali had been set at ~20 of 800 per cent revenue. The menting by changing its can- Sushil Rinku too is said to be a claimant seat represented by his hard for the people of
crore, said Local Govern- crore each. The minimum tender had gone to Leaf Berry didate from the seat each father, the late Balram Gurdaspur who voted for
ment Minister Navjot Singh base price for Jalandhar had Advertisement Private Limit- time, but losing dismally. Baldev Khaira from Phillaur or Jalandhar, although sitting Jakhar, from 1984 to 1991. me. I have sought a revival
Sidhu, while addressing a been fixed at ~18.15 crore. ed. The average annual While it fielded former PM’s Sukhwinder Sukhi from Ban- MLA Sushil Rinku too is said to For the past few weeks, package for the 150-year-
press conference here today. In case of Ludhiana, the earn- income, in Ludhiana alone, son Naresh Kumar Gujral in ga. As of now, the names of a few be a claimant. The party, how- there had been speculation old Dhariwal Woollen Mills
Sidhu said after the new ings last year were only ~1.75 would be ~32 crore, he said. 2004, it projected Sufi singer leaders are doing the rounds, ever, is delving on choosing that Jakhar, who won the and have received a
policy, the annual income of crore. The total earning, here He said the department had and Valmiki leader Hans Raj including former Speaker Cha- between former MP Santosh Gurdaspur seat in the 2017 positive response from the
the Moga Municipal Corpora- during the past 10 years was decided not to allow any adver- Hans in 2009, when the seat ranjit Atwal, his son Inder Iqbal Chaudhary and sitting MP Raj byelection by a whopping Textiles Ministry.
tion had increased from ~30 only ~31 crore approximately. tisement on building wraps got reserved. In 2014, the Atwal and former minister Kumar Chabbewal from 1.90 lakh votes, may shift to Sunil Jakhar, GURDASPUR MP
lakh to ~1 crore. The revenue The new tender would have and also rooftops. — TNS Akali Dal picked its MLA and Sohan Singh Thandal. Hoshiarpur. Sampla had won his family borough Sikar.
Ravidassia leader Pawan Since Atwals are Valmikis and the seat with a margin of 13,582 “I have no intention to “I have obtained clear-
Tinu. While Gujral had lost to Jalandhar is dominated by Ravi- against former Jalandhar MP contest from any other ance from the Railways for
Congress’ Rana Gurjeet dassias, there can be a problem MS Kaypee. Having lost elec- constituency. I am working an overbridge in Dinanagar
Singh by 33,464 votes, Hans for consensus on their name. tions thrice, he could face a hard for the people of Gur- and an underbridge on the
got defeated by 36,445 votes The proposed seat swapping denial this time. Party sources, daspur who voted for me. I Tibri (Gurdaspur) crossing.
against MS Kaypee. Even in between the SAD and the BJP however, shared that he had have sought a revival pack- The Surface Transport Min-
2019, when the NDA won tri- for Jalandhar and Hoshiarpur been lobbying hard. age for the 150-year-old istry has cleared a sum of
umphantly, Tinu got trounced also seems quite unlikely. For- AAP has already declared Dhariwal Woollen Mills Rs 26-crore for bridges in
with 70,989 votes from Chaud- mer BJP state president Vijay its Doaba president Dr and have received a posi- Mastpur and Faridnagar
hary Santokh Singh. Sampla yesterday said: “There Ravjot Singh as candidate tive response from the Tex- villages in the Bhoa Assem-
Now when the SAD is lying will be no seat swapping. I will be from Hoshiarpur. BSP is tiles Ministry,” the MP told bly seat. The crushing
politically low in the state, no sit- re-contesting from Hoshiarpur.” seeking three seats from the The Tribune. capacity of the Paniyar and
ting SC MLA in Doaba is ready The Congress is likely to proposed Punjab Democrat- To dispel rumours, Jakhar Batala sugar mills is being
to contest the Lok Sabha polls, repeat its candidate Chaud- ic Alliance, including has visited the constituen- raised with the backing of
be it Tinu from Adampur, hary Santokh Singh from Jalandhar and Hoshiarpur. cy five times in the last one Co-operation Minister
week. A trip to Gurdaspur Sukhjinder Singh Rand-
was by followed by one to hawa,” Jakhar said.
Batala, Dinanagar and then Sources say the MP has
Virasat-e-Khalsa
sees record visitors
Enters Limca Book of Records
Tribune News Service
Ropar, January 13
“Virasat-e-Khalsa,” a muse-
um which highlights the
Sikh history has made it to
Limca Book of Records. Till
now, over 9.7 million visi-
tors, including Canadian Over 9.7 million visitors visited
Prime Minister, President the museum in seven years.
of Mauritius and ambassa-
dors of various nations, showcases subsequent
among others, have visited epochs, including times of
the museum since its first Baba Banda Singh Bahadur
phase comprising 14 gal- and Maharaja Ranjit Singh
leries opened on November through 3-D technology.
25, 2011. The second phase The museum has also
of the museum comprising boosted the economy of
13 galleries was opened on Anandpur Sahib. Ever since
November 25, 2016. the first phase was thrown
Tourism and Cultural open to public, the Shiro-
Affairs Minister Navjot Singh mani Gurdwara Parbandhak
Sidhu said as per validation Committee’s (SGPC) rev-
by Limca Book of Records, enue from shops has
“Virasat-e-Khalsa” conceived increased five times and 300
to commemorate 550 years of people have been employed
history and culture of Punjab at “Virasat-e -Khalsa.”
has become a top ranked Similarly, offerings at
museum in the country. Takht Keshgarh Sahib have
While the first phase gone up to ~60 crore and
depicts Sikh history from deposits in banks stood at
Guru Nanak Dev’s era to the ~712.15 crore on March 31,
installation of Guru Granth 2018 against ~377.39 crore
Sahib, the second phase on March 31, 2012.
04 PUNJAB THE TRIBUNE
CHANDIGARH | MONDAY | 14 JANUARY 2019
in 5 pvt medical
his press conferences here all by himself. But at his last with lepers for the past three decades.
press meet on Thursday, he was accompanied by his sup-
porters. This time, he was addressing the media as the pres- DC turns Good Samaritan
ident of the newly formed Punjabi Ekta Party. So, he could Fatehgarh Sahib: On a chilly Friday night, Deputy Commis-
colleges vacant
not afford to come alone. He was required to put up a show sioner Shiv Dular Singh Dhillon stepped out of his house
of strength, giving out the message that he has the numbers with several blankets to find people sleeping in the open.
for making a change in the state politics that he has been He visited the railway station, Gurdwara Fatehgarh Sahib
claiming. Some of his supporters present at the press meet and public parks, and put blankets over people sleeping
were aligned with AAP, but now decided come his way. Will there without waking them up. The novel gesture by the
Varinder Singh
Tribune News Service Poor salaries, the numbers translate into votes? Only time will tell. DC has set an example for others to help the needy.
Jalandhar, January 13
A poor pay package and an
age bar to The staff have asked the authorities to repair the bathrooms or CONTRIBUTED BY KULWINDER SANDHU, JASWANT SHETRA, DEEPKAMAL KAUR, ARCHIT WATTS, RAJ SADOSH AND SURINDER BHARDWAJ
age bar at 70 in Punjab’s five
private medical colleges has
blame; experts at least instal doors, but their demand has fallen on deaf ears.
Ropar, January 13
Besides, there are cracks in
the double-storey building.
Separate papers for those who scored above 80% in mid-term too
Medical College in Ludhiana subsequently raise the stan- Prime Minister Narendra An official said the MC did Sanjeev Singh Bariana and there will be separate professional courses. They
— are facing an acute short- dard of medical education,” Modi’s Swachh Bharat Mis- not have funds for the repair Tribune News Service tests for those who scored will be given special papers.”
age of teaching faculty. he told The Tribune. sion seems to have made no work, claiming it was respon- Chandigarh, January 13 above 80 per cent. Singh said: “We have not
The faculty in private med- Dr OP Aggrawal of Mullana impact on the office of the Civ- sible for the upkeep of hospi- The Education Department Nearly 1.12 lakh students prepared any separate mer-
ical colleges is paid far less College, Ambala, pointed out il Surgeon here. tals and had nothing to do is conducting a special exam- who failed in mathematics it list for Class XII students
than those in government col- that till 2004 there were seven The stench emanating from with the Civil Surgeon’s ination for academically during their mid-term exams because there are different
leges. For example, a senior or eight teachers for a batch choked drains in toilets have office. As for the PWD, it want- weak students of Classes X are on the academically weak combinations. Our district
faculty member in a private of 150 students. “The made it difficult for the staff to ed funds from the Directorate and XII in government students’ list for Class X, teams are coordinating the
medical college is paid ~1.5 downslide came after that.” work. To make matters worse, of Health Services (DHS), schools to prepare them for which also comprises 98,000 examination for this class
lakh per month whereas Health Minister Brahm the toilets do not have doors. before taking up the work and annual examination of the
POOR SHOW students who flunked in Eng- at their level.”
his/her counterpart in govern- Mohindra said: “The faculty The staff have asked the the DHS, on its part, had not Punjab School Education The list shows the number of lish, 87,000 in science, 85,000 He said: “A sizable number
ment colleges on an average in private as well as govern- authorities to repair the bath- made any provision in the Board (PSEB) in March. Class X students who flunked in social studies, 63,000 in of parents are involved in the
draws a salary of ~2.5 lakh. ment medical colleges will rooms or at least instal doors, Budget for it, he said. The exams will begin on the mid-term examinations. Hindi and 44,000 in Punjabi. exercise of preparing their
The authorities concerned be strengthened. The gov- but their demand has fallen Officiating Civil Surgeon Dr January 22 and will also be Subject No. of students Special programme coordi- wards for the board examina-
are well aware of the faculty ernment medical colleges in on deaf ears. Avtar Singh said: “Since July conducted in February. Mathematics 1.12 lakh nator Jarnail Singh told The tion through WhatsApp
crunch but have made little Amritsar and Patiala too are The dilapidated toilets are 2016, several letters have been Based on the merit list English 98,000 Tribune, “We are conducting groups handled by district
effort to address the issue. facing a shortage of teach- not the only area of concern. written to the authorities, prepared on the basis of separate classes for students coordinators. Let us see the
Science 87,000
Some experts suggest rais- ers. More than 50 per cent of Employees say the electrical demanding repair of the build- mid-term examination who scored more than 80 per impact of the first set of pre-
ing the age bar to 72, if not the total 628 faculty posi- wiring needs to be replaced, ing. But nothing has been done. results, there will be a set of Social studies 85,000 cent in their mid-term exam- board examination. Later, it
75. Dr Mandip Singh Sethi, tions in these two colleges as there have been several I will try to arrange funds for papers for students who Hindi 63,000 ination to give them a feel of can be made a part of a regu-
Associate Professor (Medi- are lying vacant.” instances of short-circuit in repairing at least the toilets.” scored less than 40 per cent Punjabi 44,000 competitive entrance tests to lar academic calendar.”
Yamunanagar, January 13
and informing the police.
Chhachhrauli
Rakesh Kumar Rana said
SHO
Tribune News Service Pradeep Sharma The DDOs concerned recently following which the A 15-year-old girl died in a police team was sent
Rewari, January 13 Tribune News Service ❝
will be personally authorities concerned were Malikpur Khadar village to Malikpur Khadar vil-
Though brass utensils are Chandigarh, January 13
responsible for the asked to ensure “statutory of Yamunanagar district lage. The team stopped
losing their lustre in Rewari Chief Minister Manohar Lal deposit of EPF/ESI in the compliance” of the orders in under mysterious circum- the cremation and took
district, which is also known Khattar has stepped in to end accounts of the time. “In case of negligence, stances on Saturday night. the body to the civil hospi-
as the ‘City of Brass’, its exploitation of the contractu- contractual employees. the DDOs concerned will be Following a tip off, the tal in Jagadhri.
copper vessels are in al employees of the Haryana In case of negligence, the held personally liable and police reached the village He said members of the
demand for ‘Gangapujan’ Government employed DDOs will be held amount equivalent to the on Sunday and took the deceased’s family told the
at Ardh Kumbh scheduled through contractors and out- personally liable and amount of EPF and ESI con- body to the civil hospital police that the girl had
to commence in Allahabad sourcing agencies regarding amount equivalent to the tribution will be deducted in Jagadhri for post- been suffering from some
on January 15. depositing of their employ- amount of EPF and ESI from the salary of such mortem examination. disease for a long time.
More than one lakh copper An artisan shows a copper vessel in Rewari. TRIBUNE PHOTO ees’ provident fund (EPF) contribution will be DDOs,” the directive warned. According to informa- He said the family told
vessels have been supplied to and employees’ state insur- deducted from the salary Meanwhile, a certificate tion, the 15-year-old girl, them that when her condi-
Allahabad from Rewari in the ❝ Past three months have gone well for all those ance (ESI) contribution. of such DDOs.❞ regarding strict compliance who matriculated last tion deteriorated on
past three months. Copper associated with copper utensils business. They On the directions of the —A government directive of the orders will be obtained year, died on Saturday Saturday night, they took
manufacturers are still hope- worked round the clock to meet the massive demand Chief Minister, the Labour by the authorities concerned night. Members of her her to a private hospital in
ful for more orders in coming for vessels in Ardh Kumbh. A huge consignment Department has cracked outsourcing agencies they from the field offices and family were making the area.
days. As per manufacturers, weighing 15 tonnes and carrying items worth Rs 80 the whip on the Drawing have deposited the contribu- uploaded on the website of arrangements for her cre- He said the family told
over 10 per cent increase in lakh has been supplied to Allahabad in three and Disbursing Officers tion of EPF and ESI in respect the Labour Department up to mation on Sunday morn- them that a doctor at the
the supply of copper vessels months.❞ — Rajender, A COPPER MANUFACTURER (DDOs) making them “per- of every employee engaged 10th of every month for mon- ing. private hospital advised
has been witnessed this time sonally responsible” for the through that agency,” read a itoring by the department. Someone informed the them to take her to the civ-
as compared to the last fair. been supplied to Allahabad in much higher, but many deposit of the EPF/ESI in directive from the Principal Sources said the latest Chhachhrauli police that a il hospital, but she died on
“Past three months have three months,” said Rajender, artisans have shifted to oth- the accounts of the contrac- Secretary, Labour Depart- directions were offshoot of a girl committed suicide by the way.
gone well for all those associ- a copper manufacturer. er places, he said. tual employees. ment, to all heads of the number of complaints consuming some poisons “No complaint has been
ated with copper utensils He said there were “Rewari is the only city in “It has been directed by the departments, managing against the contractors and substance in Malikpur lodged. Statements of the
business. They worked round around 100 shops of brass, North India where maximum Chief Minister that the DDOs directors of the public sector outsourcing agencies not Khadar village. family members will be
the clock to meet the massive steel and copper utensils in varieties of copper vessels are concerned should be made undertakings and DCs. depositing the EPF and ESI The police were told that recorded under Section
demand for vessels in Ardh Rewari. These utensils are available. ‘Kumkuma’, personally responsible for In fact, after CM’s direc- contributions of the contrac- her family members were 174 of the CrPC. After
Kumbh. A huge consignment made at over 50 units being ‘shikari’, ‘rajshahi’ and compliance of the orders and tions, a meeting under the tual employees allegedly in making arrangements for postmortem, the body has
weighing 15 tonnes and carry- run by artisans. Earlier, the ‘ganga sagar’ varieties are in must ensure that prior to the Principal Secretary, Labour connivance with field staff, cremation without getting been handed over to the
ing items worth Rs 80 lakh has number of such units was demand,” said Rajender. release of payments to the Department, was held here including the DDOs. postmortem conducted kin,” he said.
Fake certificate: Ex-teacher booked Police alert in dera case Rohtak, January 13 in Rohtak, where he is cur-
Tribune News Service station on Saturday. Raj Rani deposited a photo- Haryana DGP BS Sandhu rently lodged.
The complainant said that copy of the certificate of has stated that the state “Paramilitary forces may
Yamunanagar, January 13 Raj Rani had joined the Occupational Therapy (OT) police was alert regarding also be called as and when
The police have booked a for- school as Punjabi teacher Punjabi, instead of deposit- the sentencing of Dera Sacha required,” the DGP said.
mer teacher of a government- on regular post on April 1, ing the original certificate. Sauda head Gurmeet Ram The state government was
aided private school at 1990. He said that the “She was asked to deposit Rahim by a Special CBI likely to file an appeal before
Saraswati Nagar in the district Haryana Government had the original certificate sev- Court in the case pertaining the Punjab and Haryana High
for allegedly getting the job of started the process of tak- eral times, but she failed to to the murder of journalist Court for holding the court’s
Punjabi teacher on the basis ing over regular staff of the do so,” he said. He said that Ram Chander Chhatrapati proceedings on January 17 on
of fake educational certificate. government-aided private she applied for voluntary slated for January 17. the premises of the Sunaria
On the complaint of schools in November 2013. retirement from the service Talking to reporters after prison complex, he main-
Devender Singh, president, He said that the school on January 1, 2017. “The chairing a meeting of the tained. The DGP reviewed the
managing committee, Janta ordered the regular teach- photocopy of her certificate local police authorities here security arrangements in and
High School, Saraswati ing and non-teaching staff was verified by the office of today, the DGP stated that around the jail and directed
Nagar, a case was registered to submit their original edu- the Director General, Sec- the quantum of punish- the officials concerned to
against Raj Rani under Sec- cational certificates with ondary Education, Haryana, ment for the dera head ensure the maintenance of
tions 420, 467, 468 and 471 of the management. and it was found to be fake,” could be announced on the law and order in view of the
the IPC at Chhappar police The complainant said that said Devender Singh. premises of the Sunaria jail sentencing. — TNS
06 HARYANA THE TRIBUNE
HP HOUSING AND URBAN DEVELOPMENT AUTHORITY,
NIGAM VIHAR, SHIMLA – 171002
“NOTICE”
CHANDIGARH | MONDAY | 14 JANUARY 2019
In continuation of this office advertisement published on
16.12.2018, 23.12.2018 & 6.1.2019, it is bring to the notice of General
Public that due to some administrative reason the last date for receipt
of application for the allotment of plots/flats in various Housing
New Delhi, January 13 ■ Play up TINA factor: there is no alternative to Modi New Delhi, January 13 New Delhi, January 13
As the Bharatiya Janata Par- ■ Project Congress, Opposition alliances as corrupt
The decision of the Congress With President Ramnath
ty wrapped up its two-day to go it alone in Uttar Pradesh Kovind giving his assent, the
■ Put the blame on Ram temple delay on the Congress
national convention yester- is a case of fait accompli for the government has re-promul-
day, three key takeaways are ONE TROUNCING US NOT BORN YET: UDDHAV Grand Old Party after the two gated the “Muslim Women
expected to form the saffron UP majors, the BSP and SP, (Protection of Rights on Mar-
plank for the 2019 General
Mumbai: Hitting out at BJP if an alliance happened, the announced an electoral riage) Ordinance, 2019”,
chief Amit Shah for his BJP will ensure victory for its
Election and be the centre- remarks that the saffron par- allies, but if it did not, the alliance, offering concession to which bans the practice of
piece of Prime Minister ty will thrash former party will thrash its the Congress on just two seats instant triple talaq, making it
Narendra Modi’s poll rally allies if a pre-poll former allies in the — Amethi and Rae Bareli. a penal offence, attracting a
blitzkrieg. alliance did not upcoming Lok Sabha It was not a case of the Con- jail term of three years.
First is playing up the materialise ahead polls. Thackeray, gress having been caught off A Bill to convert the earli-
‘there is no alternative’ or of the Lok Sabha whose party is an ally guard on Saturday. The er ordinance in this regard,
the TINA factor. In other polls, Shiv Sena of the ruling BJP at denouement to the negotia- issued in September 2018,
words, aggressively building chief Uddhav the Centre and in tions was known much earlier Senior Congress leader and party general secretary Ghulam Nabi Azad speaks as UP Congress was cleared by the Lok Sab-
the perception that there is Thackeray on Sun- Maharashtra, said, “I and no sooner had BSP chief chief Raj Babbar looks on at a press conference in Lucknow on Sunday. PTI ha in December but was
day said one who have heard words
no alternative to the “strong, Mayawati and SP leader pending in the Rajya Sab-
will trounce the like ‘patak denge’
decisive and corruption-free” Sena was yet to be born. In a from someone. One who will Akhilesh Yadav spelt out the Narasimha Rao entered into entered into an agreement The other view is that the ha. Since the Bill could not
Modi government. veiled warning to the Sena, trounce Shiv Sena is yet to contours of the pact, than Con- an electoral pact with the for the 2017 UP Assembly dynamics and chemistry of a get parliamentary
The choice is “between sta- Shah had recently said that be born.” PTI gress president Rahul Gandhi BSP, giving away the lion’s polls. That was her reason for General Election are differ- approval, a fresh ordinance
bility and instability, an hon- said he was not disappointed share of 300 seats of then keeping the Congress away. ent. It is certainly an uphill has been issued.
est and courageous leader ment”, that will be “corrupt”. hya title dispute, who wanted at being overlooked. undivided 425 UP Assembly The opinion within the task given that the last time Seeking to allay fears that
and a leaderless opportunis- Third, and perhaps the key the court to hold off hearing “They have taken a decision and going in as junior part- Congress appears divided. the Congress gave a decent the proposed law could be
tic alliance, a ‘mazboot’ gov- takeaway, is the subtle the case until after the 2019 in Uttar Pradesh, and we will ner contesting 125 seats, par- One view is that the move to account of itself was in the misused, the government
ernment and a ‘majboor’ attempt to shift the Ram tem- elections. have to take our own decision ty leaders and workers were contest all 80 Lok Sabha 2009 Lok Sabha polls, garner- has included certain safe-
government”, the BJP politi- ple narrative by pushing the Given that Ram Mandir is a too. The Congress has lots to aghast at the deal. seats should provide impetus ing 23 seats, a massive uptick guards, such as bail for the
cal resolution said. blame on the Congress. highly emotive issue for its offer to the people of Uttar Remembering the two- to the party’s move to revive from the nine it won in 2004. accused before trial and an
Second, projecting the Con- Leader after leader at the core Hindu voters, the BJP is Pradesh… it is on us to strength- decade-old pact, Mayawati its moribund organisation. Certainly, pact with the FIR only by the victim (wife)
gress party as “corrupt”, pre-election meeting told the satisfied with letting the en the Congress in Uttar reminded that the BSP did Ever since the 1996 decision, Congress in the BSP-SP tent and her relatives.
along with the other “dis- audience that it was Congress Sangh and its combatant Pradesh, and we will fight to our not benefit from it since the the downslide continues would have consolidated the The Ordinance is applica-
parate” groups trying to build leader Kapil Sibal, a senior affiliates — primarily the full capacity,” Gandhi said. Congress could not transfer with dejected “karyakartas” Opposition and the move by ble to the whole of India but
a coalition “with the sole aim advocate in the Supreme Vishwa Hindu Parishad — do Interestingly, way back in its votes to the BSP just as either remaining inactive or the Congress should be slic- is not extended to the state of
of ousting Modi and giving a Court who represents one of the hard talk while it awaits 1996 when the Congress the SP experienced when crossing over to other parties ing away some votes that Jammu and Kashmir which
weak, ‘majboor’ govern- the petitioners in the Ayod- the Supreme Court verdict. under then president PV Gandhi and Akhilesh Yadav in search of greener pastures. might go the BJP way. enjoys a special status.
TAX ADVICE
SC VASUDEVA
Filmmaker Hirani
draggedin#MeToo, General Category EWS quota Interest on NRE account not taxable
he denies charge
Mumbai, January 13
Filmmaker Rajkumar Hirani
has to pass basic structure test Q. A senior citizen is still working
and getting an annual salary of Rs
1,08,000 and is entitled to avail
on NRE account is not tax-
able. The income of an NRI,
which is earned in India is
Q. My son is an NRI and is doing a
job in Muscat since 2000. He is liv-
ing there with his family.
has been accused of sexual incapacity to compete with the Constitution as well. income tax exemption limit up to Rs required to be deposited in He does not have Aadhaar
assault by a woman who economically more privi- Ultimately, the Supreme 3.5 lakh. Is he eligible to add Non-Resident Ordinary card/PAN so far and has never filed
worked with him on his film leged sections of society. Also, Court will have to judge income from others sources up to account. Such an income an income tax return as an NRI. He
“Sanju”. Hirani has categori- the benefits of existing reser- whether breaching of the 50% Rs 2 lakh into his individual salary would be taxable in India. The purchased an LIC Market Plus poli-
cally denied the allegations. vations under clauses (4) and ceiling on reservations amount- income? Will income from other minimum taxable limit for cy for Rs 5 lakh from his NRE
His lawyer Anand Desai (5) of Article 15 and clause (4) ed to violation of basic structure sources be taxable? If so, how NRI is same as applicable to Account on August 3, 2010 for a
termed the allegations as of Article 16 are generally of the Constitution or not. much income from other sources an assessee who is not an NRI. term of 21 years. At present, its sur-
“false, mischievous, scan- OBITER DICTA unavailable to them. Further, imposing reserva- he can add to avail the exempt limit render value stands at Rs 9,28,000.
dalous, motivated and BY SATYA PRAKASH It’s for this reason that the tions on unaided institutions of Rs 3.5 lakh? Q. I had invested Rs 3,78,908 (sum He took another policy from HDFC
defamatory”. Act amends Articles 15 and 16 has also raised questions on 2. How much amount one can get taxable as “income from oth- assured Rs 3,80,000) in LIC one- Standard Insurance under the
T
In an article in HuffPost HE Constitution 103rd of the Constitution and adds the State passing on its bur- as help/gift from his er source”. However, such a time premium policy in 12/2012 HDFC Children Benefits Plan for Rs
India, the woman, who calls Amendment Act, 2019, an additional clause i.e. clause den on the private sector. It’s relatives/blood-related persons liv- receipt, if received from the and was paid a maturity amount of 5 lakh on March 10, 2004 for 15
herself as “an assistant”, providing for up to 10% 6 to each of the two Articles. being seen as an arbitrary ing abroad during a year? Is following relatives, is not tax- Rs 5,11,400 in 12/2018 and TDS of years by paying Rs 33,115 as annu-
alleged that Hirani sexually reservation to economically But EWS quota law is likely to move as it goes against amount received from relatives liv- able. 1% (Rs 5,116 ) was deducted from al premium.
abused her more than once weaker sections (EWS) of hit legal hurdles for more Supreme Court’s Constitu- ing aboard taxable or not? If so, “Relative” means: this amount. In form 26AS, the He is having an NRE account with
between March and Septem- General Category in educa- than one reason. An NGO has tion Bench verdicts in TMA how much tax would be applicable? (i) in case of an individual – whole maturity amount has been SBI and NRE account inclusive of
ber 2018. She detailed her tion and public employment already filed a petition in the Pai Foundation (2002) and PA 3. Is it compulsory that amount (a) spouse of the individual; shown as amount paid/credited. At NRO account with ICICI Bank .
allegations in an email dated over and above the existing Supreme Court challenging Inamdar (2005), which said shown in the savings account of an (b) brother or sister of the the time of investing, the LIC agent Please advise how his tax liabili-
November 3, 2018, to Hirani’s quota for SCs, STs and OBCs the validity of the Constitu- the State’s reservation policy individual during 2017-18 account- individual; didn’t tell me that the maturity ties will be assessed. LIC and
long-time collaborator and has triggered a fresh debate tion 103rd Amendment Act, cannot be imposed on unaid- ing year be the same in the return (c) brother or sister of the amount is taxable. My queries are HDFC officials have different opin-
“Sanju” co-producer Vidhu on the divisive issue. 2019, on the grounds that it ed educational institutions. while filing income tax return for spouse of the individual; as under: ions about the tax deductions.
Vinod Chopra. Passed by Parliament in violates the basic structure of There have been demands 2018-19 (assessment year)? (d) brother or sister of either 1. Is my LIC maturity amount They seem to be not well conver-
The woman said on April 9, two just days and assented to the Constitution. from various quarters, 4. If a person living abroad trans- of the parents of the individ- taxable? sant with rules in force.
2018, the director first passed by the President on Saturday, The new quota law exceeds including some political lead- fers amount in his savings account ual; 2. In case taxable, what amount is — Yogesh Sehdev
a sexually suggestive remark it takes total reservation to the 50% ceiling fixed by the ers, that reservation should or an NRI account, how would he (e) any lineal ascendant or to be considered as income from A. Interest earned by your
and later sexually assaulted 59%, much beyond the 50% Supreme Court in Indra be extended to private sector fill up his income tax return and on descendant of the individual; other sources? son on NRE account is not
her at his home office. “My ceiling fixed by the Supreme Shawney case. There is spec- as very few jobs are available which form? Would that income be (f) any lineal ascendant or 3. Whereas LIC has deducted 1% of taxable. However, interest
mind, body and heart were Court in the Indra Shawney ulation regarding placing the in the government sector. It taxable or not if it exceeds the lim- descendant of the spouse of maturity amount as income tax, I, earned on NRO account
grossly violated that night case (1992), popularly known Constitution 103rd Amend- appears the government is it of exemption limit? the individual; who fall in the slab of 30% tax with ICICI Bank would be
and for the next 6 months,” as Mandal Case. It also ment Act in the Ninth Sched- testing waters. If the amend- — Apma (g) spouse of the person bracket, will have to cough up 29% taxable if the amount of
the email read, which was extends reservation to pri- ule of the Constitution to ment, which provides for A.Your queries are replied referred to in terms (b) to (f); more as tax. Will it be on maturity such interest exceeds Rs
also marked to Chopra’s vate aided and unaided edu- shield it from possible judicial quota in private aided and hereunder: and amount or on maturity amount 2,50,000 being the limit up to
wife, film critic Anupama, cational institutions. scrutiny. But the top court has unaided educational institu- (a) A senior citizen who is less (ii) In case of a Hindu Undi- minus the amount I invested? which income tax is not
who is a director at Vinod Various social groups (not already ruled in IR Coelho's tions, is upheld by the than 80 years of age is not vided Family, any member Please clarify. payable by an assessee who
Chopra Films Pvt Ltd, “San- covered under the existing case in 2007 that there is no Supreme Court, the demand required to pay tax up to an thereof. — OP Kapoor is below the age of 60 years.
ju” scriptwriter Abhijat Joshi quota benefits) in Gujarat, blanket immunity from judi- to extend quota in private income of Rs 3,00,000 for (c) The provisions as stated A. Your queries are replied The amount received on the
and filmmaker Shelly Rajasthan, Maharashtra, cial review available to a law sector jobs will gain further assessment year 2019-20. above are equally applicable hereunder: expiry of the maturity peri-
Chopra, Vidhu Vinod’s sister. Haryana and certain other placed in the Ninth Schedule. momentum. Your present income being to an amount received from (a) According to my opinion, od shall not be taxable in
The complainant later told parts of the country have Placing of a law in the Ninth Caste-based quota has been Rs 1,08,000 and another sum outside India. It is necessary the entire amount received respect of LIC Master Poli-
HuffPost India that she was been demanding reservation, Schedule after the IR Coelho very divisive and runs count- of Rs 1,92,000 earned by you that the amount shown in by you from LIC should not cy in case the premium paid
“intimidated by Hirani “and often by resorting to violent verdict only changes the lev- er to the objective of achiev- as income from other savings account of an indi- be taxable but the amount by him does not exceed 20%
that said she maintained a agitation. But coming barely el of judicial scrutiny as a ing a casteless society as sources. vidual as on 31.3.2018 should received by you in excess of of the capital sum assured.
facade of normalcy as she few months before the Lok two-fold test would be envisaged by Dr BR Ambed- (b) Currently, the provisions be same while filing the the sum paid to the LIC The present surrender val-
needed to hold on to her job Sabha elections, the political applied to test its validity. kar. For the first time, caste of Gift Tax Act, 1958, are not return for assessment year should be taxable. ue is not taxable as the poli-
as her father was ill. “I had no motive behind the move is First, it would be examined will not be a criterion for quo- applicable. However, Section 2018-19. (b) As stated in (a) above, the cy is still being continued.
choice but to be polite to him. bound to be questioned. whether the law violates a ta in India under this law. The 56 of the Act provides that (d) NRI has an option to excess amount of Rs 1,32,292 The policy with HDFC
It was unbearable but the rea- The EWS among the Gen- provision in Part-III of the Supreme Court may or may any sum of money received deposit in NRE account should be taxable. Standard Insurance having
son I endured it all, until I eral Category have largely Constitution (Fundamental not uphold the new quota law. by an assessee during the amounts sent to India in for- (c) The amount of Rs been taken before March
couldn’t, was because I did- remained excluded from Rights) or not. If, yes, then it But the fact is that scope for financial year in excess of Rs eign exchange. Such an 1,32,492 would be taxable as 31, 2012 would also
n’t want my job to be taken higher educational institu- would be further examined if merit in the system is getting 50,000 from any person account can be a savings income from other sources be covered in the same cat-
away from me, and work to tions and public employment the violation also amounts to restricted in India is some- except relatives and other account or fixed deposit and shall be includible in egory as the master policy
be questioned. Ever.” — PTI on account of their financial violation of basic structure of thing to worry about. specified persons shall be account. The interest earned your total income. taken from LIC.
08 OPINION THE TRIBUNE
CHANDIGARH | MONDAY | 14 JANUARY 2019
A
good level of development. They are
QUARTER of a century is a long time to stay estranged. And MK BHADRAKUMAR
suggesting creating a joint station.’
any rapprochement without a closure, as is the case with the SP FORMER AMBASSADOR Rogozin even floated the idea of a
and BSP in UP, speaks of more than a hint of desperation. Till ‘BRICS station’. Of course, Russia is
U
the run-up to the 2017 Assembly polls, Mayawati was in no mood to S space agency NASA has technologically capable of building a
‘forgive or forget’ the 1993 VIP Guest House incident in Lucknow. abruptly called off a planned lone Russian lunar station. But then,
But the BSP has been locked out of the power centre in UP for six visit to the US in February as the director of the Institute of
years and its vote share has steadily declined. The political banish- by the head of the Russian Space Policy in Moscow, Ivan M Moi-
ment from Lucknow will last another three years. Such a long period state space corporation, Roscosmos seyev, told the New York Times
on the bench precludes any division of spoils between Mayawati and Dmitry Rogozin. NASA made the recently, ‘The technical capability
Akhilesh: a role in Delhi for one and another for Lucknow. announcement on January 4 following exists, but the finances don’t.’
The dumping of the Congress makes for an interesting reading of criticism by the US media and law- MISSION SPACE: Russia can build a lone lunar station, but funds are a challenge. Quite obviously, considering that
tea leaves. Past experience has shown, according to Mayawati, that makers who demanded cancellation of space efforts are inextricably connect-
the visit. The snub to Moscow presages ed to military plans, Russia needs to
the Congress cannot transfer its votes. Nothing can be said if the
sudden death of the historic Russian-
The waning of NASA-Roscosmos synergy can be to India’s take a leap of faith to form an alliance
alliance will finally be a big tent that will accommodate the entire sec-
ular line-up or the non-Congress part. But the outline of the bi-party
American collaboration in exploring advantage. New Delhi should seize the opportunity. with China. On the one hand, the scien-
the ‘last frontier’ for mankind. It tific space-related endeavours have
pact indicates their game plan of preventing the Congress from becomes an inflection point. immense commercial potentials, while
becoming the ringmaster by aggregating enough seats from various Rogozin is a close political associate particular, following the cancellation of tect space assets (satellites, etc.) with on the other, they signify the ultimate
states to be the largest party. The Congress is welcome to contest all of President Vladimir Putin. He has the US Space Shuttle Program in 2011, space-based weapons. Suffice to say, ‘eye in the sky’ through a combination
seats where it is BJP’s principal opponent, but the SP-BSP alliance been subjected to the Western sanc- the US began relying on Russia’s the scope for sharing sensitive tech- of satellites and unmanned aerial
will aim at maximising its pickings from UP to be in a position for bet- tions over Moscow’s annexation of Soyuz capsules for transport to the ISS. nology or capabilities in space part- reconnaissance vehicles that would
ter bargaining if secular parties manage to best the BJP in 2019. Ukraine’s Crimean Peninsula in Russia receives an average of $81 mil- nerships has dramatically shrunk give unmatched insight into positions
The Congress’ exclusion also buries the talk of a nationwide 2014. US Senator Jeanne Shaheen, lion per seat on the Soyuz. In a joint due to the growing hostility between of enemies (as well as allies). They will
maha-gathbandhan. The electoral canvas may now be dotted by who is a leading critic of Russia’s statement in 2017, the two countries the US and Russia. phenomenally improve military logis-
state-level alliances against the BJP with the leftouts in the secular alleged meddling in the 2016 US pres- even projected the idea of collaborating Secondly, a private sector space tics, facilitate ‘orbital strikes’ at enemy
camp providing a rump alternative. On paper, simple arithmetic idential election, threatened that the on deep space exploration, including industry has appeared in the US and it targets as well as open up new lucrative
Congress will be ‘forced to act’ the construction of the Lunar Orbital has spawned commercial interests. trade and travel routes.
gives three-fourths of the 80 UP Lok Sabha seats to the SP-BSP. But
unless NASA withdrew the invitation Platform-Gateway, a research-focused The development of advanced tech- India is far better placed than China
the postulation sidesteps the likelihood of more cards up the BJP’s
to Rogozin. Shaheen called Rogozin space station orbiting the moon. nologies by private companies means can ever be to align with Russia’s
sleeve: quota within the SC\OBC quota and, of course, the Ram tem- ‘one of the leading architects of the (Rogozin’s visit aimed at fleshing out NASA has new options to choose from space programme, as there are no con-
ple case. What remains to be seen is whether the desperation of the Kremlin’s campaign of aggression the tantalising idea.) Both countries and to reduce the dependence on Rus- tradictions in the relations between
vanquished can match the creativity of the saffron corner. towards its neighbours’ and said the saw clear benefits, given the high price sia. In fact, NASA is already in a posi- the two countries. China is a competi-
invitation ‘undercuts our message tag for solo space exploration. tion to use Boeing and SpaceX cap- tor for Russia — as much as for the US
and undermines the US’ core nation- However, times have changed. Rus- sules for human spaceflight beginning — in space. Commenting on the
al security objectives’. sia and the US are flaunting today in 2020 and even has the option to recent landing of a Chinese scientific
C
countries have had a long history of domain of warfare. If the 2018 US tary (‘Space Force’), the dominant quarters in Washington, as in
OMETH the elections, cometh the revised pay scales. With working together in space ever since National Defense Strategy charac- aerospace companies in the US — Moscow… is likely to reflect trepida-
barely three months to go for the Lok Sabha polls, the cash- the joint Apollo-Soyuz mission in 1975, terised ‘space and cyberspace as war- Boeing, Lockheed Martin, Northrop tion.’ It cannot be otherwise in New
strapped Punjab Government has decided to bite the bullet and more so, in the past two decades. fighting domains’, Russia’s 2010 mil- Grumman, Raytheon and BAE Sys- Delhi also. All factors taken into con-
and finally implement the recommendations of the Sixth Pay Com- Within the ambit of cooperation, the itary doctrine explicitly stated that tems — are eyeing the new frontier. sideration, therefore, a tapering off in
mission. This is a last-ditch attempt to win over lakhs of disgruntled two countries have shared training, ensuring superiority in space would Russia’s preference has always the NASA-Roscosmos cooperation,
government employees, who have been holding protests in recent communications, operational capabili- be a ‘decisive factor’ in achieving its been to press on with a space pro- which is on cards in a near-term sce-
months in support of their demands, primarily a salary hike and ties and expenses in support of the strategic goals. In this tense security gramme entwined with the US’s. But nario, can be to India’s advantage.
payment of dearness allowance arrears. International Space Station (ISS). In environment, the need arises to pro- in a scenario where NASA turns its Delhi should seize the opportunity.
The Commission was set up in February 2016 when the Akali-
BJP alliance was in charge, but things moved at a snail’s pace,
H
and a half, receiving hundreds of representations from employees’ OW much?’ I asked a clerk at Perhaps, he wanted me to vanish, but in the hierarchy — and the elderly he made a quick decision to douse it
unions. It has been a tightrope walk for him as the government the post office. Rupees 41, he I was not in a mood to oblige. Anoth- man outside the counter an aam aad- with exceptional sweetness, dipping
hardly has any financial elbow room. replied. I gave him Rs 40 and a er five minutes passed. I asked him mi. I did not like this evaluation of his hand in the cashbox. He fished
Accounting for about half of its total earnings, the state’s annual Rs-5 coin. He looked at the coin and for the balance. Again he mumbled, myself. It was unacceptable to me. out a Rs-5 coin and gave it to me.
salary and pension bill is a major drain on the exchequer. Punjab’s frowned, ‘Give me change,’ he said. ‘ Let change come. I will give you Raising my tone, I said, ‘Char rupay Sheepishly, he said, ‘Ok, Sir, you take
government employees, particularly those who have spent several ‘This is change,’ I retorted. ‘You will your Rs 4. Main kahin bhaga thode ja ke liye kitni wait karni chahiye?’ ‘A it and go.’ I said the situation had not
years in service, are relatively well paid compared to their counter- have to wait for the change,’ he replied. raha hoon.’ His tone was weak this few minutes more, maybe,’ he said. I changed. ‘I don’t have a rupee coin.’
parts in other states, but the picture is far from rosy for the fresh It was around 3 pm. I had gone to time as I had seen him accept small told him angrily that he reminded me He asked me not to bother.
speed-post a letter. Though the queue coins over 15 minutes. I told him that of bus conductors of the bad old days I came back with my Rs 4 clinking
recruits. The latter find themselves in a ‘take it or leave it’ situation.
was not long, the young clerk was though he was not running away, I who would never return change to in my pocket. Besides, I had a rupee
The ruling party needs to do a lot to make sarkari naukri alluring for
taking an inordinate time in dispos- was a busy man and had other things helpless passengers on one pretext or interest too! I had won a small but
these young employees. The protracted unrest among government ing of the customers. It had taken me to do. ‘Please wait,’ he insisted. the other. ‘Even conductors have righteous battle against an official
teachers, who are seeking regularisation of services at decent over half an hour to reach the book- Another five minutes passed. The stopped doing this. Check your cash- who had the potential to misappropri-
salaries, shows that the powers that be have made a mess of things. ing window. And now the wait, for Rs wait was becoming painful. I was box. There is enough change there.’ ate public money at some stage, when
Punjab also has plenty of catching up to do with neighbour Haryana, 4! I took a stealthy look into the cash- tired and felt weak-kneed. My temper The clerk had not expected this. He he would be in a senior position. It
which had taken the lead last year in implementing recommenda- box and sighted a few glistening was rising, but I realised that the glared at me. I glared back. The peo- wasn’t about Rs 4; it was about the
tions of the Seventh Pay Commission. coins. I understood. young man behind the counter was ple around backed me. They had been dignity of the common man and the
‘I will wait,’ I said, and stood my taking me either to be a fool or a weak watching the whole drama and knew propriety on the part of public ser-
ground. The clerk asked me to stand man who could be browbeaten simply who was at fault. vants while discharging their duties.
❝ ❞
thought for the day letters to the editor
The Universe is under no obligation to make sense
Better late than never An enlightened being Air Force to achieve integrated com- process by middlemen, clinics and
to you. — Neil deGrasse Tyson The verdict in a 1984 riot case, convict- The article ‘Vivekananda’s practical mand in sync with modern times. Vio- doctors, and the use of women as ‘sell-
ing Sajjan Kumar, is a precedent that Vedanta’ (Jan 12) precisely explains lence in Kashmir is declining and his ers’ of babies is certainly acknowl-
must be followed in other pending the great message he conveyed to the message to terrorists to join the edged by the surrogacy Bill. But a
criminal cases for decades. Otherwise, nation and the whole humanity. The national mainstream should have a complete ban is not what is required. It
on this day...100 years ago those cases are likely to be thrown Swami said, ‘There cannot be any positive effect. Kashmiri separatists is not feasible to ban commercial sur-
away on the ground of delays. The lat- antagonism amongst the religions of should also stop toeing the line of the rogacy altogether, when it is worth $2.3
est example is the second conviction the world. I wish there were as many ISI and work for the prosperity of the billion. The ban would lead to more
against Dera Sacha Sauda chief religions in the world as people, shed- people of Kashmir. violations and misuse, and will also
Gurmeet Ram Rahim and his three ding more light on spirituality.’ When SUBHASH VAID, NEW DELHI lead to the exploitation of surrogates.
aides, who have been pronounced he talked of being fearless and strong, DIVYA SINGLA, PATIALA
lahore,tuesday, january 14, 1919
guilty by the special CBI court in the he meant only love not hate. Love is
Chhatrapati murder case. Now a vic- strength. He identified every human ‘Poor’ taxpayer
The Civil Service Opposition. tim may be hopeful that justice may being as an embodiment of divine Ambedkar had proposed reservation Principals on probe panels
WE have in our leading article referred to the organised opposition which certain be delivered, even though there may presence. I salute him with the same for only 10 years, for the poor of socie- Refer to ‘PSEB exam centres outside
members of the Indian Civil Service in the Madras Presidency are endeavouring be delay in its delivery. reverence as he felt for Ramakrishna ty. After decades, our politicians have schools again, in 3-km radius’ (Jan
to offer to the Montagu-Chelmsford scheme of Reforms. In the interests of that SHADI LAL, BY MAIL Paramhans when he said, ‘Whatever I failed to end reservation. Now, the 12); I am a retired lecturer from the
Service itself, on the cause of good government in India, and of that mutual have said and written belongs to my issue has become a strong tool to Punjab education department. It is
understanding between Englishmen and Indians on which so much depends, Master and the mistakes that have attract voters. The recent quota for said that only seniormost principals
we appeal to the Government to nip this movement in the bud, if it has not Faith in judiciary occurred in doing so belong to me.’ upper caste people was passed by both have been included in probe panels. I
outgrown that stage. Anybody can see that it can only do harm. That it cannot Apropos ‘Comeuppance for dera RUP SINGH, BY MAIL Houses. No political party dared to contest this claim. In most districts
and ought not to succeed goes without saying. It is intolerable that a body of men, chief’ (Jan 12), the verdict should refuse it, because they know the value principals promoted in 2014 and 2016
who are paid out of Indian revenue for the single purpose of administering the bring respite to the family of the vic- of upper caste vote. People who pay have been adjusted on the panels
affairs of India, according to the law and the constitution in vogue for the time tims. The determination with which Task cut out for Chief taxes will get reservation in govern- whereas those promoted in 2009 and
being, should claim the right to determine what that law and constitution should they pursued the legal battle has The editorial ‘Sorting wheat from ment jobs and educational institu- 2010 have been ignored. This puts a
be, and should make it a grievance when that right was denied to them. borne fruit. The message is clear: no chaff’ (Jan 12) has good advice for the tions. But this is not a permanent solu- question mark on the functioning of
miscreant can go scot-free, despite Army Chief. The matters of interna- tion. As a patriot and an active citizen the panels. Also, another report says
Disapproval of the Scheme. having enormous wealth and strong tional relations should be left to politi- of this nation, I want only a single that there will be no self-exam centre,
THAT the scheme is not approved by some members of the Service is, of course, political connections. The verdict cians and diplomats. Let them chart reservation system implemented. but in many parts of the state, stu-
neither new nor surprising. No one who has exercised ruling authority can like to will go a long way in reinforcing the way forward for matters in KARAM SINGH THAKUR, MANDI dents of school ‘A’ go for exam to
be told that his true business is not to rule but to serve. Our objection is to the people’s faith in the judicial Afghanistan. Our jawans are deputed school ‘B’ and vice versa, and in this
members of the Service giving organised expression to their disapproval of the process, despite it being long and for peace missions only under the UN process, they help one another and
scheme and, indeed, to their expressing any opinion with regard to it at all, unless cumbersome. Hopefully, more peo- flag. The Chief has huge responsibili- Surrogacy Bill flout the bar of 3-km distance. To
they were officially called upon to do so. This, however, is precisely what the ple will be emboldened to fight ty on two fronts and to deal with inter- Refer to ‘Surrogates victims of abuse, curb copying, there should be no
Madras Association does. “We do not intend now,” it says “to criticise the proposals injustice fearlessly and doggedly. nal security. Close coordination must exploitation’ (Jan 12); commercialisa- vice-versa centres.
regarded merely as a scheme for administering British India, but as a reference to VIMAL SETHI, KAPURTHALA be forged among the Army, Navy and tion of motherhood and misuse of the GURBACHAN SINGH, BY MAIL
the subject in the British Press suggests that the I.C.S. as a whole approves and
welcomes the scheme, we think it desirable to say that it is not so.” Letters to the Editor, typed in double space, should not exceed the 200-word limit. These should be cogently written and can be sent by e-mail to: [email protected]
THE TRIBUNE
CHANDIGARH | MONDAY | 14 JANUARY 2019 OPED 09
R
AMAKANT Achrekar, a cricket none of these honours. Lok Sabha, Chief Justice of the Supreme
coach known for having nur- However, nothing can be as glaring as Court, Chief Ministers and Bharat Ratna
tured Sachin Tendulkar and the difference in the treatment meted awardees. The Honour Guard at such
Vinod Kambli, passed away out to two giants of the Armed Forces. funerals should be drawn from the state
recently. However, even before the In September 2017, Marshal of the police or the Central Armed Police
embers had cooled, a controversy flared Indian Air Force Arjan Singh was cre- Forces, which would fire three volleys by
up about a ‘state funeral’ not being mated in Delhi with full state honours. seven riflemen. Bodies would be draped
accorded to him. The Maharashtra Gov- The Tricolour was flown at half mast in the Tricolour, but there would be no
ernment had to go into overdrive and and both the President and the Prime HOMAGE: State funerals with full military honours, including the 17-gun salute, should be accorded to Field Marshals/Marshals lowering of the National Flag.
apologise for the ‘omission’. Minister paid tributes at his residence, of the Air Force/Admirals of the Seas and all Param Vir Chakra/Ashok Chakra awardees. State funerals with full military hon-
Such controversies have erupted where the body lay in state. The funer- ours, including the 17-gun salute,
several times. In 2017, the Karnataka al was attended by top political leaders, constitutional and central political reserved only for the President, Prime should be accorded to Field Mar-
Government was slammed for accord- including Manmohan Singh and LK
Whims and fancies of leadership, including the Defence Minister and former Presidents, while shals/Marshals of the Air Force/Admi-
ing a state funeral with a 21-gun salute Advani, the Raksha Mantri (Defence people in power, vote-bank Minister, found time to attend his cre- Governors were added to the list for rals of the Seas and all Param Vir
to Gauri Lankesh, a journalist known Minister) and the three Service Chiefs. mation. Nor did the Governor or Chief ‘state funerals’. However, this came Chakra/Ashok Chakra awardees.
for her support to Naxals and views on A 17-gun salute, a fly-past by three pressures and a loose Minister of Tamil Nadu. The sole rep- with a clause that in the case of other All other prominent citizens of great
right-wing Hindu extremism. The
administration claimed that the gun
Sukhoi fighters and helicopters carry-
ing the IAF colours were part of the
‘discretionary’ clause resentative of the government was the
Minister of State for Defence. Even the
dignitaries, the Centre could issue spe-
cial instructions or order a state funeral.
stature could be accorded a ‘ceremonial
funeral’ at the discretion of the Central
salute was given as “a mark of respect honours accorded to the ‘Air Warrior’. can imbalance Air Force and Navy Chiefs did not Thus, over the years, rules have been or state governments. A ceremonial
for her selfless service and not for ide- Compare this with the shocking attend the funeral and instead chose to relaxed or overlooked on several occa- funeral should also be authorised for for-
ological reasons”. Another recent case treatment meted out to India’s most protocol-based events, send two-star-ranked officers. sions to accommodate some personali- mer Union Cabinet ministers or equiva-
was that of Sridevi, who was given full
state honours at her funeral under the
iconic soldier, Field Marshal SHFJ
Manekshaw, the Chief of the Indian
resulting in controversies All these cases exemplify how poli-
tics, whims and fancies of people in
ties. There is, therefore, a need to review
existing instructions and streamline and
lent former government dignitaries.
Such a funeral would basically entail
Chief Minister’s discretionary powers Army which liberated Bangladesh in and debates. While honours power, vote-bank pressures and a standardise these to ensure uniformity logistical and security arrangements
for being an “eminent personality who 1971 and captured over 90,000 Pak- loose ‘discretionary’ clause can and transparency across the country. by the government, provision of a
has done public service”. A third case istani prisoners of war. Sam passed accorded to well-known imbalance such protocol-based Some recommendations are: police escort and attendance by appro-
is that of Sarabjit Singh, convicted of
spying and subsequently killed in a
away in June 2008 at Wellington, Tamil
Nadu. However, for reasons unknown,
personalities have generally events, resulting in avoidable contro-
versies and debates. While honours
‘National mourning’ and a ‘national
funeral’ should be authorised only for
priate elected/government dignitaries.
Bodies of such departed citizens would
Pakistani jail in 2013, for whom the the Indian Government appeared to not been objected accorded to well-known personalities the President, Vice President, Prime neither be draped in the Tricolour nor
Punjab Government ordered three- deliberately downplay the state hon- have generally not been objected to, Minister and former Presidents. would rifle volleys be fired.
day mourning and a state funeral. ours that this great soldier so richly to, what has vexed people the two main issues that have, howev- These dignitaries would be entitled to National mourning with flags low-
It is these powers of discretion that give
rise to controversies and hype among the
deserved. In any other country, such a
funeral would have been attended by
is the draping of Tricolour er, vexed the people are the draping of
the Tricolour over the bodies of some
most of the existing protocols, includ-
ing a 21-gun salute by the military and
ered to half mast throughout the
country should be proclaimed if the
public. Over the past several years, state the highest officials of the nation. over bodies of some of of the departed and the rendering of a recommended four-day period of nation goes through any major
funerals under the discretionary powers However, here no national mourning gun salutes to them. mourning during which the Tricolour calamity or natural disaster resulting
have been given to several other personal- was declared and not one among our the departed. A ‘state mourning’ was initially would fly at half mast. Based on a in large-scale loss of lives.
■ Magh Parvishte
24
1
Sunny Partly Cloudy Cloudy
CITY MAX
Rainy
MIN
Foggy
10 Brilliant red (7)
■ Hijari 1440 Chandigarh 19 06
11 Excessively affectionate (6)
12 Ferocious (6) 3 7 4 ■ Shukla Paksh Tithi 8, up to 12.38 am
New Delhi
PUNJAB
21 08
15 Caller (7) ■ Sidh Yoga up to 6.52 am
Amritsar 17 05
17 Escape grasp of (5)
19 Result in failure (4,2,7) 8 9 6 1 7 2 ■ Revti Nakshatra 12.53 am
Snow spell ends in Kashmir Two ultras held in Shopian pain to thousands of people.
Worse, what they have done
is to create a situation where
This makes his political
plans selective, ignoring the
other side completely.
Tribune News Service Air, road traffic resumes Our Correspondent Joint operation A case has been registered militancy, conferred with a Second, he made observa-
at the Shopian police station. dignified term of resistance, tions about the instances
The surface connectivity as well as air traffic, which was disrupt- The militants were arrested
Srinagar, January 13 Anantnag, January 13 One pistol and 14 live car- made the country respond that have plagued the coun-
ed by the snowfall in the state, was restored and vehicles strand- from a ‘naka’ put up by a joint
The sun shone over most The Delhi Police on Sunday team of the Delhi Police and tridges were recovered from with equally ruthless count- try in recent years, high-
parts of the Valley for the ed along the Jammu-Srinagar highway were allowed to move claimed to have arrested two the possession of the duo. er-terrorism operations. The lighting the Muslim victimi-
J&K Police at Narwaw village
first time in recent weeks on militants, including a juve- of Shopian. The arrested mili- The Delhi Police said there familiarity of the armed sation. That is a squinted
Sunday as the latest spell of The latest snowfall ended Srinagar national highway nile, from a ‘naka’ in Shopi- tants were in touch with were specific inputs regard- forces to the soil of Kashmir view. India has that tolerance
snowfall, which continued by Saturday evening at most were allowed to move. an district. The ‘naka’ Naveed Babu, a policeman- ing a Hizbul Mujahideen has brought in many and it gives the freedom of
intermittently for three places in the Valley and was In Kashmir, where the res- (checkpoint) had been put turned-Hizb commander. module, which visited the changes on the landscape, speech and expression that
days, ended in the region. the fifth such spell since the idents are struggling with up by a joint team of the Del- . NCR for procurement of and today all Kashmiris are he said was being sup-
The rare sunny day came snowfall in November’s first freezing climatic conditions, hi Police and J&K Police. atullah Bukhari, a resident of sophisticated small weapons. living a split life — their pressed in the country.
as a respite in the region week, which had marked the temperatures overnight In a press release, the Delhi Nowpora in Shopian district. “A special team was sent to love for what they believe In 2010, Faesal made youth
which has been battling one the early arrival of winter. remained comparatively Police said two militants were The second militant has only Jammu and Kashmir. The is “a pious revolution” and in Kashmir compete and
of its severe winters in the The surface connectivity warm. The minimum tem- arrested from Narwaw village been identified as a “juve- information was shared desperate search for a excel. But now, he has creat-
past decade with back-to- as well as air traffic, which perature in Srinagar, the of Shopian. However, the nile in conflict with law”. with the counterparts in peaceful life for themselves ed doubt in their minds that
back snowfalls causing traf- was disrupted by the snow- state’s summer capital, press release did not men- “The militants were in Shopian following which a and their children. if politics is the final destina-
fic disruptions and triggering fall in the region, was dropped to a low of -0.4°C, tion the date of the arrest. touch with Naveed Babu, a trap was laid and the two The would-be politician in tion, why route it through the
threats of avalanches in restored and the vehicles making it the warmest One of the arrested persons policeman-turned-Hizb com- militants were arrested,” Faesal has looked at one side of IAS and leave your own
remote mountainous areas. stranded along the Jammu- night of the month. has been identified as Kifay- mander,” the statement read. the statement said. the problem, thus making it people disillusioned.
Dharamsala, January 13
at the Dharamsala complex,
medical and engineering
❝ Himachal already has
six medical colleges that
mit a specified number of
courses that could be started
leges could be set up by the
CUHP in later stages.
PATNA, JANUARY 13
At least two persons were
critical as she was admitted to
the ICU of the hospital.
aged, killing driver of the
truck at the spot.
Central University colleges would come up at are in various stages of in the initial phase, he said. The CUHP was estab- killed and about three dozen The bus was on way to Confirming two deaths in
Himachal Pradesh (CUHP) Dehra. Vice-Chancellor, development. It won’t be Agnihotri said the state lished in 2010. On the rec- injured after an Uttarak- Uttarakhand via Gaya dis- the fatal road accident,
has dropped the proposal CUHP, Kuldeep Agnihotri wise to start another had enough engineering ommendations of the then hand-bound tourist bus trict as it was returning from Muzaffarpur district Magis-
for setting up medical and said he had written to the medical college at this colleges in both govern- government, led by PK collided with a truck on the Janakpur Dham of Nepal trate Mohammad Suhail
engineering colleges. Centre in this regard. He said stage. The state has ment and private sectors. In Dhumal, a committee was NH-77 near the Runnisaid- where Uttarakhand tourists said: “The injured were taken
The university had pro- initially, the university had enough engineering the initial phase, the CUHP set up for the selection of pur locality of Sitamarhi dis- had gone to offer prayers to the SKMCH where they
posed to set up these col- no intention to start medical colleges in both would now only concentrate sites for the university in trict of Bihar on Sunday. before they met with a fatal were getting proper treat-
leges in its vision docu- and engineering colleges. government and on sciences, humanities Kangra. It was on the basis The injured were rushed to accident in Sitamarhi’s Run- ment. Except a few, the condi-
ment. As per initial In the initial “vision docu- private sectors. The and other professional of the recommendation that Sri Krishna Medical College nisaidpur police station area. tion of other tourists was said
proposal of the CUHP, it was ment”, the university had focus will be on other courses, he said. the then Centre decided to and Hospital (SKMCH) in Since collision of bus and to be out of danger”. One
planned that while human-
ities and basic sciences pro-
proposed to start 130 courses.
The ministry had now asked
courses now. ❞
Kuldeep Agnihotri, VC, CUHP
The Vice-Chancellor, how-
ever, made it clear that med-
have two complexes — at
Dehra and Dharamsala.
Muzaffarpur. The condition
of one patient is said to be
truck was head-on, both bus
and truck were badly dam-
woman who died was identi-
fied as Rukmini Devi. — TNS
THE TRIBUNE
CHANDIGARH | MONDAY | 14 JANUARY 2019 NATION 11
CLASSIFIEDS
COURT NOTICES
(U/O 5 Rule 20 CPC)
In the Court of
COURT NOTICES
In the Court of
COURT NOTICES
(U/O 5 Rule 20 CPC)
In the Court of
COURT NOTICES
(U/o 5 Rule 20 CPC)
‘Honey-trapped’,
jawan shares
Ms Priya Sood Ms Mamta Kakkar, In the Court of
Shatin Goyal Sh. Manav
SITUATION VACANT PUBLIC NOTICES Additional District & Sessions Judge,
Hoshiarpur.
PCS, Judicial Magistrate Addl. District and Additional Civil Judge,
1st Class, Batala Sessions Judge-XI, (Senior Division),
Requires boys/girls spoken fluent I, Naresh Kumar S/o Dev Raj Ranjit Singh s/o Dalip Singh r/o
English for famous company Mohali. R/o Bathinda, have changed Village Khablan, Tehsil and District CNR No. Jalandhar. Hoshiarpur.
HOW
Eco-friendly coating of fruits and vegetables can
prolong their shelf life and help in minimising
post-harvest losses, besides increasing
WAX
export opportunities, says BVC Mahajan
WORKS
A
FTER China, India is the fungicidal residue, and proliferation of FSSAI’S 10 RULES shield and provides protection against tion and about 100 such automatic lines
largest producer of fruits resistance in the pathogen populations. pathogens and minor mechanical have been installed by progressive
and vegetables in the world.
The country produced about
Nowadays, consumers are highly
health-conscious and demand fresh
1 Keep vending premises/carts
clean and pest-free
damage to fruits and vegetables. The
application of wax coating not only
farmers and traders in the kinnow-
growing areas of Abohar, Fazilka, Muk-
300 million metric tonnes of
fruits and vegetables, as per the 2016-17
fruits and vegetables, which has spurred
researchers to develop eco-friendly coat- 2 Use potable water for washing
fruits and vegetables
reduces water loss through transpira-
tion, but also minimises the respira-
tsar, Bathinda and Hoshiarpur . In Pun-
jab, kinnow growers are commercially
3
data of the National Horticulture Board. ings and packaging that prolong the Keep sliced fruits and tion rate, thus slowing the biological using citrashine wax (shellac) for
However, due to lack of post-harvest shelf life of the products. However, there vegetables covered and system of perishable produce which improving the shelf life and quality of
infrastructure and cold chain facilities, are widespread misconceptions about at a low temperature are dependent on oxygen. kinnow fruits during marketing. The
about one-third of the produce goes fruit waxing among consumers. Certain With a slower respiration rate, the application of citrashine wax on kinnow
waste. Such losses adversely affect Indi-
an economy, even as the intercontinental
types of waxes are permitted to be
applied on fruits, in accordance with
4 Wash chopping board, knives
etc. with clean water before
and after use
ripening process is delayed and thus,
the fruit remains firm, fresh and nutri-
has been recommended by Punjab Agri-
cultural University (PAU), Ludhiana.
trade in fresh fruits and vegetables is Good Manufacturing Practices or within tious for a longer period with a better The citrashine-treated fruit can main-
increasing rapidly.
Indian markets are flooded with exot-
the specified levels in countries such as
Australia, New Zealand, the US and
5 Keep garbage bins covered
to keep pests away
shelf life. The wax coating, when
applied on fruits and vegetables, forms
tain its quality for up to two weeks
under ambient conditions.
ic fruits with wax coatings. Waxing of
fruit is an emerging technology which
those under the European Union.
The Food Safety and Standards 6 Wear clean clothes or uniform
while plying the trade
an odourless, tasteless membrane
which creates a modified atmosphere LUBRICANTS UNSAFE
can minimise post-harvest losses and
increase opportunities for distant and
export marketing. Other techniques
Authority of India (FSSAI), under Regu-
lation 2.3.6 of the Food Safety and Stan-
dards (Prohibition and Restriction on
7 Wash hands before, after
handling items; after using toilet
around each fruit. Resultantly, the
freshness and quality of the produce is
preserved for a longer period com-
It has been noticed that many fruit
retailers rub fruits and vegetables with a
piece of cloth soaked with oils or lubri-
such as right methods of harvesting,
packaging, storage systems etc. are
Sales) Regulations, 2011, has approved
three wax coatings — shellac, carnauba
8 Use water-proof bandage
to cover cuts or burns pared to the unwaxed ones.
It can be done in several ways, ranging
cants to improve glossiness and appear-
ance. This practice by small vendors or
equally significant in curtailing losses of
perishable produce.
and beeswax — for application on fruits
and vegetables. Shellac is a resin secret- 9 Do not handle food items
when unwell
from manual rubbing of the product sur-
face gently with a soft cloth or cushioning
traders should be strictly checked as
food safety regulations do not permit the
PERISHABLE PRODUCTS
Fruits and vegetables are a rich source
ed by the female lac bug on trees. Car-
nauba wax is obtained from the leaves of
the carnauba palm. Beeswax is the natu-
10 Use clean and separate
dusters to clean surfaces
and wipe utensils
material drenched with wax, or submer-
gence in wax, to automated roller brush
application. During the process, only a
use of non-edible chemical compounds.
The waxing technique is commonly used
in developed countries; in some coun-
of dietary fibre, vitamins and minerals ral wax produced by the honeybee. All tiny amount of wax is required to provide tries, it is mandatory as quality assur-
and form an important part of a healthy these waxes are processed as dry flakes FSSAI (Food Safety & Standards Authority of India) a microscopic coating around the crop. In ance treatment for export marketing.
diet. However, these commodities are and dissolved in organic solvents to is the country’s food safety regulator general, each piece of waxed produce has Wax coatings used on fruits must
highly perishable because they contain make a liquid form for application on only a drop or two of wax. Nonetheless, meet the FSSAI regulations for safety.
80-90 per cent water. Once these are har- the horticultural produce. waxing does not improve the quality of Produce shippers, traders and super-
vested, water quickly evaporates, lead- inferior fruits. Heavy application of wax markets are required to label fresh
ing to loss of cosmetic appearance, MOISTURE SHIELD may, on the contrary, adversely affect the fruits and vegetables that have been
nutrients and resulting in poor shelf life Fruits and vegetables have a natural quality of fruits by blocking the fruit gas waxed. Fruits coated with food-grade
of the produce. Thus, fresh fruits and wax coating which develops during exchange, leading to the development of waxes approved by the FSSAI are gen-
vegetables require protective treatment. the maturation and ripening process. off-flavours. Some of the fruits which can erally safe to eat. However, if people
Chemical fungicides provide the pri- However, the natural shield is be coated are apple, kinnow, lemon, don’t want to consume wax, they can
mary means for controlling post-harvest destroyed during harvesting and post- orange, pear and mango. simply wash and rub the fruits under
fungal decay. However, continuous use harvest operations such as washing, In Punjab, about six commercial auto- lukewarm water.
of fungicides has faced two major obsta- grading, packaging, transportation mated mechanical waxing and grading Director, Punjab Horticultural
cles: increasing public concern regard- etc., leading to bruising and decay of lines for kinnow have been established Post-harvest Technology
ing contamination of these crops with the produce. Waxing acts as a moisture by the Punjab Agro Industrial Corpora- Centre, PAU, Ludhiana
KS Pannu
Watch out for artificial ripeners
fruits and 0.2 ppm for vegetables. The EXPORT SCENARIO 65 to 68 per cent. The TSS is a measure
F
MRL fixed for pesticide dicofol is 5 ppm of the amount of material that is solu-
RUITS are the best natural
food as these are the richest
for fruits and vegetables.
ACID CONTENT
~9,411 crore ~4,229 crore Fruits
ble in water. The correct sugar content
is critical for proper preservation of
~5,182 crore
source of nutrition. The con- Export of fruits and vegetables the product. If the final TSS of the jam
sumption of fruits has Acids are added to fruit juice to bring the from India during 2017-18 Vegetables is lower than 65-68 per cent, the shelf
increased considerably in pH within the range 3-3.3, which is nec- life will be reduced.
recent years due to improved financial essary for product-making (pH is a ■ Mangoes, walnuts, grapes, bananas and pomegranates
21 workers die
in China coal Amid US shutdown,LOVE Act comes to couples’ rescue Nobel-winning scientist
mine collapse Washington, January 13
There doesn’t seem to be
who was preparing to wed
fiance Sam Bockenhauer,
Walters, who plans to wed
Kirk Kasa on February 2 on
stripped ofhonorary titles
Beijing, January 13 much love in the air in Wash- said. “So we were going to the campus of Catholic Uni- Washington, January 13 intelligence. However, in the
Twenty-one workers were ington these days, as a long have a wonderful party, of versity, the shutdown was Nobel laureate James Wat- new PBS documentary titled
killed after a roof collapsed and bitter government shut- course, but couldn’t be legal- simply “a small speed bump son, co-discoverer of the "American Masters: Decoding
at a coal mine in northwest- down drags on with no end in ly married in DC until we got in the road”. “We knew about DNA helix and father of the Watson", when asked about
ern China, state media sight. But couples whose mar- our marriage licence.” the shutdown, but we didn’t Human Genome Project, has his views on race in the
reported on Sunday. riage plans were thwarted by Some couples, like Dan Pol- know that it would directly been stripped of honours by decade since his departure
Eighty-seven persons were the partial shutdown have lock and Danielle Geana- affect our ability to get mar- his laboratory following “rep- from the lab, Watson said he
working underground in the gotten a break, thanks to the copoulos, had no time to spare. ried in DC legally,” said Wal- rehensible” remarks on race stood by his former remarks,
Lijiagou coal mine in the action of Mayor Muriel Bows- They managed to get their ters, a New York resident who and ethnicity. citing the difference in IQ
Shaanxi Province at the time er and city council. wedding licence on December was determined to get mar- The Cold Spring Har- tests results to suggest
of the accident on Saturday The city’s Marriage Bureau, 27, just two days before their ried in the nation’s capital. bor Laboratory black inferiority. While
afternoon, state-run Xinhua part of the US capital’s feder- scheduled wedding. “By the But while some have taken (CSHL), the New York he expressed his hope
news agency reported. ally funded court system, had
The DC Council passed fast-track legislation, time we figured out we could- the shutdown in stride, it has facility where Watson for everyone to be
Initial reports said that 19 been deemed “nonessential” Let Our Vows Endure Emergency n’t get a licence, we were run- brought “chaos” to those in worked for nearly four equal, he said: “People
persons were killed while 66 and shuttered as part of the Amendment Act, or LOVE Act, empowering ning out of time before friends the wedding business. “It’s a decades and which
James Watson
who have to deal with
others airlifted to safety. thorny standoff between and family were coming to lot of chaos, it’s a lot of has a school named black employees
Rescuers found two more President Donald Trump and
the mayor's office to validate marriages Washington to celebrate with uncertainty,” said Rachel after him, said it was acting found this is not true.”
bodies of trapped miners on congressional Democrats. us,” Geanacopoulos said. Rice, a wedding planner who in response to his remarks “Watson's statements are
Sunday, the report said. The But on Friday, Bowser but they cannot shut down will spare future brides like “So we focused on the really recently had to shift a wed- made in a television docu- reprehensible, unsupported
cause of the accident at the signed an emergency meas- love in the District of Colum- Claire O’Rourke from find- important thing — celebrat- ding ceremony from Wash- mentary aired this month, by science and in no way rep-
site, run by Baiji Mining, is ure authorising city officials bia,” City Council member ing themselves in ing — and decided to figure ington to nearby Virginia. Xinhua reported on Sunday. resent the views of CSHL,”
under investigation. Though to validate marriages in the Brandon Todd said when he Kafkaesque situations. out the rest later.” Her Even if the shutdown were to The 90-year-old geneticist the laboratory said before
the number of deaths has absence of the Marriage introduced the measure. “Practically, we couldn’t mother, Daphne, said she was end next month, Rice said, resigned under fire from his revoking three titles — chan-
reduced at mines in recent Bureau, which closed when Titled the Let Our Vows sign all legal certificates dur- “delighted”. “We had a really “some might say, ‘I can’t laboratory in 2007 after cellor emeritus, Oliver R
years, mining accidents are the budget standoff began on Endure Emergency Amend- ing the shutdown without great big wedding two weeks wait to book my venue; I telling a British newspaper Grace Professor Emeritus
common in China, the world’s December 22. “They can shut ment Act, or LOVE Act, the having a marriage licence,” ago... (but) it feels wonderful have to book my catering, my that people of African and honorary trustee soon
largest coal producer. — PTI down the US government, law is valid for 90 days and O’Rourke, a Washingtonian to have it official.” For Caitlin photographer.’ — AFP descent tend to have lower afterwards. — IANS
14 SPORT THE TRIBUNE
CHANDIGARH | MONDAY | 14 JANUARY 2019
BRIEFLY One year after making his First-Class debut, 19-year-old Shubman Gill ready to don India colours Gill ready for
TODAY ON TV
er, he feels it has come at
the right time and might
help him fulfil his dream of
56, 54
In his first Ranji Trophy
In the recent past, a num-
ber of Punjab players —
including the likes of Man-
was phenomenal as an
opener for India A in New
Zealand. We have dis-
I-LEAGUE
CHENNAI VS EAST BENGAL playing for India in the match of the season, Gill deep Singh, Gurkeerat cussed with India A caoch
World Cup and helping the was in fine form in Mann and Barinder Sran — Rahul Dravid and he has
STAR SPORTS 7:30PM November, kicking off his
team win the quadrennial made it to the Indian team said that Gill is ready for
ASIAN CUP showpiece. The 12th edition campaign with two 50s. but were unable to keep up international cricket. The
INDIA VS BAHRAIN (9:30PM) of the 50-over World Cup He has added 3 more to the rigours of internation- best part is the clutch of A
UAE VS THAILAND (9:30PM) will be played in England Shubman Gill gets throwdowns from his father Lakhwinder Singh at their own training facility in 50s, apart from 2 100s, in al cricket. Gill doesn’t want tours which has made all
STAR SPORTS the ongoing season
and Wales in May-July. Mohali on Sunday. TRIBUNE PHOTO: RAVI KUMAR to think about that right now. these players battle-ready
PWL “It is a great opportunity “I don’t want to see myself for the biggest challenge,”
PUNJAB VS MUMBAI for me and it has come at Asked how he would learnt in these years.” played there. The pitches, Virat Kohli. “I am a great fan in that position because it Prasad said.
SONY SIX 7PM the right time… If I do well, approach the New Zealand “I have visited New the atmosphere… I am of Virat. I love the way he would put added pressure on The likes of Hanuma
I have a great chance of tour, Gill said: “I will go Zealand twice in the last familiar with those condi- conducts himself on and off me. I just want to go there Vihari, Mayank Agarwal,
EPL
making it to the World Cup there and just express one year, so of course that tions, so I believe it will be a the field. Whether I am and play my natural game Prithvi Shaw, Khaleel
MAN CITY VS WOLVES (TUESDAY)
squad. Everything is in my myself, whether I am bat- will be of great help,” he good tour.” picked in the playing XI or and utilise whatever cricket- Ahmed have all been
STAR SPORTS 1:30AM
favour and I really want to ting or I am in the field. I added. “I know most of the Gill is also excited about not, it will be a great learning ing knowledge I have gath- impressive in internation-
TENNIS make this count,” said the want to go out there and pitches where India is sharing the dressing room curve to see him prepare for ered in my short career so al cricket and that makes
AUSTRALIAN OPEN promising cricketer. exhibit whatever I have scheduled to play. I have with his idol, India skipper the match and the way he far,” he concluded. Prasad very happy. — PTI
SONY SIX 5:30AM
3
Wickets required by ODI by 34 runs. 66 to take a two-shot lead into right rough, his second shot Andrew Putnam was two
Duanne Olivier to equal
The series resumes in Ade- the final round as he goes for went 180 yards to the right shots behind after a 67. Keith
South Africa’s 117-year-
old record for the most laide on Tuesday with the his second victory this season front greenside bunker, and Mitchell had a 63 and was
wickets in a three-Test series final match in Melbourne on on the PGA Tour. Kuchar his sand shot went 29 yards four shots behind, along with
Friday. —Reuters ended a three-year drought ANIRBAN LAHIRI to the green where he had a Chez Reavie (66). — PTI
THE TRIBUNE
CHANDIGARH | MONDAY | 14 JANUARY 2019 SPORT 15
Bahrain stand in way of India’s knockout dream
Sharjah, January 13 ment was played in a
Despite their loss to UAE,
India will still be fired up by
the prospect of reaching the
round-robin format com-
prising four countries.
Even a defeat on Monday
❝ About India’s record against Bahrain
I don’t believe in records. There are a lot of
factors that come into play. When was the last time
knockouts for the first time may still see India through we played them? Was it the same team? What were
when they take on Bahrain in to the knockouts as one of the circumstances? Everything’s always changing.
their final Asian Cup group the four third-placed teams Not do-or-die
match here on Monday. if hosts United Arab Emi- If we win, we don’t have to worry about anyone
A draw against world No. rates beat Thailand in the else. So we’ll focus on ourselves. I’m
113 Bahrain will be enough other Group A match on the not sure whether we can call it do-or-
for world No. 97 India to qual- same day. Along with the die. That’s a bit too dramatic.
ify for the Round of 16 for the top two countries, four
first time after failed third-placed sides from the Will score
attempts in 1984 and 2011. six groups will also advance They defend very well and are very well North Korean fans watch their team’s match against Qatar. AFP
The match, which may to the knockouts. But organised. I’m sure that it will be
turn out to be the biggest Stephen Constantine’s side difficult. But we have shown that we can QATAR HIT NORTH KOREA FOR SIX
night for Indian football after cannot lose to Bahrain by a score against good teams. I’m AL-AIN: Qatar’s Almoez Ali scored four goals in a 6-0 Asian Cup
its achievements during the big margin as goal differ- sure we can score tomorrow as rout of North Korea on Sunday in the eery atmosphere of a
golden era (1951 to 64), is ence will be crucial. India Under Constantine, India’s defence has improved significantly. AFP well. — Stephen Constantine, INDIA COACH near-empty Khalifa Bin Zayed Stadium in the United Arab
also significant as skipper had lost 5-2 to Bahrain in the Emirates. Ali hit two in the first half and two more in the sec-
Sunil Chhetri will equal for- 2011 Asian Cup. The team largely maintained deploy a defensive approach land, who defended deep in matches. The 2-0 win had
ond to go top of the goalscorers’ charts with five altogether,
as the 2022 World Cup hosts safely reached the Round of
mer captain Bhaichung But India have shown that its shape and intensity in the and hit on the counter the first half and hit on the come in an international 16. However, there was little excitement at any of Qatar’s
Bhutia’s record of 107 they are no longer an also-ran first two matches. against a physical Bahrain counter. India would take friendly in Bahrain in goals as a long-running Gulf blockade of the resource-rich
international appearances. side. Constantine has built However, the lack of cre- as they need just a draw confidence from that result. October 1979. Bahrain state prevented any fans from attending the game in Al Ain.
India had finished run- India into a compact and ativity in the midfield was while it is a must-win game Historically, India have have won on five occasions The tiny attendance of roughly 300 in the 16,000-capacity
ners-up in the 1964 edition largely defensive unit which evident and a lot will depend for the West Asian side. won just one match win while one match had venue was dominated by two small groups of North Korean
in Israel but that tourna- tries to score on the counter. on Chhetri. India may again Bahrain lost 1-0 to Thai- against Bahrain in seven ended in a draw. — PTI fans who sporadically cheered and waved flags. AFP
Federer, Djokovic going for record seventh title | Andy’s last Major?
Melbourne, January 13
YOUNGEST SLAM
While Wimbledon (established in 1877) is
Mom on a mission
Serena seeks 24th Grand Slam singles
In search of
Roger Federer and Novak the oldest of the four Grand Slams, the Aus-
Djokovic are both gunning tralian Open is the youngest. It started in 1905 and was
for a record seventh Aus- named the Australasian Championship in the beginning. title to equal Court’s all-time record
tralian Open crown from
HOTTEST SLAM
7th heaven
Monday, but Andy Murray
will make his last appearance The tournament is set dur- bines air temperature and
ing peak summer in Aus- humidity, will be replaced
in Melbourne as the era of the
tralia. Temperatures can by a heat stress scale. Air
“Big Four” draws to a close. reach up to 40°C, while temperature, radiant heat,
World No. 1 Djokovic and high humidity adds to the humidity and wind speed
third seed Federer face a players’ difficulties. The will be taken into account
stern challenge from the Extreme Heat Policy was under the new system. A
likes of youthful force introduced in 1988, under score of 1 on the 5-point
Alexander Zverev, seeded which the referees stopped scale is regarded as tem-
four, who is still looking for play if the temperature perate playing conditions.
a first Major to cement his reached 40°C. But last Players will get a longer
place as torch-bearer for year, the policy was criti- break at 4. Play will be sus-
the next generation. cised by several players. pended on the outside
But Murray dropped a Alize Cornet and Simona courts and the roof shut on
Halep needed treatment. the main courts at 5. A 10-
pre-Grand Slam bombshell,
So, the organsiers have minute break between the
breaking down during a made changes to the heat third and fourth sets will be Serena Williams during a practice session. AFP
tear-filled press conference policy. The Wet Bulb Globe introduced in the men’s
as he revealed chronic hip Temperature, which com- singles matches. MELBOURNE, January 13 ❝ I think it’s possible for
pain means he will retire Serena Williams was eight Serena to equal me but I
after Wimbledon — if he FIFTH-SET TIE-BREAKS weeks pregnant during her don’t think there’s a clear-
can carry on that long. And The 2019 edition will see final-set tie-breaks for the first 2017 Australian Open tri- cut favourite. I think it’s a
question marks remain time in the Australian Open history. The US Open was the umph and while she has pretty open tournament
over the fitness of world No. first Grand Slam to introduce final-set tie-breaks. While failed to add to her tally of and I think an outsider
2 Rafa Nadal who pulled out the US Open has a standard first-to-seven-points system, 23 Grand Slam titles, the can win it❞ Margaret Court
of his Brisbane warm-up at the Australian Open, winner will be decided by a first- American is still regarded as
but arrived in Melbourne to-10-points tie-break. Wimbledon also announced a the dominant force in has had a fractured lead-up
professing he was “fully fit” switch to final-set tie-breaks from the 2019 edition, but women’s tennis on her to the tournament, with a
and promising to unleash a the British Major will have a first-to-seven-points tie- return to Melbourne. back injury cutting short
remodelled serve.
break when the scores reach 12-12 in the final set. The 37-year-old took a year her 2018 season in Septem-
It all means the era of the DEFENDING CHAMPIONS off after the birth of her ber. She will be without a
“Big Four” is almost over daughter Alexis Olympia in coach for the first few
MEN’S SINGLES
after a season in which Feder- Roger Federer September of that year, months of the season after
er — who opens his title before returning to action Darren Cahill left for “fami-
WOMEN’S SINGLES
defence against Denis last season, when she ly reasons” and if that set-
Caroline Wozniacki
Istomin on Monday — rolled reached the finals at Wim- back was not enough, she
back the years on Rod Laver Roger Federer hits a volley during a practice session on Sunday. AFP MEN’S DOUBLES bledon and the US Open. was outplayed by unseeded
Arena to win an emotional
Oliver Marach & Her quest for another Major Australian Ashleigh Barty
Mate Pavic
20th Grand Slam. It put him fell at the final hurdle on in the second round of the
on a par with other six-time WOMEN’S DOUBLES both occasions, however, Sydney International. The
Australian Open winners Timea Babos & with defeats to Germany’s Romanian, who lost the
Kristina Mladenovic
Djokovic and Roy Emerson Angelique Kerber in London 2018 Australian Open final
— although the Australian MIXED DOUBLES and rising Japanese star to Caroline Wozniacki, could
great’s victories all came Gabriela Dabrowski Naomi Osaka in New York. rue her lack of competitive
before the Open era. & Mate Pavic Caroline Wozniacki practises. AFP
The losses left Williams still matches but remained
By contrast, the 31-year-old MONDAY’S MAIN MATCHES seeking a 24th Grand Slam upbeat, while saying she
Djokovic endured a miser- singles title to equal Mar- had low expectations for the
WOMEN: 30-Maria Sharapova (Russia) vs Harriet Dart
able early Melbourne exit in Novak Djokovic serves during a practice (Britain); Polona Hercog (Slovenia) vs 2-Angelique Kerber garet Court’s all-time record year’s first Grand Slam.
2018, followed by elbow sur- session; (right) Rafa Nadal greets compatriot (Germany); Alison Van Uytvanck (Belgium) vs 3-Caroline and she will have another tilt A second Australian Open
gery and a string of disap- Garbine Muguruza. REUTERS, AP/PTI Wozniacki (Denmark); 5-Sloane Stephens (US) vs Taylor at that milestone during the title for Kerber, who denied
pointing results that saw him Townsend (US); 8-Petra Kvitova (Czech Republic) vs Mag- January 14-27 event, despite Williams in the 2016 final,
drop outside the top-20. greatness all began in 2008 Sunday. “I’m playing good If I am not feeling good, I will dalena Rybarikova (Slovakia) entering the tournament will be a perfect birthday gift
But since winning a fourth with his first Grand Slam tennis. I’m confident that I not be here,” he said before MEN: James Duckworth (Australia) vs 2-Rafa Nadal (Spain); ranked 16th in the world. for the world No. 2, who
Wimbledon in July, the Serb win. “It was my first Major think it needs a good per- revealing he had remodelled Denis Istomin (Uzbekistan) vs 3-Roger Federer (Switzer- While Williams achieved turns 31 during the first
rose inexorably back to num- trophy, that obviously served formance by my opponent his serve. “There are always land); 6-Marin Cilic (Croatia) vs Bernard Tomic (Australia); her win over sister Venus in week of the tournament.
ber one by losing only three as a great springboard for probably to beat me,” said the things to improve,” said the 22-Roberto Bautista Agut (Spain) vs Andy Murray (Britain) the final two years ago, the She looked sharp at the
further matches — one of my career,” Djokovic said as Swiss, who warmed for Mel- Spaniard, who faces Aus- challenge this year is expect- Hopman Cup, maintaining a
which was to Zverev at the he prepared to open his bourne with victory in tralian wildcard James INDIA NO. 1 IN ACTION ed to come from a vast array 100 percent singles record,
ATP Finals. Djokovic won his assault on a seventh crown Perth’s Hopman Cup. Duckworth on Monday. Prajnesh Gunneswaran is the lone Indian in the singles of players. Chris Evert has even though Germany lost
third US Open in September against American Mitchell Second-ranked Nadal, 32, Djokovic picked young main draw and the 29-year-old will meet American 20-year- described trying to pick a to Switzerland in the final.
to put him on 14 Grand Krueger on Tuesday. pulled out of Brisbane with a guns Zverev of Germany, old Frances Tiafoe, ranked 39, in his opening round on women’s singles champion Defending champion Woz-
Monday. Gunneswaran, India’s highest-ranked singles play-
Slams — three behind Nadal thigh strain although he Borna Coric of Croatia, in Melbourne as a “crap- niacki has been battling
er at 112, did not have much idea about Tiafoe. “I don’t
and six behind Federer. Nadal ‘feels good’ returned for an exhibition in Karen Khachanov of Russia know too much about him. I have seen him on TV,” shoot”, with the last eight rheumatoid arthritis but the
And Djokovic said that he Federer, now 37, remains the Sydney and insisted at the and Greece’s Stefano Tsit- Gunneswaran said. “I will have to play well to beat him. I Major titles having been won 28-year-old Dane will remain
was delighted to be back in chief threat to the Serb and weekend his fitness woes sipas as key threats to the will come up with a game plan and give it all I have got.” by different players. a contender, as will 21-year-
Melbourne where his rise to he sounded a warning on were behind him. “I feel good. top-three. — AFP World No. 1 Simona Halep old Osaka. — Reuters
Bengaluru win maiden PBL title Man United win Juventus ease into Coppa Italia quarterfinals Messi scores
at Tottenham MILAN: Juventus took the first step towards a
record fifth consecutive Coppa Italia triumph
comfortable win. The Turin club have won the 400th goal
league and cup double in Italy for the last
LONDON: Tottenham Hotspur’s BARCELONA: Barcelona for-
with a 2-0 win over Bologna on Saturday that four years and are aiming to become the first
Premier League title ambi- ensured the defending champions will join team from Europe’s top five leagues to win ward Lionel Messi further
tions suffered a major blow AC Milan and Lazio in the quarterfinals. five national cup titles in a row, although etched his name into Span-
as Marcus Rashford’s goal Goals from Federico Bernardeschi and Moise Barcelona and Paris Saint-Germain are chas- ish football history by
gave Manchester United a 1- Kean either side of the break gave Juve a ing the same objective this season. REUTERS becoming the first player to
0 victory at Wembley on Sun- score 400 goals in La Liga
day to maintain caretaker when he netted against
manager Ole Gunnar Solsk- Eibar on Sunday. The Argen-
jaer’s perfect start. Rashford tine, who has been the com-
beat Tottenham keeper Hugo petition’s all-time top scorer
Lloris from a tight angle in since 2014, calmly slotted
the 44th minute as rejuve- in a pass from Luis Suarez
nated United claimed a sixth from close range to strike
win from six matches since the league leaders’ second
former striker Solskjaer goal against the Basque
Bengaluru Raptors beat Mumbai Rockets 4-3 Shreyanshi Pardeshi and she lived up to the stepped in. United’s Spanish side. Messi was making his
to win their maiden Premier Badminton expectations, notching up a 15-8 15-9 win. keeper David De Gea pro- 435th La Liga appearance
League title. World No. 18 Anders Antonsen Earlier, Mumbai trump Pia Zebadiah and Kim duced a series of superb for the club, having made
lost narrowly to Bengaluru skipper Kidambi Gi Jung gave a fabulous start to their team by saves to deny Dele Alli, Harry his league debut in 2004.
Srikanth 15-7 15-10. Hendra Setiawan and beating Marcus Ellis and Lauren Smith 15-8 Kane and Toby Alderweireld Barca won 3-0 to go five
Mohammad Ahsan beat Mumbai’s Lee Yong 15-14. World No. 12 Sameer Verma bounced after the break as United points clear of Atletico
hung on for a first away Madrid at the top of the
Dae and Kim GI Jung 15-13 15-10. World No. back from a poor start to avenge his league
league win against Totten- standings. Earlier, Atletico
59 Vu Thi Trang had the responsibility of stage defeat to Bengaluru’s Sai Praneeth, ham since 2012. REUTERS Bologna’s goalkeeper Da Costa gets the ball before Juventus’ Cristiano Ronaldo. AFP beat Levante 1-0. REUTERS
playing the trump match for Bengaluru against winning 7-15 15-12 15-3. PTI
16 BACK PAGE THE TRIBUNE
CHANDIGARH | MONDAY | 14 JANUARY 2019
CSIO develops pilot display unit for IAF’s Hawk 44 strategic roads to be
Vijay Mohan
Tribune News Service
Chandigarh, January 13
built along China border
project to CSIO and the first
prototype has been fabricat-
ed. It is expected to take to
IN LINE OF SIGHT
■ The display unit will be
artificial horizon, take off
and landing data as well as
weapon aiming and delivery
with head-up displays.
“The PDU can be operated
in different modes that can
An indigenous pilot display the skies in a few weeks. installed above the cock- cues. Since the pilot does not be selected from a multi- New Delhi, January13 area. The standoff ended fol-
unit (PDU) has been devel- The British Hawk entered pit’s instrument panel with have to change his line of function up-front control The government will con- NEW 2,100-KM ROADS lowing a mutual agreement
oped for the IAF’s indige- IAF service in 2008, with 24 its screen at the pilot’s eye sight or visual accommoda- panel. In the ‘raster’ mode struct 44 strategic roads along ALONG PAKISTAN under which China stopped
nously upgraded Hawk-i aircraft received in fly-away level to ensure there’s no tion by peering repeatedly at it displays the real time the border with China and the construction of the road
advanced jet trainer by the condition and 42 being change in line of sight his instrument panel inside infrared camera video to the over 2,100 km of axial and lat- Lateral and axial roads and India withdrew its troops.
measuring over 2,100 km
Central Scientific Instru- assembled by HAL. Another ■ It will reduce reaction time, the cockpit, the PDU pilot for target seeking, eral roads in Punjab and The report stated that these
will be built at a cost of
ments Organisation (CSIO) 57 Hawks, with some enabling pilot to take split- reduces his workload and while in the mixed mode, Rajasthan, abutting Pakistan, around ~5,400 crore in 44 roads along the India-China
here. The instrument, akin going to the Navy, second decisions reaction time, while raster video is combined a CPWD document shows. Rajasthan and Punjab border will be constructed at a
to a head-up display unit, is were to be licence- enabling him to take split- with other information for According to an annual along the Pakistan border cost of nearly Rs 21,000 crore.
installed above the cockpit’s produced by HAL second decisions and weapon aiming and target report (2018-19) prepared and “The CPWD has been
instrument panel with its along with upgrade of enhancing his weapon locking along with other released earlier this month by touches areas from Jammu entrusted with construction
screen at the pilot’s eye lev- the fleet and incorpo- aiming capability. flight critical information to the Central Public Works and Kashmir to Arunachal of 44 strategically important
el and superimposes vital ration of some Indian It is smaller and the pilot,” Vipan Kumar, Department, the agency has Pradesh. The report comes at roads along the India-China
flight and mission parame- made components lighter than earlier principal scientist oversee- been asked to construct 44 a time when China is giving a border spanning J&K,
ters on the pilot’s line of and sub-systems. The head-up displays ing the project, said. “strategically important” roads priority to projects along its Himachal, Uttarakhand,
vision of the outside world. upgraded aircraft have developed by CSIO for “In the eventuality of mis- along the India-China border India borders. In 2017, Indian Sikkim and Arunachal
The Mission Combat Sys- been christened as Hawk-i. the light combat aircraft, sion computer failure, PDU to ensure quick mobilisation of and Chinese troops were Pradesh,” the report stated.
tems Research and Design The PDU provides a com- HAL trainer aircraft and has dedicated information troops in case of a conflict. engaged in a face-off at the It said the process of approval
Centre of Hindustan Aero- prehensive flight-symbology conditions. It displays navi- Jaguar. All modern combat which can be displayed to the The nearly 4,000-km-long Doklam tri-junction after the of detailed project reports by
nautics Limited (HAL), Ban- display along with ambient gation inputs like altitude, aircraft as well as some trans- pilot in stand-by-sight Line of Actual Control neighbouring country had the Cabinet Committee on
galore, had awarded this vision under all-weather airspeed, angle of attack and port aircraft are equipped mode,” he said. between India and China begun building a road in the Security is underway. — PTI | https://www.scribd.com/document/397733032/The-Tribune-14-Jan-Chandigrah-Www-sscias-com | CC-MAIN-2019-35 | refinedweb | 21,899 | 56.49 |
Posts: 1158
Registered: 08-10
Posts: 447
Registered: 08-09
Cell said:
The thread title speaks for itself - the command lines say that "Mancubus" is an unknown class and I don't have any other ideas what the hell they could be to be summoned.
Posts: 1482
Registered: 10-06
Phobus said:
It is definitely "fatso".
Posts: 1400
Registered: 03-09
__________________
Facebook | Twitter | Music on Facebook | Soundclick | Youtube | SoundCloud | ReverbNation
Posts: 212
Registered: 01-11
Cell said:
Heh, that would have been even more obvious than I could imagine... :D I was trying with "fat" and then "fatt", too, because I've seen sprite datas in Slumped which names the images as "Fatt*".
Thanks!
Posts: 6849
Registered: 06-06
Posts: 3851
Registered: 01-09
Posts: 652
Registered: 10-10
Posts: 403
Registered: 08-07
skib said:
Yeah, and the zombieman sprite is "POSS" but it's summon is "zombieman"
Posts: 1224
Registered: 03-04
Last edited by Vermil on 05-31-11 at 14:27
Posts: 16
Registered: 05-11
printz said:
The collectible artifact and Heretic weapon names are VERY annoying in ZDoom. I hope Eternity calls them sensibly like TomeOfPower or HellStaff.
Posts: 7130
Registered: 01-03
Posts: 5268
Registered: 01-02
__________________
essel.spork-chan.net - doom stuff, artwork, and music by esselfortium
Posts: 266
Registered: 03-02
Graf Zahl said:
People aren't doing what I think they should!
Posts: 4615
Registered: 08-00
Posts: 587
Registered: 05-07
esselfortium said:
Source port developers are under no obligation to do things the exact same way ZDoom did them simply because ZDoom did them first. Making it easier for ZDoom to run every wad in existence is likely not on the goal list of any other source port's developers.
Posts: 1740
Registered: 08-03
DaniJ said:
I don't really want to get drawn into this "debate" but com'on Graf, seriously? How many features has ZDoom felt the need to re-invent? Doomsday was using native files, pk3s, models, thing definitions (etc...) long before ZDoom even broached the possibility. Yet did Zdoom do as you claim and attempt to keep things compatible? I think not.
Posts: 802
Registered: 05-02
Graf Zahl said:
What I have problems with is to implement something in a way that breaks interoperability with other ports.
RjY said:
I never heard anybody say "Eternityism".
Or anybody besides myk say "Boomism"
Graf Zahl said:
You can implement a feature differently for various reasons. But that's not the point here.
Oh, and regarding PK3 directory structure, yes, I investigated Doomsday but I had 2 major problems with it:
1. lack of understandable documentation
2. the feature set was too limited and the design goals too different. I needed something that translates Boom's WAD namespaces properly to a directory structure. Hard to do that when the only existing implementation doesn't even know the concept of Boom namespaces, isn't it?
Also I never, ever received a shred of feedback to ensure better compatibility.
Last edited by DaniJ on 06-01-11 at 20:40
Last edited by Quasar on 06-02-11 at 01:08
Posts: 115
Registered: 04-10
> | http://www.doomworld.com/vb/source-ports/55498-what-do-i-have-to-type-in-command-line-parameters-to-summon-mancubi/ | crawl-003 | refinedweb | 531 | 61.56 |
Simply choose the working script, from the right list tree, choose the fonctions, the class to instanciate and there methods to run and just press thebutton Run : <your script path>
Requirement : Pymel
Usage
import source_python
test = source_python.SourcePython()
see the installation to put the menu in the main Maya window/General Editors and the auto-start.
Installation:
In your usersetup.mel (not userSetup.py)
(if you don't have one yet, create one on your mel folder)
put the lines below:
// put this line if you don't have it, it force the build of Maya menus
buildDeferredMenus();
// this add the menu Source Python below the Script Editor
python("import source_python;source_python.add_menu()");
// this load the interface on Maya start
evalDeferred "python(\"import source_python;test = source_python.SourcePython()\")";
Description:
The Source Python and Script Editor windows (or dock) is divided in two zone.
On bottom side: the standard Script Editor.
On the up side: the new Source Python zone.
This is divided in 2 panes:
Right :
the list of all the functions, classes and methodes of the loaded module
Filter / Sort / Doc
Filter : enter the string you're looking for and define the test:
in, startswith or endswith
Sort Alphabetical : enable the sorting or keep the original order
Show doc : on each selection, the corresponding doc is printed
Left :
the text zone to define the execution request
On top of all, the Run button to execute after reloading the script
Menus
File:
Open : open a python script to work on it
Refresh : read again the file to update the list of python object
Recents : the list of last opened python scripts
(the length is settable on the options)
Options:
Insert ScriptEditor : to force the insertion of the scriptEditor
Run Reset History : the scriptEditor history is cleaned on each run
In dock : to dock the window (by default on right side)
Recents:
Set length : define the max recent list length
Reset : clear the history
Settings:
Save : Store the settings of the ui
Reset : Restore the defaults ui settings
Help : This help
Limitations:
The scripts using some relatives informations using, for exemple __file__ or have some particular python object like singleton should not work. This because of the used method: execfile, where a new temporary file is used.
This script use the utf-8 encoding.
Thanks to Mako developers to implement the string conversion of the ast objects arguments.
Please use the Feature Requests to give me ideas.
Please use the Support Forum if you have any questions or problems.
Please rate and review in the Review section. | https://ec2-34-231-130-161.compute-1.amazonaws.com/maya/script/source-python-script-editor-dockable-for-maya | CC-MAIN-2022-21 | refinedweb | 425 | 53.95 |
Hi, I need some help with a C++ assignment. I'm supposed to write a Hangman program that)(In C++, a string is MUCH preferable to the old-fashioned c-strings.)
The user (either the guesser or the hangman) should be asked for the number of incorrect guesses to allow the guesser... within the range 4 to 10 inclusive.
Before each guess entered by the user, the program should:
Display the letters already chosen
Display the number of guesses left
Display the portion of the word already guessed, inserting an * (asterisk) for each letter not yet guessed.
The user enters a character; the program will then indicate if an incorrect character was chosen:
A letter already chosen
Any non-alphabetic character (such as ?, /, 4, $, etc.) (Hint: see documentation on ctypes.h - especially isalpha()).
Upon termination of a game the program should prompt the player if another game is wanted - an 'n' or 'N' will terminate the program, otherwise it will loop back, select another word, and do it all again!!
here's my code:
// PROGRAM 5 // HANGMAN GAME #include <iostream> #include <fstream> #include <string> #include <ctime> #include <cstdlib> using namespace std; int instructions(); void manual(); void file( char* ); int letterFill( char, char*, char* ); void Unknown( char*, char* ); const int MAX_LENGTH=10; void main() { bool done = false; char word[MAX_LENGTH]; char unknown[MAX_LENGTH]; char letter; char name[MAX_LENGTH]; int wrong_guesses=0; int MAX_TRIES; // SWITCH: MANUAL vs. SOURCE FILE do { switch(instructions()) { case 1: { manual(); break; } case 2: { file(word); break; } default: { done = true; break; } } } while(!done); cout << "INPUT NUMBER OF GUESSES THE PLAYER IS ALLOWED: " << endl; cin >> MAX_TRIES; Unknown(word, unknown); cout << endl << endl << "HANGMAN"; cout << endl << endl << "Each letter is represented by a star." << endl; cout << "You have " << MAX_TRIES << " tries to try and guess the word."; cout << "ENTER GUESS WHEN READY"; while (letter !='N' && letter !='n') { // LOOP UNTIL GUESSES USED UP while (wrong_guesses < MAX_TRIES) { // DISPLAY UNKNOWN WORD cout << unknown << endl; cout << "Guess a letter: " << flush; cin >> letter; // REPLACE * W/ LETTER IF CORRECT, // INCREMENT WRONG GUESSES IF INCORRECT. if (letterFill(letter, word, unknown)==0) { cout << endl << "Uh Oh! That's ONE Guess down!" << endl; wrong_guesses++; } else { cout << endl << "YAY! That letter is in the word" << endl; } // GUESSES LEFT cout << "Guesses Left: " << MAX_TRIES-wrong_guesses << endl; // GUESSED WORD? if (strcmp(word, unknown) == 0) { cout << word << endl; cout << "Yeah! You got it!" << endl; exit(0); } cout << "Ouch, you've been hanged." << endl; cout << "The word was : " << word << endl; } } system (“pause”); } // PROGRAM MENU int instructions() { int select = 0; cout << endl << "HANGMAN" << endl << endl; cout << " PROGRAM MENU" << endl; cout << " Select option 1 or 2" << endl << endl; cout << " 1. INPUT WORD MANUALLY" << endl; cout << " 2. PLAY AGAINST THE COMPUTER" << endl; cout << " 3. EXIT PROGRAM BY INPUTING: N or n" << endl << endl; cin >> select; return select; } //WORD FROM USER INPUT void manual() { string word; cout << endl << "INPUT WORD: " << endl; cin >> word; } void file(char *roc) { ifstream fin("G:/wordsource.txt"); int x; int count=1; int word; int i = 0; // INITIALIZE RANDOM GENERATOR srand(time(0)); // RANDOM NUMBER GENERATOR word = rand() % 20; // MOVE TO CORRECT PLACE IN FILE while (count < word) { fin >> x; if (x==0) { count++; } } // READ IN WORD do { fin >> x; roc[i++] = char (x); } while (x); } int letterFill( char guess, char *secretword, char *guessword ) { int i; int matches=0; for( i=0; i<MAX_LENGTH; i++ ) { // END OF WORD if( secretword[i] == 0 ) { break; } // GUESSED SAME LETTER TWICE if( guess==guessword[i] ) { return 0; } // MATCH GUESS TO SECRET WORD if( guess==secretword[i] ) { guessword[i] = guess; matches++; } } return matches; } // INITIALIZE UNKNOWN WORD void Unknown( char *word, char *unknown) { int i; int length=strlen(word); for( i=0; i<length; i++ ) { unknown[i]='*'; } unknown[i]=0; }
It compiles, but then does some really odd things, so hopefully you can all help me edit it?
Assignment's due tomorrow and this program is driving me nuts. Any useful websites would be helpful as well.
Thanks! | https://www.daniweb.com/programming/software-development/threads/180132/hangman-program-help | CC-MAIN-2022-33 | refinedweb | 647 | 67.49 |
Changes in 3.0.1
Bug 3916: deprecate RCVD_IN_RFC_IPWHOIS (trivial patch)
Bug 3822: warn during "make" if module versions are too low
Bug 3826: Turn copy config on for all cases, it will still turn itself off when max client == 1
Bug 3910: spamd/slackware-rc-script.sh: Removed redundant echos, fixed flags to kill and rm.
Bug 3776: restrict size of message body fed to TextCat to 10kbytes which is enough for reliable classification and prevents excessive time and memory consumption
Bug 3895: Mail::SA::Conf::Parser::finish() method is missing; this is required for Mail::SpamAssassin::finish() to operate. the result is that a user of the perl modules cannot call finish to GC the entire Spamassassin set of modules, as the call dies. fixed
upped the spec file to 3.0.1
Bug 3766: Provide support for specifying the username for virtual environments
Bug 3747: Move test to port 8 which is unassigned and hopefully will work on all systems. Also add an onfail warning that describes why the test might be failing
Bug 3806: do not run DNSBL and SPF tests as root on non-linux UNIX platforms, due to a stupid bug in Sys::Hostname::Long that renames the hostname
Bug 3741: FORGED_MUA_THEBAT_BOUN would FP for The Bat versions > 1, so we should only check for that v1 in the test
added MIME::Base64 to the optional (but highly suggested) section in INSTALL
changing comment since it's IMO exactly what we don't want to do
Bug 3865: specifying certain configuration parameters without a value didn't result in an error at parse time, but set an invalid value internally which could cause errors/etc. do a simple check for numeric, boolean, and string values.
Bug 3872: when syncing the journal and getting seen updates, the code would call seen_{put,delete} which defer to the journal when learn_to_journal is set, resulting in the msgid never getting stored and being passed from one journal to the next in certain situations.
Bug 3831: due to the RegistrarBoundaries REs being too loose, we would often misparse the given domain into the wrong number of parts. make the RE more strict to avoid this issue and also skip doing the RE check when the RE can't possibly match based on number of parts in the string.
Bug 3887: don't record regression test strings unless t/rule_tests.t is being run
Bug 3883: spamcop reporting was sending the whole user gecos field, which can give out private information, etc. since the real name isn't necessary for reporting (just need the email address), we can just stop trying to figure out the full name.
Bug 3876: flatten tokens hash returned by tokenizer to save memory, updated Plugin docs to show change, and pass in additional hash for bayes_scan hook
Bug 3855: Do not use qr to whitelist entries, Storable does not handle Regexp objects
Bug 3854: if no rules hit, _TESTSSCORES_ doesn't return 'none' like _TESTS_ does.
Bug 3734: uridnsbl rules work on body data, not header data, so change the rule type from header to body
Bug 3875: Remove map/grep combo and replace with foreach loop to avoid odd memory bloat issue
Bug 3801: MUAs allow no blank line between the end of the message header and a MIME boundary, so we should too.
Bug 3805: add the ability to whitelist (not query) the URIBLs for certain domains. added the top list (125 or so) from SURBL for queried domains that they whitelist.
Bug 3812: fix parsing of SMTPSVC headers, as generated by MS IIS, in Received hdr parser
Bug 3791: add support for XMail Received header formats
Bug 3830: add support for 'return-path' to extract MAIL FROM address from Received: headers
Bug 3649: helper_app_pipe_open doesn't do the right thing if STD{IN,OUT,ERR} filehandles != {0,1,2} fds
Bug 3837: over-broad RE in Received parser gets some rDNS and HELO strings mixed up
Bug 3827: typo in the RE for 2TLD
Bug 3827: update 2TLD listing in the URIBL Plugin
Bug 3427: if a schemeless URI was found, we would add '
http://' to the front, which is very bad since it would do this for 'foo.gif', '#foo', etc. Also, modify uri.t to give debug output upon failure.
some updates from trunk
Just did a case-sensitive sort with $ export LC_ALL=C $ sort < MANIFEST > MANIFEST.TMP && mv MANIFEST.TMP MANIFEST $ sort < MANIFEST.SKIP > MANIFEST.TMP && mv MANIFEST.TMP MANIFEST.SKIP
fix plugin POD docs; Plugin.pm had a sub-section inside a method's =item, which is just totally wrong
Bug 3825: document that # characters must be escaped in RE, or else they're considered the start of a comment
Added --whitelist option to the other autowhitelist options as one that has been removed
Bug 3822: clean up requirements documentation
Bug 3804: fix typo that caused X-Languages metadata for _LANGUAGES_ tag to be empty
prep 3.0.1 devel cycle
prep 3.0.0 release
Bug 3798: remove ninja* images
new logo
Bug 3794: add some defined() checks for incomplete DNS responses
Minor typo in Mail::SpamAssassin::Conf man
add documentation about Plugin::dbg having to be called via package name as it's not available in the plugin package namespace
added documentation for the standard arguments passed to plugins of different types
Create 3.0 (stable) branch, open up trunk for 3.1 (development) operations. | http://wiki.apache.org/spamassassin/changes301 | crawl-002 | refinedweb | 910 | 54.66 |
Contributor
6710 Points
Apr 10, 2017 06:47 AM|Eric Du|LINK
Hi sunureddy,
According to your description, as far as I know, you want to call module controller form another module controller, please refer to the following code:
sample code:'); } }]);
For more details, please check this tutorial:
AngularJS: How To Call A Controller From Another Controller:
Best Regards,
Eric Du
Apr 10, 2017 11:31 AM|sunureddy|LINK
Hi Eric,
Thanks for your code.
But My question is not accessing one module controller in another module controller.
I have controller like
var myModule = angular.module('myapp', []); myModule.controller('myController', ['$scope', function ($scope,) {
//some code }]);
I want to access entire "myController" in another module as it is.
Can you provide me solution
All-Star
15176 Points
Apr 10, 2017 11:45 AM|raju dasa|LINK
Hi,
sunureddyHow to access one module controller in another module in angular.js
Your requirement is not clear.
Controller are mainly used in templates, not for reusing in another component.
Module mostly acts like namespace/container for services, directives, filters etc. and not contains logic of its own.
So where does you want this controller into another module's component? like service, filter, directive etc.
and why? what is your actual requirement?
3 replies
Last post Apr 10, 2017 11:45 AM by raju dasa | https://forums.asp.net/t/2119309.aspx?How+to+access+one+module+controller+in+another+module+in+angular+js | CC-MAIN-2019-43 | refinedweb | 220 | 55.74 |
Can I use the Profile API on the client-side?
For security reasons, we require the Profile API only be used server-side. The Profile API allows you to look up data about any user given an identifier (e.g. email,
anonymousId, or
userId) and an authorized access secret. While this enables powerful personalization workflows, it could also let your customers’ data fall into the wrong hands if the access secret were exposed on the client.
Instead, by creating an authenticated personalization endpoint server-side backed by the Personas Profile API, you can serve up personalized data to your users without the risk of their information falling into the wrong hands.
Do you have an Audiences API?
Currently you can add, remove, and modify audiences only by using the Personas in-app audience builder.
However, you can programmatically query the Profile API in order to determine if a particular user is a member of a particular audience because Personas creates a trait with the same name as your audience. For example, to determine if the user with an email address of
[email protected] is a member of your
high_value_users audience, you could query the following profile API URL:<namespace_id>/collections/users/profiles/email:[email protected]/traits?include=high_value_users
The following response indicates that Bob is indeed a high-value user:
{ "traits": { "high_value_users": true, }, "cursor": { "has_more": false, } }
To learn more about our profile API, you can head here.
Does your identity model support multiple external ID types?
Yes, Identity Graph supports multiple external IDs.
Identity Graph automatically collects a rich set of external IDs without any additional code:
- Device level IDs (ex:
anonymous_id,
ios.idfaand
android.id)
- Device token IDs (ex:
ios.push_tokenand
android_push_token)
- User level IDs (ex:
user_id)
- Common external IDs (
- Cross domain analytics IDs (
cross_domain_id)
If you want Identity Graph to operate on a different custom ID, you can pass it in using
context.externalIds on an
identify() or
track(). If you’re interested in this feature, please contact your CSM to discuss the best way to implement this feature.
How do historical lookback windows work?
Person field.
Lookback windows are precise down to the hour, so a 90-day lookback window will include any events with a
timestamp timestamp within the last 2,160 hours (24 hr/day * 90 days).
The trait and audience will automatically update going forward as historical events exceed the lookback window.
How does Personas handle identity merging?
Each incoming event is analyzed and external IDs are extracted (
user_id,
anonymous_id,
- We first search the Identity Graph for incoming external IDs.
- If we find no users, we’ll create one.
- If one user is returned, then that user is chosen.
- If multiple users are returned, our merge protection kicks in and checks the validity of all of the provided external IDs.
- If the merge protection checks pass, we’ll create a new merge connection between those two users. The first user profile ever created becomes the parent profile, and all merged users become child profiles.
- If the merge protection checks fail, we’ll discard the lowest precedence external ID and re-run the algorithm.
Is all matching deterministic, or is there any support for probabilistic matching?
All Profile matching is deterministic and based on first-party data that you’ve collected.
We do not support probabilistic matching. We’ve found that most marketing automation use cases require 100% confidence that a user is who you think they are (sending an email, delivering a recommendation, etc). We’ve found the best way to support this is through a deterministic identity algorithm.
Should I use Personas if I already have a marketing automation tool?
Personas pairs well with marketing automation tools on the Segment platform.
You can think of Personas as the brain on top of your raw data streams, synthesizing those event streams into profiles, relationships, clusters, and new insights about your users.
From there, your marketing, product, sales, and success teams have channels on which they can act on a user’s needs.
They can reach out via livechat, email, push notification, or text. Success can better prioritize their support ticket in Zendesk, or hone in on the customer’s problem faster. On the sales side, they can focus on the products a prospect is most engaged with, or focus on getting the customer on the right plan. Your product team can serve specific recommendations, based on that user’s specific needs next time they visit your site.
Today, most businesses are forced to think about each channel as individual siloes. With Personas, all channels — including your marketing automation tool — can be powered by the same, singular understanding of your users.
What are Funnel Audiences?
Funnel.
The audience in the image below includes all users that have Product Added in the last week, but not Order Completed within a day of doing so.
Important: Funnel Audiences compute based on all instances of the parent event within the lookback period. This means that if you have a user that Product Added ⟶ Order Completed ⟶ Product Added, this user would be entered into the Abandoned Cart state despite having previously completed an order.
What happens to conflicting and non-conflicting profile attributes?
If two merged user profiles contain conflicting profile attributes, we’ll select the newest, or last updated, attributes when querying the profile. In the future, we’ll let the conflict resolution policies be configurable.
What is Personas Merge Protection?
Personas merge protection algorithm protects your identity graph from unnecessary merges by finding and removing untrusted external IDs. Here’s an example:
In this example,
anonymous_id: a1 is not reset during a
User Logout. Without merge protection, we’d merge
user_id u1 and
user_id u2. Instead, our Merge Protection algorithm detects that such a merge would break user_id uniqueness and prevents the merge.
This is especially helpful for preventing “blob users” that are merged together by non-unique anonymous IDs or by common group emails like
[email protected].
Which destinations support syncing the identity graph?
Most destinations on the Segment Platform are built up around a user model. They assume that a user will have a single userId. Further, most Destinations are not built to handle anonymous traffic.
By default, we do not sync the output of the Identity Graph to Destinations. However, Segment computed traits and audiences are based on the entire user profile, including anonymous and merged data. We sync the value of these computations (e.g.
blog_posts_ready_30_days: 10) using all
userIds on the profile.
For Destinations that support an
alias call (for example, Mixpanel), we have the option to emit an alias call on merge.
What Sources can I sync to Personas?
You can sync data from your…
- Website (analytics.js)
- Mobile SDKs (ios, android, amp)
- Serverside libraries (go, node, java, PHP, python, ruby, .NET)
- Facebook Lead Ads
- Activecampaign
- Customer.io
- Drip
- Iterable
- Klaviyo
- Mailjet
- Nudgespot
- Vero
- Blueshift
- Delighted
- Appboy
- Looker
- Radar
- Autopilot
- Friendbuy
If you have any questions, or see anywhere we can improve our documentation, please let us know! | https://segment.com/docs/personas/faqs/ | CC-MAIN-2019-18 | refinedweb | 1,170 | 55.64 |
I don't know how to recreate this but it seems to
be happening more frequently.
When I start up the ide it start with "Scanning
Project Classpath" and I get a progress bar that
shows the progress. After it's finished the
dialog box closes then comes up again and this
time it says "Initializing scanning. Please
wait..."
It closes then reopens continuously even if I
leave it for hours. No more progress bar just
the initializing message.
What seems to fix it is if I delete
the .netbeans\nb4.0beta1 directory
When I first ran netbeans it asked if I wanted to
import settings from 3.6 and I said yes. This
time I selected no. Hopefully that was the
problem but it's annoying to have to delete that
directory whenever this happens.
Probably caused by a partial fix to issue 48611.
amenegat,
what build number you use ???
this is P1 issue so your answer is important, thanks in advance.
Bulid Number is 200408191352
JDk client 1.5.0-beta-b32c on win2k
(Not worth making a new issue but can the about:detail page be made
readonly but selectable so the info above could have been copied and
pasted?)
It happened again when I went to look for the build number. Had to
delete the .netbeans\nb4.0beta1 directory again so transfering
settings from 3.6 or not doesn't seem to make a difference.
I also seem to get that initializing dialog box every so often out of
nowhere though it is fairly infrequent.
BTW, I've been playing with the 4.0 betas and early access releases
for some time. I can't go back to the 3.6 ones because 4.0 is so
much better I hope this gets worked out soon. I even used eclipse
for a while but came back to netbeans. You guys are doing a great
job.
Some confusion here. Tomas' fix of issue #48611 was put into trunk
just recently. I can't see how it could cause a bug in beta 1 which
the user is apparently using.
Oh, now I realize we saw this bug before and fixed it. It was a URL
problem - in some cases the apisupport project returned URL which was
not normalized (the disk letter was lowercased) on Windows which
caused equals on two URLs representing the same file to return false.
As you can see from the duplicate, this was fixed some time ago.
*** This issue has been marked as a duplicate of 47433 ***
Ok, so what do I have to do to get the fix? Will downloading the
file again from the beta link do it or do I have to get a more
current snapshot, beta, nightly, qbuild? Can I just do an update
from the ide itself?
Just because the problems been fixed doesn't mean it fixes my
problem :)
Either download a recent Q-build or dev build from:
or wait for NB 4.0 Beta 2 (to be released soon).
You might also want to update your JDK 1.5 version. Build 32c is Beta
1. There's a release candidate available from java.sun.com.
Reorganization of java component | https://netbeans.org/bugzilla/show_bug.cgi?id=49256 | CC-MAIN-2018-05 | refinedweb | 535 | 84.57 |
(grr it happened again >.<, my apologies to the guy who received this mail, it
was intended for the list)
From: Petr Jakeš <petr.jakes@...>
To: vicariousdm@...
Date: Thursday 01 April 2010
> Some examples of the code, so we all can learn from your experiences, will
> be nice.
>
> Regards
>
> Petr
>
Well, for this particular case, I was using a factory class that was in charge
of creating the several objects that were required. It worked more or less
like so: there is an indexer class, which takes care of crawling the
filesystem. For every file or directory it encounters, it passes a series of
parameters to the factory class (or object ;)), which the factory uses to
instantiate the object that represents said file/dir. Yes, you may say that
has too much coupling, but given the handling that one must do regarding
connections and transactions (and taking care not to use them in a different
thread than the one they were created on), it seemed the easiest and more or
less "right" way to do it.
So, let's say that there's one method in this Factory class/object to
instantiate each of the objects that can be scanned from the filesystem
(regular file, directory, image/video/audio file). Instantiation in itself
isn't too expensive (or at least there isn't much that you can do about it).
But when it comes to extracting the metadata for some particular files
(namely, audio, video and image files) I found that I was setting fields on
the object one at a time. This caused several UPDATE statements, which slowed
everything down.
So, in order to alleviate this, I did the following:
def new_photo(self, parent, name, relpath, mimetype, atime, mtime,
root, size, strsize, strabs):
trans = self._conn.transaction()
atime, mtime = self._check_stat(atime, mtime)
mimetype = mimetype[0]
photo = Photo(parent = parent, name = name, relpath = relpath,
mimetype = mimetype, atime = atime, mtime = mtime,
size = size, strsize = strsize, root = root,
isdir = False, strabs = strabs,
connection = trans)
self._get_photo_metadata(photo)
trans.commit(close = True)
return photo
The photo (I didn't use "Image" as a name so I wouldn't overwrite some other
class already defined within Python) was the heaviest class in this regard,
since it extracted two scaled images from the original (that's just something
the pogram does, you can try it out if you want to). This extraction is done
in the _get_photo_metadata method. So I got a transaction from the regular
SQLObject connection, and used it as a parameter at object creation time,
instead of the connection. After that I commit it with the close parameter on
True, since then the method ends and I don't want that transaction lying
around so that after working I still have a journal file for the SQLite db :P.
Hope it is useful for somebody in the future. Don't forget that the
transaction object you get from the connection.transaction() method, is
already begun. You just have to work directly with it and DON'T FORGET to
close it :) (via commit or rollback).
Thanks for the help people.
Cheers
Juan Manuel Santos
View entire thread | http://sourceforge.net/p/sqlobject/mailman/message/24913824/ | CC-MAIN-2014-23 | refinedweb | 524 | 58.92 |
Hello Friends,-
8)Now from below window choose create button:
Please write your comment and feedback below:-
3)See your browser URL and note your project ID from above some thing like that-1080127563513
4)In the main Google APIs Console page, select Services.
5)Turn the Google Cloud Messaging toggle to ON.
6)In the Terms of Service page, accept the terms.
7)get API Key from main Google APIs Console page, select API Access. You will see a screen that resembles the following and click on Create new Server Key:
8)Now from below window choose create button:
9)From below window note your project id and api key:
<?php $regID=$_GET['regID']; $registatoin_ids=array($regID); $msg=array("message"=>'HI Manish'); $url=''; $fields=array ( 'registration_ids'=>$registatoin_ids, 'data'=>$msg ); $headers=array ( 'Authorization: key=AIzaSyA46UE7bBWXCpHSD5sbNxbRwI1MAKVI-jg', ; ?>
package com.manish.gcm.push; import static com.manish.gcm.push.CommonUtilities.SENDER_ID; import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import android.annotation.TargetApi; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.google.android.gcm.GCMRegistrar; @TargetApi(Build.VERSION_CODES.GINGERBREAD) public class MainActivity extends Activity { private String TAG = "** GCMPushDEMOAndroid**"; private TextView mDisplay; String regId = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkNotNull(SENDER_ID, "SENDER_ID"); GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this); mDisplay = (TextView) findViewById(R.id.textView1); regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { GCMRegistrar.register(this, SENDER_ID); } else { Log.v(TAG, "Already registered"); } /** * call asYnc Task */ new sendIdOnOverServer().execute(); mDisplay.setText("RegId=" + regId); } private void checkNotNull(Object reference, String name) { if (reference == null) { throw new NullPointerException(getString(R.string.error_config, name)); } } @Override protected void onPause() { super.onPause(); GCMRegistrar.unregister(this); } public class sendIdOnOverServer extends AsyncTask2)GCMIntentService.java
{ ProgressDialog pd = null; @Override protected void onPreExecute() { pd = ProgressDialog.show(MainActivity.this, "Please wait", "Loading please wait..", true); pd.setCancelable(true); } @Override protected String doInBackground(String... params) { try { HttpResponse response = null; HttpParams httpParameters = new BasicHttpParams(); HttpClient client = new DefaultHttpClient(httpParameters); String url = "?" + "®ID=" + regId; Log.i("Send URL:", url); HttpGet request = new HttpGet(url); response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); String webServiceInfo = ""; while ((webServiceInfo = rd.readLine()) != null) { Log.d("****Status Log***", "Webservice: " + webServiceInfo); } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { pd.dismiss(); } } }
package com.manish.gcm.push; import static com.manish.gcm.push.CommonUtilities.SENDER_ID; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import com.google.android.gcm.GCMBaseIntentService; public class GCMIntentService extends GCMBaseIntentService { public GCMIntentService() { super(SENDER_ID); } private static final String TAG = "===GCMIntentService==="; @Override protected void onRegistered(Context arg0, String registrationId) { Log.i(TAG, "Device registered: regId = " + registrationId); } @Override protected void onUnregistered(Context arg0, String arg1) { Log.i(TAG, "unregistered = " + arg1); } @Override protected void onMessage(Context context, Intent intent) { Log.i(TAG, "new message= "); String message = intent.getExtras().getString("message"); generateNotification(context, message); } @Override protected void onError(Context arg0, String errorId) { Log.i(TAG, "Received error: " + errorId); } @Override protected boolean onRecoverableError(Context context, String errorId) { return super.onRecoverableError(context, errorId); } /** *); } }3)CommonUtilities .java
package com.manish.gcm.push; public final class CommonUtilities { //put here your sender Id static final String SENDER_ID = "311451115764"; }4)activity_main.xml
5)manifest.xml5)manifest.xml
6)Download Zip CodeThanks,
Please write your comment and feedback below:
Nice tutorial can you please help me? how to use sql database to send push?
Please see demo i am using mysql. You can use any...
Hi Can u upload the whole project source code ...
I thinks it's gonna be more helpful for us than some peace of code.
the project can be built .
Thanks in advance.
Sure i will upload soon..
Hi, I'm new to java and android but I think there could be a problem with your example.
If the device has not registered before, GetRegistrationId will return an empty string and so you then call register. That returns the new registrationId in the GCMIntentService as a local variable.
So when you call sendIdOnOverServer the registrationId might not have been received but even if it has been received, it will not be the registrationId that is sent to the server in MainActivity. That one will still be blank.
Or am I missing something?
Thanks.
No no this demo always send registration id before get a push..
It should not be blank any time...
I have tested it no issue here and i am using it in my app also...
I'm sure you know your program better than I do but I'm confused as to how it is working. This is how I see it:
The first ever time you call getRegistrationId it will return an empty string. You then call register to get a regId from GCM but that call returns immediately and the regId is returned seconds later in the intent service.
You call sendIdOnOverServer immediately after the call to register and hence regId will be empty at that time so an empty string will be sent to your server.
The next time the progam runs, it will work fine because getRegistrationId will return the last registration and so regId will not now be empty and so a valid regId will be sent to your server.
If I am wrong about this I'd appreciate to know how it works. I can understand that your app may work long term but I think first time, it will effectively fail.
No John its work all time fine because this app send registration id on server every time.. I have tested it..
upload full project source code please
Sure I will Upload on GIT server, keep in touch..
Thanks,
Hello Manish thanks for your tutorial. but i think there is a problem..
in your manifest file you are declaring
android:minsdkversion="7"
but i think it should be
GCM requires Android SDK version 2.2 (API level 8) or above.
android:minSdkVersion="8"
Deepak
Yes may be if google not allow us we can't send push message..
This comment has been removed by the author.
Note down the project id which will be used as SENDER ID in android project=311451115764;
sender Id is project_Id? and i have copied your code in that "GCM registrar" shown error line...!pls help brothr
Yes sender id= project id..
Where you are facing trouble please let me know..
Nice tutorial,it shows error in this line...public class sendIdOnOverServer extends AsyncTask, the error is Syntax error on tokens, Dimensions expected instead. I am using ROR framework,do you know how to write server side code for that one to send push notification,if i add data in server the push notification has to come in my android apps.Help me dude
I am using eclipse, and code is working for me.I have put all code of=n Git Server please download from there. And a download link on my post also.
Thanks,
The code is completely mangled up, probably a fault of the syntax highlighter, but it ruins the entire tut.
For e.g. a theres a complete loss of capitalization in the xml tags for (also in the manifest):
I have add a download link on my post please download zip code and try again...
Thanks,
This comment has been removed by the author.
Great post! Thanks Manish...
Thanks and your welcome!
Hi Manish, Is there anyway to contact you via chat?
Can you share your problem here? It will usefull to others visitor. Well you can email me at [email protected]
Hi Manish,
It is a nice tutorial but I see your GCM.php starts with some weird syntax. Can you clarify the GCM.php file. it gives error of variable registatoion_ids and msg not defined.
Thanks
Hello Pragmatute!
Thanks for your suggestion, I change the code please check now...
Hi Manish,
It is a nice tutorial but I have doubt when we get $_GET['regID'];
It is not working?
It should work any problem in code?
No problem in code but its my doubt
How we get registration id?
You will get reg-id from client side in this method-Delete?®ID=+regId
Hi
When i use this code i get the following error
{"error":"InvalidRegistration"}
Have you short out problem? Have you created new project on Google developer?
Hi Manish
I am also same this problem
I was registry, user Project ID number to register on Device and there are below notification
Your device registred with GCM
Server successful added device
But when i user server to sent notification,
At resutl message from google.send is
{"multicast_id":6265367446240819368,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
So, how to fix it
Please help me
Its seems any php tag like "pre" or something else missing.
This comment has been removed by the author.
in logcate it's display
09-17 12:22:40.017: V/GCMRegistrar(342): Registering app com.manish.gcm.push of senders 386632392116
09-17 12:22:40.017: V/GCMRegistrar(342): Creating pending intent to get package name
09-17 12:22:40.297: V/GCMBroadcastReceiver(342): onReceive: com.google.android.c2dm.intent.REGISTRATION
09-17 12:22:40.297: V/GCMBroadcastReceiver(342): GCM IntentService class: com.manish.gcm.push.GCMIntentService
09-17 12:22:40.327: I/Send URL:(342):?®ID=
09-17 12:22:40.357: V/GCMBaseIntentService(342): Intent service name: GCMIntentService-386632392116-3
09-17 12:22:40.387: D/GCMBaseIntentService(342): handleRegistration: registrationId = null, error = ACCOUNT_MISSING, unregistered = null
09-17 12:22:40.387: D/GCMBaseIntentService(342): Registration error: ACCOUNT_MISSING
09-17 12:22:40.387: I/===GCMIntentService===(342): Received error: ACCOUNT_MISSING
09-17 12:22:40.527: I/global(342): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
i have few question pls help me
i had set senderid as per google account regiser
i had make GCM.php file put it into parsing/GCM.php file in wamp server
but i had not create any talbe nothing so where it store?
second thing how can i send any message on device using this?
Hi Pankaj!
Let me clear all of your doubts.
1)Its not must your device return always registration id. Please try 1-3 time if you did not got registration id in your application.
2)Here we are not storing any thing in database just we are getting registration-id from device and we hit the google server and google send push message on mobile device.
3)Please check your project on google developer console and put sender-id same as your project-id, both are same.
4)In your php code change 'Authorization: key=AIzaSyA46UE7bBWXCpHSD5sbNxbRwI1MAKVI-jg', with your project key generated by you.
Note: I think you are using same package name whats in my demo app so be sure your application package name should be same on Google console. I think you should change package name in your android code and create new project on Google console.
Here I am explaining php code line by line hope it will help you.
'HI Manish'); //here I create json array message to send to user device
$url=''; //this is url where we hit for sending push message on device from php server
$fields=array
(
'registration_ids'=>$registatoin_ids,
'data'=>$msg
);
$headers=array
(
'Authorization: key=AIzaSyA46UE7bBWXCpHSD5sbNxbRwI1MAKVI-jg', //this is your google app project key
'Content-Type: application/json'
);
$ch=curl_init(); // init method is used for start curl; // it will return result
?>
Hi this is Maheswaran, I get only the empty Reg Id while I am running your demo app. I want to send notification to my application users when created a new Events, Can u please help me to integrate your code in my app?
Have you check all necessary thing like manifest permissions? and You are using mobile device instead of emulator ? and have you created your own project on Google Developer and change project-key with yours?
Yes, I have checked everything what you are asking me, Is it possible to send notification to multiple users? I am using Emulator only not a mobile. Can you please come to chat? [email protected] this my mail ID.
Please use mobile device instead of emulator, because we can't guaranty its give you reg-id. And yes I have messaged you check your gtalk.
Hello Manish .....
I just download the whole source code to see how it works. I've use my sender ID and uploaded the GCM.php file on my server. But when i run the app it just give me a screen tell " RegId = "
Any Idea why so ?
Are you using mobile phone? And please see log cat. may be there correct reg-id. And please try 1-2 time may be in first time we did not reg-id.
Can we send notification to IPHONE from android? This is, if my application installed in IPhone means, the notification will send or not?
No dear you can't send notification to IPHONE from android device. You should use APNS(apple push notification services) for that.
Is it any possible to send notification to IPhone device through this code? I can send notification to Android Mobiles.
See dear both are competitor and they will not allow for messaging between each other. write web-service in php and use GCM for android and APNS for iphone and send push message from php server. I think this is the best way..
when im trying to import this app zip its telling no projects are found to import. could you please solve this problem?
advance thanks for solving this
Don't import, create new project from exiting code.
Hii Manish,,Great thanks for this tutorial
your welcome dear!
Hii Manish,Thanks for saving My Time......Great Work
Thanks & your welcome!
Hello Manish the demo works fine on my device but all I see is the regID. How can i get to see the messege "Hi Minash"
Hi Manish,
I am following this tutorial, I am able to get reg Id for android emulator in which I have configure google account, so my android app side is ok, but to register application server i.e tomcat to c2dm i am using java REST web service in place of your php web service calling. Here from web service i am getting 401 response code and not getting push message from c2dm.
I have changed your web service calling line i.e String url = "?" + "®ID=" + regId; r with my webservice calling i.e String url = "?" + "®istrationid=" + regId;
and web service is code is as follows:
@Path("/registertogoogle")
@GET
@Produces("application/json")
public String registertogoogle(@QueryParam("registrationid") String registrationid)
{
System.out.println(" register google:"+registrationid);
//GetAuthenticationToken.setAuthentication();
String auth_token="key=AIzaSyB6w2Acf4C3DN2IPefgXd-etU9SQqpzuAo";
//"key=AIzaSyB6w2Acf4C3DN2IPefgXdetU9SQqpzuAo";//ServerConfiguration.getAUTHENTICATION_TOKEN();
System.out.println("authtocken:"+auth_token);
JSONObject jsonObject = new JSONObject();
try {
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID).append("=")
.append(registrationid);
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=")
.append("0");
postDataBuilder.append("&").append("data.payload").append("=")
.append(URLEncoder.encode("This works fine", UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
// Hit the dm URL.
URL url = new URL("");//");
HttpsURLConnection
.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
conn.setRequestProperty("Authorization", auth_token);//"GoogleLogin auth=" +
System.out.println("Connectopn:"+conn.toString());
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
System.out.println("responsecode:"+responseCode);
jsonObject.put("responsecode",responseCode);
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject.toString();
}
private static class CustomizedHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
I have searched for 401 error code it's about authentication but not able to get exact solution to fix this issue, could please give your suggestion!!!!!
Sorry Dear i have no more idea about web-services so I can't say anything. well error 401 means "Authorization Required error" That mean your server or Google server some where authentication is required.
I have download this code from this link . But when I import this project in eclipse . It will not import and error is that "No projects are found to import". give me solution ?
Please go through file menu and and create new project using exciting code.
Hi Marnish,
Nice tutorial and I have copied your source code in my apps and it works. However, i have little problem.
It seems I have got the registration ID but I in the app, it always shows "RegId=", however, i can see i have got the id in the cat log:03-29 19:06:41.241: I/===GCMIntentService===(7156): Device registered: regId = APA91bFFkVQMPl5SAQtofT-KXu5OwsU7sY2dFfRs5P0PyGFrjMxkwjr3k38M5C_k7as71bqEkYzP6sHSDVo0R9qqZ4Qsj0z2vIO7kPsbX77ta20nYa2HH3aBy-gnb4WChJKaNrC1R2hF0M3fwF_kMkMcsR2vqJFfKA
But in the status log, it create error:
03-29 19:06:42.151: D/****Status Log***(7156): Webservice: {"multicast_id":6265367446240819368,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MissingRegistration"}]}
03-29 19:06:42.191: E/ViewRootImpl(7156): sendUserActionEvent() mView == null\
could you please help me? thanks!!
Please add this line inside onPostExcute() method -
mDisplay.setText("RegId=" + regId);
Part - A
Number : 8
what i add in Accept requests from these server IP addresses:???
i can not get RegId now .
i change SenderID in Java class and API key in PHP
In my case, 9 out of 10 times sendIdOnOverServer has been executed before GCMRegistrar returns an ID. Logcat shows one second difference between sending ID and GCMBaseIntent.handleregistration. How to avoid empty RegId strings?
Peet
can u please give the gcm server code using java
Hi ,.
You need to use-
long diff=date2.getTime()-date1.getTime();
Now you can change this long to minute hour according to your need.
import com.google.android.gcm.GCMBaseIntentService;
i am getting error on this import saying import cannot be resolved ,please help manish sir.
I need a simple application android, a user registers on my rest server and see the rest server response if the record was made by a push notification, have some sample code as well? thank you
i have an error that" import com.google.android.gcm.GCMBaseIntentService;" or GCMBaseIntentService, and
import com.google.android.gcm.GCMRegistrar; GCMRegister class file not found..please you have any solutions..
"Android Cloud to Device Messaging (C2DM) is deprecated. The C2DM service will be shut down completely on 10/20/2015. Currently, C2DM accepts no new users, and grants no new quotas. C2DM developers are strongly encouraged to move to Google Cloud Messaging (GCM). GCM is the next generation of C2DM."
have you any update for it?
Now Android is using "Google play services" for push messaging and they have full demo on android official website. please download from there.
Thank you!
please can you post that url @manish
Can you Please send the Code for Sending Notifications using Google Play Services @Manish
How can I send Notifications from Server Machine to Multiple Devices(Mobiles) for Single Click can you Please Explain I new to Android
how to send push notification everyday at particular time...?
in android using php..
Are you able to send a message on send button? If yes then just set a crone job. Search it on google -"How to create cron job using PHP?"
we are using button right now .. but i want to send automatically every 24hrs..
Thank you
i want to send automatically without using any button ...
Thank you
we are using button right now .. but i want to send automatically every 24hrs...
Using cron job you don't need button, it is same like Alarm Manager.
This comment has been removed by the author.
how can i create cron job ...?
how to send message to one device to anther device using GCM , if you have any code related to this please share with me
I don't think GCM support device to device messaging. You can use Bluetooth or WiFi for communication between 2 phone. Or you can use some logic like send message to server than server again redirect to 2nd device, it is same like how chat application does work. | http://www.androidhub4you.com/2013/04/google-cloud-messaging-example-in.html | CC-MAIN-2017-47 | refinedweb | 3,446 | 51.95 |
Hello Folks,
Finally… Step 6 of our “From The Ground Up” series. Today we we’ll finish the storage equation by assign Shared Storage using iSCSI for our Cluster Shared Volume and we will optimize our cluster.
If you feel like doing it and getting your hands on Hyper-V and SCVMM you can download Windows Server 2012 R2 and Hyper-V Server 2012 R2, setup your own lab and try it for yourself. I think I may have made you wait long enough. Right?
Cluster Shared Volumes (CSVs) in a Windows Server 2012 R2. To each of the cluster nodes in the cluster, the CSV appears as a consistent file namespace i.e. C:\ClusterStorage\Volume1.
CSVs provide a general-purpose, clustered file system
With the release of Windows Server 2012 R2, there have been a number of improvements in CSV.
Optimized CSV Placement Policies
CSV ownership is now automatically distributed and rebalanced across the failover cluster nodes..
In Windows Server 2012, there was only one instance of the Server service per node. Also, there was no monitoring of the Server service.
CSV Cache Allocation
Windows Server 2012 introduced a new feature known as CSV Cache. The CSV cache provides caching at the block level of read-only unbuffered I/O operations by allocating system memory (RAM) as a write-through cache. (Unbuffered I/O operations are not cached by the cache manager in Windows Server 2012.) This can improve performance for applications such as Hyper-V, which conducts unbuffered I/O operations when accessing a VHD. The CSV cache can boost the performance of read requests without caching write requests. By default, the CSV cache was disabled.
In Windows Server 2012 R2, you can allocate a higher percentage of the total physical memory to the CSV cache. In Windows Server 2012, you could allocate only 20% of the total physical RAM to the CSV cache. You can now allocate up to 80%.
Increasing the CSV cache limit is especially useful for Scale-Out File Server scenarios. Because Scale-Out File Servers are not typically memory constrained, you can accomplish large performance gains by using the extra memory for the CSV cache. Also, in Windows Server 2012 R2, CSV Cache is enabled by default.
Let get it configured. VMM assigns an iSCSI LUN that was created earlier to the cluster nodes to provide shared storage. VMM manages the iSCSI connectivity between the hosts and the iSCSI SAN through multiple sessions, as well as configuring the LUN correctly. The files of a clustered VM would be hosted on this SAN and accessible by both node.
Assign Shared Storage using iSCSI
1. In the Virtual Machine Manager Console select the Fabric workspace, in the Storage node, select Classification and Pools.
2. From the central pane, expand Bronze Tier, then expand iSCSITarget: DC01: C:, then select CSV01. On the upper ribbon, select Allocate Capacity.
3. In the Allocate Storage Capacity window, click Allocate Storage Pools. In the Allocate Storage Pools window, under Available storage pools, select iSCSITarget: DC01: C:, click Add, and then click OK.
4. In the Allocate Storage Capacity window, click Allocate Logical Units. in the Allocate Logical Units window, under Available Logical units, select CSV01, then click Add, and then click OK.
5. In Allocate Storage Capacity window, click Close.
6. In the Fabric workspace, expand Servers, and then click All Hosts. Right-click HYPER-V01, and click Properties. Click the Storage tab, click Add, and then select Add iSCSI Array.
7. In the Create New iSCSI Session window, select DC01 from the Array dropdown, and then click
Create.
8. In the Hyper-V01 Properties window, click OK. and repeat steps 6 to 7 for Hyper-V02.
9. Under All Hosts, right click CLUSTER1, and select Properties. Click the Shared Volumes tab, and then click Add.
10. In the Add Cluster Shared Volume window, select CSV01. In the Volume Label field, type CSV01, click the boxes for Quick Format and Force Format, and then click OK.
11. In the CLUSTER1.contoso.com Properties window, click OK. VMM will then assign the LUN to both nodes in the cluster, format the volume, convert it to a Cluster Shared Volume, and make it available for placement of virtual machines.
Optimize a Cluster
1. Open the Virtual Machine Manager Console. select the Fabric workspace, expand Servers, right-click All Hosts, and select Properties.
2. In the All Hosts Properties window, click the Host Reserves tab. ensure that the Use the host reserve settings from the parent host
group box is unchecked, and change the Memory settings for Unit to % and for Amount to 5.
Since the Hyper-V hosts in this lab environment only have 2GB RAM, the Memory setting needs to
be set lower to ensure that a VM can be deployed.
3. Click the Dynamic Optimization tab. slide the Aggressiveness slider to High. Aggressiveness affects how evenly distributed the VMs are across the different hosts. An aggressively balanced cluster will live migrate VMs more frequently to ensure that a similar amount of host resources are used
on each cluster node.
4. Select the box for Automatically migrate virtual machines to balance load at this frequency (minutes) and type 5 in the box.
5. Select the Enable power optimization box, and then click Settings. Review the default threshold values. Under Schedule click one of the blue squares between 8am and 6pm and Monday to Friday. The square will turn white when clicked, to indicate no power optimization will operate during those times. By pressing the keyboard arrow keys and the space bar, the squares can be changed. Change a few of these squares, and then click OK.
6. Back on the All Hosts Properties window, click OK to close the window.
Our cluster is UP! Optimized! and ready to accept virtual machines….
you can use the recipe in my “From The Ground Up” series to setup your own cluster in a lab or in production if you want. You wont regret it.
Next week, we build on top of this cluster and start looking at Cluster Patching ( I know, I said in the last post that we were going to do that today, but this post is long enough. Some of you are probably already sleeping…). We will look at creating a Generation 1 VM & Generation 2 VM, create a VM with PowerShell, (so you can automate your environment).
But for now… I need some sleep.
Cheers!
Pierre Roman | Technology Evangelist
Twitter | Facebook | LinkedIn
Thank you Mr. Pierre. Very very good Hyper-V series. | https://blogs.technet.microsoft.com/canitpro/2014/02/19/hyper-v-clustering-resiliency-step-6-clustered-shared-volume-optimize/ | CC-MAIN-2017-09 | refinedweb | 1,093 | 65.62 |
brian kennemer endlessly obsessing about project server, so that you don't have to
B. :-)
Just in case mine is the only Project blog you read, in which case you should really expand your blogroll by the way, here is an invitation to join the Technical Preview for the next version of Project and Project Server. :-)
_________________________________
Final call to those wishing to have access to the Microsoft Project 2010 client and Microsoft Project Server 2010 Technical Preview.).
There is only one invitation per..
See
This '”contains /”. Both of these give you an error when you try to save your filter.
What you can do is test to see if the value in the date field is greater than 1/1/1984. If it is greater than 1/1/1984 then the field contains a valid date.
So “is greater than 1/1/1984” will return only rows where the date value is NOT “NA”. The hard part is that you cannot use this idea to have a filter only show rows there there is NOT a date. The filtering mechanism does not seem to understand the idea of NA.
So the workaround for this is to do a ‘does not contain’ filter for a character that you know will always be in your dates but NOT the forward slash character (which throws an error.) If your dates for this field will always be in this century and you always use regional settings that show four digit dates then you can use this filter:
“does not contain 2”
This filter will return all rows that do not have a date in them if you use 4 digit years and your dates are always greater than 12/31/1999.
I hope this helps. Sorry I deleted your comment Santhiya. :-)
Here
OK as nerdy things go I’m pretty sure a 4 day conference about Project Server ranks right up there. Maybe not as nerdy as Blizzcon but for sure more nerdy than Comdex. Of course I’m using ‘nerd’ in its most complimentary sense. :-)
September 14-17 2009 in Phoenix. The Project Conference is THE place to be to learn from and rub elbows with all the best minds in the Project\Project Server\Portfolio Server universe. From the designers, the developers, testers, support pros, Microsoft Consulting Services on the consulting and implementation side, as well as the many GREAT partners providing addins, training and top notch deployment consulting…everyone is represented.
It is going to be a huge geek-out that is sure to answer all your questions about this version and the next! :-)
After having tested and found what I think are good settings for my screencasting I would like to gather suggestions for topics to cover.
Im thinking of a variety of topics ranging from beginning user tips around using Project Standard\Professional (creating views, setting baselines, using Usage views to look at and edit time scaled data) all the way up to more advanced things like Data Analysis views, security model ins and outs and resource management.
Please email me with any ideas.
OK. I’m learning how to use encoder to manipulate things like viewer size and whatnot. Sadly, it does not fix how freaked out I am when I know I’m being recorded. So you will have to put up with some “UMs and ERRs” in this one (and likely for a while until I become used to this recording thing.) :-)
I think this size will allow decent viewing with the embedded player without having to go full screen. Let me know.
Glenn Alleman has a great post here asking the question “If I'm Doing Project Management Right am I Agile?” and my answer is a resounding PROBABLY!!! :-)
I have been thinking this same thing since way back in 2004 when I posted about an article I saw about agile methods. My post was called “Agile Methods: Based on False Assumptions?” In it I talked about how many of the points the author was making about what it called “Traditional Management” was really just bad management. This was at a time when I was on some email lists that talked about PM methods and I was getting the feeling that Agile had been created by a group of people that had worked for the WORST PMS EVER. The stories they told and the processes they talked about were not the PM I understood and practiced. It was some horrible torture method designed by people that did not like software developers. I started to feel like the Agile community was a support group for abused software developers. The hard part was that they were talking about “Project Managers” as if they were an interchangeable set of identical parts” (IRONIC since that was one of the main accusations the agile community was making about how PMs saw software developers.)
That said I don’t think that good project management and Agile methods are a 100% overlap I do think that if you are doing project management correctly and the methods you are using in the management of your project are well fit to the particular project you are managing then what you are doing will NOT be the kind of PM that the agile community rails against. So for the most part the answer to Glenn’s question is YES. :-)
There is a new version of the help file that contains all the Project Server technical articles. Great if you need to review one while you are away from your internet connection.
If you are doing Project Server development using the PSI then you NEED to check out what Colby Africa is doing with mpFx. This is a set of class libraries that simplifies the development of PSI code. It reduces the number of calls you need to make to do things like create projects, assign resources, create tasks, etc.
This is what is required to create a project and wait for the queue job to finish:
1: namespace Microsoft.SDK.Project.Samples.QueueCreateProject
2: {
3: class Program
4: {
5: [STAThread]
6: static void Main(string[] args)
7: {
8: try
9: {
10: const string PROJECT_SERVER_URI = "h//ServerName/ProjectServerName/";().Replac", ""); \r\n";
50: for (int i = 0; i < errors.Length; i++)
51: {
52: errMess += "\n" + ex.Message.ToString() + "\r\n";
53: errMess += "".PadRight(30, '=') + "\r\nPSCLientError Out("Er " + errMess);
71: }
72: catch (Exception ex)
73: {
74: Console.ForegroundColor = ConsoleColor.Red;
75: Console.WriteLine("Er " + " + jobId + ".\r\n" + xmlError));
119: }
120: else
121: {
122: Console.WriteLine("Job St " + jobState + " Job " + jobId);
123: Thread.Sleep(QUEUE_WAIT_TIME * 1000);
124: }
125: }
126: }
127: while (!jobDone);
128: }
129: }
130: }
Here is the same code("h//epm2007demo/pwa",: }
32 lines of code as opposed to 130! :-)
Given the season I have started thinking about what I’m thankful for. Here is my list of a few things I am thankful for this year:
I know what you are saying “No way, how could they do it?” But it is all right there. It slices, it dices it makes thousands of julienne fries. But it also lets you have every technical document on Project Server 2007 in one place that you can search. It is amazing. NOW how much would you pay. OK anyway… this is pretty cool and you should download it right now. Tech Docs in a Single File
Now when I downloaded it I got a small issue where it would not show me any of the content. I’m not sure if this is an issue based on my OS (I’m running Windows Server 2008 on my laptop) but here is the fix. If you right click on the .chm file and then hit Properties you may see a button that says “Unblock” if you see it then click it and then you will be able to see the content of the file.
In the past few weeks I have seen a ton of questions floating around about users of project management systems wanting to see reporting showing resource capacity vs. demand. Now you might be saying “But Brian, that is pretty common. Doesn’t EVERYONE want this kind of data from their PM system?” to which I would reply “Certainly, but these requests were different in that they all wanted to see it for time periods going out as far as 2 years into the future.” My question is what is someone going to do with a comparison between demand (scheduled work) and availability that far into the future? The instant answer I always get is that they want to see how the current load of projects scheduled is placing demand on their resources and that is a good answer. But in my opinion most organizations are just not good enough at scheduling and estimating and forecasting to make schedule data that far into the future of a quality that would support any real decision making around demand\capacity problems. Schedules are hard enough to get accurate for the next 2 months let alone the next 2 years.
There are industries or environments\situations where the type of projects being done are easy to estimate because they have a high similarity with projects that have already been done but for the most part capacity\demand data derived from project schedules should be looked at as ‘fuzzy’ if the time period of the data is farther out than a few months and even fuzzier if it is more than a year out.
There are decisions that can be made based on this data but they should be made with the knowledge that those numbers could swing wildly in some cases depending on changes to the project as it moves forward. The adage that some data is better than no data holds true for the most part but ‘some data’ that is highly suspect but still used in the decision making process as if it was certain is worse than no data.
When you are looking at data that depends on the quality of your schedule estimates and project WBS you need to think about that quality when you make decisions based on that data. Where are those estimates coming from? Are they top-down estimates (like many that are that far out into the future) or are they bottoms-up estimates coming from the resources that will do the work (hard to do when the tasks in question are months or even over a year in the future?
There can be confusion among those deploying Project Server about if they need to define and use an RBS as part of their security structure. There is lots of information and a lot of opinions. Here is more information and one more opinion. Hopefully one that rings true in your experience.
In my experience the use of an RBS is only needed if you need to limit access to project or resource data based on some kind of structure. This structure is almost always an organizational structure.
For example if you need to make sure that a Project Server user who sits at 1.2 on the org structure can ONLY see Projects that are managed by or worked on by users at or below 1.2 or a user who sits at Organization 2 cannot see Projects inside Organization 1 then you need to have an RBS in place.
If your security needs are based on role rather than on organization then your don’t need RBS. An example of this is when Project Managers need Write access to their own projects and read access to all other projects and other roles such as managers need read access to all projects. So if the organization a user is in does not have a direct impact on the projects or resources they can see then you don’t need an RBS.
For sure there are shades of several colors here but this is the gist. I look forward to your comments. | http://blogs.technet.com/projectified/ | crawl-002 | refinedweb | 2,001 | 68.3 |
Opened 5 years ago
Closed 5 years ago
Last modified 5 years ago
#25685 closed Bug (fixed)
Model.delete() issues extra queries after a deferred queryset
Description (last modified by )
Consider the following models
from django.db import models class ModelA(models.Model): a = models.CharField(max_length=15) class ModelB(models.Model): fk = models.ForeignKey(ModelA)
and the following test
from django.test import TestCase from .models import ModelA class DeferProblemTestCase(TestCase): def test_defer(self): a = ModelA.objects.create(a='test') with self.assertNumQueries(2): a.delete() unrelated_qs = list(ModelA.objects.defer('a')) # let's try once again a = ModelA.objects.create(a='test') with self.assertNumQueries(2): a.delete()
The above test fails under django 1.8.6, as the second call to
.delete() will produce 3 queries instead of 2. It seems django somehow caches the deferred model and tries to delete any related ModelB records twice. Except from the overhead, this can lead to random test fails based on the execution order.
Change History (12)
comment:1 Changed 5 years ago by
comment:2 Changed 5 years ago by
comment:3 Changed 5 years ago by
comment:4 Changed 5 years ago by
I don't think back porting should apply here since this isn't a bug in a new feature.
comment:5 Changed 5 years ago by
I came up across this issue while upgrading from django 1.7 to 1.8. I can confirm the above test works in 1.7.XX and the issue was introduced in 1.8. But since I'm not familiar with the release cycle I don't know if that would justify a back port. Thanks anyway!
comment:6 Changed 5 years ago by
comment:7 Changed 5 years ago by
As far as I can tell, there isn't a patch to review yet.
This has been fixed in the process of solving #18012 (8bdfabed6563f2ae136ad43e05bb254c9c15811a).
I guess adding this regression test case to
tests/deletewouldn't hurt at this point. | https://code.djangoproject.com/ticket/25685 | CC-MAIN-2020-24 | refinedweb | 333 | 69.48 |
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode.
Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript).
Hi~I recently notice a fatanstic bar chart data comparison video in youtube,below is the video link:
link text
i want to create a 3D version of this kind of data comparision video by python ,so that i can batch generate animation by easily input data
For example i have a data named :Four companies profit from 2000 to 2010
and i want to create 4 bar chart cubes respectively ,1th key represents 2000 year ,25th to 2001 year and so on ,each cube Y size key-value is the profit respectively ,in 1th key,A company Y size is 398 ,B 400 ,C 500,D 600, and in 25th ,each Y size value is the profit of 2001.
This is the simple demonstration i make in C4D by hand
i am crazy to achieving it by python,easily input data ,automatically create cube or cylinder and generate key and value and changeable number ,this is a powerful tool,well,i know definitely it is not easy
it is a big project !!!
**so i just want to ask the possibility of this code
if it can be achieve in C4D by python ?
could you please tell me the probable direction or the python module i should to use ?
if you can demonstrate with some basic code ,i would be grateful !
Thanks ~
**
i
Hi @Joe132 welcome in the plugincafe community.
So there is nothing in the Cinema 4D API that could help you to import this kind of data.
However, python lets you the possibility to import natively CSV data which can be normally exported from any software. See How to read and write CSV files.
Once you have done it you need to create an object. To do so you have to creates a new instance of BaseObject like so
If you open the python console and drag a cube, press enter you will see the object is a BaseObject one. For more information see Python Console Manual then for a list of ID or object, either you write the ID that was given while drag and drop either you can look at this page Object Type.
Something like:
import c4d
# Creates the object in memory
cube = c4d.BaseObject(c4d.Ocube)
# Inserts the object into the document
doc.InsertObject(cube)
# Pushes an update event to Cinema 4D
c4d.EventAdd()
Then for the animation, I suggest you read to this topic from yesterday where you can find valuable information Beginner:How can I set a key-frame and value to a cube by python?
If you have any questions, do not hesitate.
Cheers,
Maxime.
@m_adam
Thank you very much ! it is certainly helpful !! | https://plugincafe.maxon.net/topic/11701/brainstorm-to-automatically-create-a-data-comparison-animation-by-python | CC-MAIN-2022-05 | refinedweb | 486 | 66.88 |
Convert a multibyte-character string into a wide-character string
#include <stdlib.h> size_t mbstowcs( wchar_t * pwcs, const char * s, size_t n );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The mbstowcs() function converts a sequence of multibyte characters pointed to by s into their corresponding wide-character codes pointed to by pwcs, to a maximum of n wide characters. It doesn't convert any multibyte characters beyond a NULL character.
This function is affected by LC_CTYPE.
The mbsrtowcs() function is a restartable version of mbstowcs().
The number of array elements modified, not including the terminating zero code, if present, or (size_t)-1 if an invalid multibyte character was encountered.
#include <stdio.h> #include <stdlib.h> int main( void ) { char *wc = "string"; wchar_t wbuffer[50]; int i, len; len = mbstowcs( wbuffer, wc, 50 ); if( len != -1 ) { wbuffer[len] = '\0'; printf( "%s(%d)\n", wc, len ); for( i = 0; i < len; i++ ) { printf( "/%4.4x", wbuffer[i] ); } printf( "\n" ); } return EXIT_SUCCESS; }
This produces the output:
string(6) /0073/0074/0072/0069/006e/0067 | http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.neutrino.lib_ref/topic/m/mbstowcs.html | CC-MAIN-2018-43 | refinedweb | 183 | 66.13 |
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
For example, the character ‘a’ (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
char is already an integer type in C++, and it gets automatically promoted to int. So you can use a character where you would otherwise use an integer. Conversely, you can use an integer where you would normally use a character, except you may need to cast it, as char is smaller.
In this case, the output operator << is overloaded to handle integer (outputs the decimal representation) and character (outputs just the character) types differently, so we need to cast it in both cases.
#include <iostream> int main() { std::cout << (int)'a' << std::endl; // prints "97" std::cout << (char)97 << std::endl; // prints "a" return 0; }
Content is available under GNU Free Documentation License 1.2. | https://tfetimes.com/c-character-codes/ | CC-MAIN-2021-49 | refinedweb | 172 | 50.57 |
Lack of Encapsulation in Addons
I first noticed a lack of good design in addon code when I started trying to tweak existing addons to be slightly different.
One of the stand out examples was a Threat Meter (you know which one I mean). It works well, but I felt like writing my own, to make it really fit into my UI, with as little overhead as possible. Not knowing how to even begin writing a Threat Meter, I downloaded a copy, and opened its source directory... to discover that the entire addon is one 3500+ line file, and 16 Ace.* dependencies.
When I had finished my Threat Meter, I had two files (170 lines and 130 lines), and one dependency (Dark.Core, which all my addons use). I learnt a lot while reading the source for the original threat meter - it is very customisable, is externally skinable, and has some very good optimisations in it. But it also has a lot of unused variables (which are named very similarly to used ones), and so much of it's code could be separated out, making it easier to modify by newer project members.
This set of observations goes on forever when concerning addons. The three main problems I see are:
- Pollution of the global namespace
- All code in one file
- No separation of concerns
All of this makes it harder for new developers to pick up and learn how to maintain and write addons. They are all fairly straight forward to solve problems, so lets address them!
Pollution of the Global Namespace
A lot of addons you find declare many variables as global so they can access them anywhere within their addon. For example, this is pretty standard:
MyAddonEvents = CreateFrame("Frame", "MyAddonEventFrame") MyAddonEvents:RegisterEvent("PLAYER_ENTERING_WORLD") MyAddonEvents:SetScript("OnEvent", MyAddonEventHandler) MyAddonEventHandler = function(self, event, ...) if event == "PLAYER_ENTERING_WORLD" then --do something useful end end
This is an example of poluting the global namespace, as now the entire UI has access to:
MyAddonEvents,
MyAddonEventFrame,
MyAddonEventHandler. This is very trivial to rewrite to not expose anything to the global namespace:
local events = CreateFrame("Frame") local handler = function(self, event, ...) if event == "PLAYER_ENTERING_WORLD" then --do something useful end end events:RegisterEvent("PLAYER_ENTERING_WORLD") events:SetScript("OnEvent", handler)
This version exposes nothing to the global namespace, and performs exactly the same function (you can even get rid of the
handler variable and just pass the function directly into
SetScript).
However, by writing your code like this, you can't access any of this from another file (either a lua file, or shudder a frameXml file), but using namespaces we can get around this limitation without polluting the global namespace.
Splitting into Separate Files
So, how to access local variables in other files? Well Warcraft addons come with a feature where all lua files are provided with two arguments:
addon and
ns. The first of these is a string of the addon name, and the second is an empty table. I almost never use the
addon parameter, but the
ns (or "namespace") parameter is key to everything.
You can access these two variables by writing this as the first line of your lua file:
local addon, ns = ... print("Hello from, " .. addon)
By using the
ns, we can put our own variables into it to access from other files. For example, we have an event system in one file:
eventSystem.lua
local addon, ns = ... local events = CreateFrame("Frame") local handlers = {} events:SetScript("OnEvent", function(self, event, ...) local eventHandlers = handlers[event] or {} for i, handler in ipairs(eventHandlers) do handler(event, ...) end end) ns.register = function(event, handler) handlers[event] = handlers[event] or {} table.insert(handlers[event], handler) events:RegisterEvent(event) end
Note how the
register function is defined on the
ns. This means that any other file in our addon can do this to handle an event:
goldPrinter.lua
local addon, ns = ... ns.register("PLAYER_MONEY", function() local gold = floor(money / (COPPER_PER_SILVER * SILVER_PER_GOLD)) local silver = floor((money - (gold * COPPER_PER_SILVER * SILVER_PER_GOLD)) / COPPER_PER_SILVER) local copper = mod(money, COPPER_PER_SILVER) local moneyString = "" local separator = "" if ( gold > 0 ) then moneyString = format(GOLD_AMOUNT_TEXTURE, gold, 0, 0) separator = " " end if ( silver > 0 ) then moneyString = moneyString .. separator .. format(SILVER_AMOUNT_TEXTURE, silver, 0, 0) separator = " " end if ( copper > 0 or moneyString == "" ) then moneyString = moneyString .. separator .. format(COPPER_AMOUNT_TEXTURE, copper, 0, 0) end print("You now have " .. moneyString) end)
A pretty trivial example, but we have managed to write a two file addon, without putting anything in the global namespace.
We have also managed to separate our concerns - the
goldPrinter does not care what raises the events, and the
eventSystem knows nothing about gold printing, just how to delegate events. There is also an efficiency here too - anything else in our addon that needs events uses the same eventSystem, meaning we only need to create one frame for the entire addon to receive events.
Structure
Now that we can separate things into individual files, we gain a slightly different problem - how to organise those files. I found over time that I end up with roughly the same structure each time, and others might benefit from it too.
All my addons start with four files:
- AddonName.toc
- initialise.lua
- config.lua
- run.lua
The toc file, other than the usual header information is laid out in the order the files will run, for example this is the file segment of my bags addon's toc file:
initialise.lua config.lua models\classifier.lua models\classifiers\equipmentSet.lua models\itemModel.lua models\model.lua groups\group.lua groups\bagGroup.lua groups\bagContainer.lua views\item.lua views\goldDisplay.lua views\currencyDisplay.lua views\bankBagBar.lua sets\container.lua sets\bag.lua sets\bank.lua run.lua
The
initialise lua file is the first thing to run. All this tends to do is setup any sub-namespaces on
ns, and copy in external dependencies to
ns.lib:
local addon, ns = ... ns.models = {} ns.groups = {} ns.views = {} ns.sets = {} local core = Dark.core ns.lib = { fonts = core.fonts, events = core.events, slash = core.slash, }
By copying in the dependencies, we not only save a global lookup each time we need say the event system, but we also have an abstraction point. If we want to replace the event system, as long as the replacement has the right function names, we can just assign the new one to the lib:
ns.lib.events = replacementEvents:new()
The sub namespaces correspond to folders on in the addon (much the same practice used by c# developers), so for example the
classifier.lua file might have this in it:
local addon, ns = ... local classifier = { new = function() end, update = function() end, classify = function(item) end, } ns.models.classifier = classifier
The config file should be fairly simple, with not much more than a couple of tables in it:
local addon, ns = ... ns.config = { buttonSize = 24, spacing = 4, screenPadding = 10, currencies = { 823, -- apexis 824, -- garrison resources } }
And finally, the
run.lua file is what makes your addon come to life:
local addon, ns = ... local sets = ns.sets local pack = sets.bag:new() local bank = sets.bank:new() local ui = ns.controllers.uiIntegration.new(pack.frame, bank.frame) ui.hook() --expose DarkBags = { addClassifier = ns.classifiers.add }
If you need to expose something to the entire UI or other addons, that's fine. But make sure you only expose what you want to. In the example above the
DarkBags global only has one method -
addClassifier, because that is all I want other addons to be able to do.
Wrapping Up
I hope this helps other people with their addons - I know I wish that I had gotten to this structure and style a lot sooner than I did.
There will be a few more posts incoming covering encapsulation, objects and inheritance in more detail, so stay tuned. | http://stormbase.net/2014/11/23/good-design-in-warcraft-addons/ | CC-MAIN-2017-17 | refinedweb | 1,291 | 53.92 |
I have having trouble trying to port our Excel Addin to Aspose.
I use data tables (list objects) in Excel 2007 in my attached workbook (See loanapplicationdata sheet).
I open the workbook, delete the listobject, create a new listobject to replace it and then loop through a ADO.NET datatable and put a new row in the listobject. However I cannot get this to work correctly in Aspose.
I try different variations using Aspose with no luck. I notice the passing an array into putvalue is not supported in Aspose? I kept getting system.object appearing in all the cells. I tried looping with a standard putvalue but it didn’t add it to the listobject. Thoughts?
Here is a snippet of some code I use for my current Excel 2007 add in. It works fine. Trying to convert to Aspose.
Dim TblLoanApplicantData As Microsoft.Office.Interop.Excel.ListObject=ws.ListObjects(“TblLoanApplicantData”)
TblLoanApplicantData.Delete()
ExcelHelper.InsertListObject(ws, dt, “TblLoanApplicantData”, ws.Range(“A1”), pBar.pgBar)
Public Shared Sub InsertListObject(ByVal ws As Excel.Worksheet, ByVal dt As Data.DataTable, _
ByVal tblName As String, ByVal location As Range, _
ByVal pBar As System.Windows.Forms.ProgressBar)
Globals.ThisAddIn.Application.ScreenUpdating = False
Globals.ThisAddIn.Application.DisplayAlerts = False
ws.Activate()
Dim rangeApplicant As Excel.Range = location
For iCol = 0 To dt.Columns.Count - 1
rangeApplicant(1, iCol + 1).value2 = dt.Columns(iCol).ColumnName
ws.ListObjects.AddEx(Excel.XlListObjectSourceType.xlSrcRange, ws.Range(location, location.Cells(1, dt.Columns.Count)), True, Excel.XlYesNoGuess.xlYes).Name = tblName
Dim rowIdx As Integer = 2
Dim colStart As Integer = 1
Dim colCount As Integer = dt.Columns.Count
For Each dr As DataRow In dt.Rows
Dim rowArray As Object = dr.ItemArray
ws.Range(ws.Cells(rowIdx, colStart), ws.Cells(rowIdx, colStart + colCount - 1)).Value2 = rowArray
rowIdx += 1
If Not (pBar Is Nothing) Then
pBar.Value += 1
End If
Globals.ThisAddIn.Application.DisplayAlerts = True
Globals.ThisAddIn.Application.ScreenUpdating = True
End Sub
What is your design pattern for working with listobjects for 2007 with your component?
Thanks
Robin
I have having trouble trying to port our Excel Addin to Aspose.
Hi,
<?xml:namespace prefix = o
Currently Aspose.Cells only supported to get/set picture and chart(line, column, pie, bar) shape to .xlsx format file. Other type of shapes such as listObject, button will be preserved when load and save the file, but cannot be accessed or added to the file. We are working on these features. Thank you for your patience.
This is definitely a setback. The major benefit of your component to us was the perceived ability to open an Excel file, replace some data and shoot it down to the customer. They would open it and the data in the listobject (or Table as Excel calls it in the UI) would be updated. Thus, all the charts and pivot tables would now show the latest data.
This allows us to create really cool excel files in advance that do advanced analysis on a set of data without have to regularly paste the data into a spreadsheet and email them back the new version. Here we can dump the data straight from a Datatable into the sheet and the other sheets would update thier charts automatically. We have created an excel add in to do this. However I have concerns about rolling out client side applications that need to communicate to a server to get the data and also have to be updated. It is a much more complicated process compared to having Aspose on the web server that can open a spreadsheet and dump data into a table.
Do you have time frame for this feature. I really want to stick with Aspose solutions as your Word component has been just great over the years.
Hi,
<?xml:namespace prefix = o
I checked your file, but could not find any listObject in it. Instead I found some autofilter that also can be dropped down, such as the autofilter in worksheet “TblLoanApplicantData” cell “A1”.
Do you need to change these autofilters or add some listObjects to the file?
Please give us more detail about your need, thank you.
Hi,
Sorry for my misreading. I look around your mail again, I guess you need to:
1. Delete the data table in sheet “LoanApplicationData”
2. Create a new data table named “TblLoanApplicantData” (same as the previous)
3. Fill the new data table with an ADO.NET datatable
<?xml:namespace prefix = o
Since currently Aspose.Cells do not support data table feature, you cannot delete or create a data table in Aspose.Cells. But if you do not need to change the table’s structure (such as table name, columns name and the range of table), I think you can reach you need by only changing the table’s cell’s data with Aspose.Cells.
Please consult the following code:
string infn = @"E:\test\before.xlsx";
string outfn = @"E:\test\before_out.xlsx";
Workbook book = new Workbook();
book.Open(infn, FileFormatType.Excel2007Xlsx);
Worksheet sheet = book.Worksheets["LoanApplicantData"];
// remove old datas
sheet.Cells.DeleteRows(1, 4151);
System.Data.DataTable dt = new System.Data.DataTable();
// todo: fill the datatable
// import the data table
sheet.Cells.ImportDataTable(dt, false, "A2");
book.Save(outfn, FileFormatType.Excel2007Xlsx);
Thank you
Everything seems fine with your code except, the range will change as the number of rows with vary with the parameters of the data range used to collect the row data.
That is why we use a data table rather than a range of rows. Because in the pivot tables and charts, we can reference a data table rather than a hardcoded range. That way the range can be a dynamic set of rows.
The data table on the sheet can be 4 rows or 40,000, the charts and pivot tables don’t care.
Your thoughts?
Hi,
<?xml:namespace prefix = o
It is suggested that you use named range instead of data table as the data source of pivot tables. So you can set the named range to new value with Aspose.Cells after you update the data source worksheet.
Please consult the following steps:
1. Create a template file
2. Define a name range “DataSourceLoanApplicantData” with “name manager” covering data table “TblLoanApplicantData”’s range
3. Create pivot table with name range “DataSourceLoanApplicantData” and set data option to “Refresh on open”
(Please check the attached file. I create a pivot table in worksheet “New_Ethnicity_pivot” with name range “DataSourceLoanApplicantData”in it.)
4. Open the template file with Aspose.Cells
5. Update data in worksheet “LoanApplicantData” or other worksheet containing data source (With Cells.DeleteRows() and Cells.ImportDataTable() methods)
6. Update the named range “DataSourceLoanApplicantData”’s refer range to new range
7. When the file is opened, pivot table in worksheet “New_Ethnicity_pivot” will auto refresh with the new data
The following code demos how to update a named range:
string infn = @"E:\test\ template.xlsx";
string outfn = @"E:\test\ template_out.xlsx";
Workbook book = new Workbook();
book.Open(infn, FileFormatType.Excel2007Xlsx);
Worksheet sheet = book.Worksheets["LoanApplicantData"];
sheet.Cells.DeleteRows(500, 4000);
// todo: fill the datatable
//System.Data.DataTable dt = new System.Data.DataTable();
//sheet.Cells.ImportDataTable(dt, false, "A2");
// update named range
Name r = book.Worksheets.Names["DataSourceLoanApplicantData"];
r.RefersTo = "=LoanApplicantData!$A$1:$V$500";
book.Save(outfn, FileFormatType.Excel2007Xlsx);
Thank youThank you
Try using newer Aspose.Cells APIs which allows you create and manipulate Tables/List objects from the range of cells. The following are the steps to create a table in an Excel (XLSX) file using Aspose.Cells for .NET:
- Load an Excel workbook or create a new one using Workbook class.
- Add data to the cells of the worksheet.
- Add a new ListObject to the worksheet.
- Set ListObject.ShowTotals property to true .
- Calculate the total and save the workbook as an Excel .xlsx file.
See the following code sample that shows on how to create a table in Excel worksheet.
e.g
Sample code:
// Instantiate a Workbook object that represents Excel file. Workbook wb = new Workbook(); // Get the first worksheet. Worksheet sheet = wb.Worksheets[0]; // Obtaining Worksheet's cells collection Cells cells = sheet.Cells; // Setting the value to the cells Aspose.Cells.Cell cell = cells["A1"]; cell.PutValue("Employee"); cell = cells["B1"]; cell.PutValue("Quarter"); cell = cells["C1"]; cell.PutValue("Product"); cell = cells["D1"]; cell.PutValue("Continent"); cell = cells["E1"]; cell.PutValue("Country"); cell = cells["F1"]; cell.PutValue("Sale"); cell = cells["A2"]; cell.PutValue("David"); cell = cells["A3"]; cell.PutValue("David"); cell = cells["A4"]; cell.PutValue("David"); cell = cells["A5"]; cell.PutValue("David"); cell = cells["A6"]; cell.PutValue("James"); cell = cells["B2"]; cell.PutValue(1); cell = cells["B3"]; cell.PutValue(2); cell = cells["B4"]; cell.PutValue(3); cell = cells["B5"]; cell.PutValue(4); cell = cells["B6"]; cell.PutValue(1); cell = cells["C2"]; cell.PutValue("Maxilaku"); cell = cells["C3"]; cell.PutValue("Maxilaku"); cell = cells["C4"]; cell.PutValue("Chai"); cell = cells["C5"]; cell.PutValue("Maxilaku"); cell = cells["C6"]; cell.PutValue("Chang"); cell = cells["D2"]; cell.PutValue("Asia"); cell = cells["D3"]; cell.PutValue("Asia"); cell = cells["D4"]; cell.PutValue("Asia"); cell = cells["D5"]; cell.PutValue("Asia"); cell = cells["D6"]; cell.PutValue("Europe"); cell = cells["E2"]; cell.PutValue("China"); cell = cells["E3"]; cell.PutValue("India"); cell = cells["E4"]; cell.PutValue("Korea"); cell = cells["E5"]; cell.PutValue("India"); cell = cells["E6"]; cell.PutValue("France"); cell = cells["F2"]; cell.PutValue(2000); cell = cells["F3"]; cell.PutValue(500); cell = cells["F4"]; cell.PutValue(1200); cell = cells["F5"]; cell.PutValue(1500); cell = cells["F6"]; cell.PutValue(500); // Adding a new List Object to the worksheet Tables.ListObject listObject = sheet.ListObjects[sheet.ListObjects.Add("A1", "F6", true)]; // Adding Default Style to the table listObject.TableStyleType = Tables.TableStyleType.TableStyleMedium10; // Show Total listObject.ShowTotals = true; // Set the Quarter field's calculation type listObject.ListColumns[1].TotalsCalculation = Tables.TotalsCalculation.Count; // Save the Excel file. wb.Save("Excel_Table.xlsx", SaveFormat.Xlsx);
For further reference, learn more about working with tables in Excel worksheets.
We also recommend you to have a look at the documentation of Aspose.Cells for .NET to learn the advanced features for manipulation of Excel files. | https://forum.aspose.com/t/listobject-with-aspose/91748 | CC-MAIN-2022-21 | refinedweb | 1,667 | 53.98 |
Opened 8 years ago
Closed 8 years ago
Last modified 8 years ago
#2540 closed bug (fixed)
[Text.Regex] incorrect word boundary ("\\b") substitutions. Bug in regex-compat's subRegex handling of BOL flags.
Description
Consider:
import Text.Regex main = putStrLn $ subRegex (mkRegex "\\b(.)") "abcdef" "|\\1"
This outputs "|a|b|c|d|e|f", while it really should output "|abcdef" (at least according to Perl and Ruby).
Change History (6)
comment:1 Changed 8 years ago by dons
comment:2 Changed 8 years ago by igloo
- difficulty set to Unknown
- Milestone set to Not GHC
- Owner set to TextRegexLazy@…
I'd expect it to do the same things as sed:
$ echo "abcdef" | sed -r 's/\b(.)/|\1/g' |abcdef
i.e. it looks like a bug to me.
Looks like the problem is how subRegex recurses on what comes after the match (trail):
case matchRegexAll regexp inp of Nothing -> inp Just (lead, match, trail, groups) -> lead ++ lookup match repl groups ++ (subRegex regexp trail repl)
Christopher, I've assigned it to you as the regex libraries maintainer.
comment:3 Changed 8 years ago by ChrisKuklewicz
- Architecture changed from x86_64 (amd64) to Multiple
- Keywords regex-compat added
- Operating System changed from Unknown to Multiple
- Owner changed from TextRegexLazy@… to ChrisKuklewicz
- Status changed from new to assigned
- Summary changed from [Text.Regex] incorrect word boundary ("\\b") substitutions to [Text.Regex] incorrect word boundary ("\\b") substitutions. Bug in regex-compat's subRegex handling of BOL flags.
Ah bollocks, there is a bug here but it is subtle. The above complaint is actually to do with the lack of support for GNU extensions to regex/sed. The regex-posix library expects to implement just the POSIX regular expressions and none of the different extensions. This is also consistent with the BSD sed.
The actual c-library calls in regex-posix are regcomp and regexec (and regfree, regerror).
In GNU regex/sed (I tested version 4.1.5 on linux) the \b means a word boundary. I assume that this is also the case in Perl and Ruby. Thus \b matches only at the front of the abcdef word for these systems.
In POSIX sed the \b is not recognized as a known escape, but is accepted as a literal b. So it matches the bc in abcdef and is replaced by |c.
On Mac OS 10.5.4 the equivalent to -r is -E and then:
$ echo "abcdef" | sed -E 's/\b(.)/|\1/g' a|cdef
With ghc version 6.8.3 on OS X I get the same answer as POSIX sed
Prelude> :m +Text.Regex Prelude Text.Regex> subRegex (mkRegex "\\b(.)") "abcdef" "|\\1" "a|cdef"
On linux I can reproduce the bug report:
Prelude Text.Regex> subRegex (mkRegex "\\b(.)") "abcdef" "|\\1" "|a|b|c|d|e|f"
Note that man 3 regexec and man 7 regex on linux are not describing the \b behavior. It is mis-documented.
But there is a further problem: Change \b to ^ and it is clear that Text.Regex is getting the wrong answer on all systems. On OS X:
$ echo "abcdef" | sed -E 's/^(.)/|\1/' |abcdef Prelude Text.Regex> subRegex (mkRegex "^(.)") "abcdef" "|\\1" "|a|b|c|d|e|f"
So there is a bug to fix with respect to ^. Fixing this may also accidentally fix the \b handling on GNU systems. I thought I had added enough 'execNotBOL' (REG_NOTBOL) flags to cover all these cases, but regex-compat's subRegex is not clearly not clever enough.
I will update this bug report when there is a fixed version to announce.
comment:4 Changed 8 years ago by ChrisKuklewicz
- Resolution set to fixed
- Status changed from assigned to closed
I have uploaded regex-compat 0.92 and regex-posix 0.93.2 to hackage (they are also in darcs). These contain two changes:
regex-posix's Wrap.hsc defines _POSIX_C_SOURCE to (untested) cause the gnu systems to stop trying to handle non-posix escapes like \b.
regex-compat's splitRegex and subRegex are changed to use matchAllText and not to use recursion. This may (untested) create differences in behavior compared to the old version, including laziness.
Both require the newer regex-base to compile and run, the current version of which is 0.93.1 at this time.
comment:5 Changed 8 years ago by simonmar
- Architecture changed from Multiple to Unknown/Multiple
comment:6 Changed 8 years ago by simonmar
- Operating System changed from Multiple to Unknown/Multiple
Inconsitency between the regex.h C library, and PCRE? | https://ghc.haskell.org/trac/ghc/ticket/2540 | CC-MAIN-2016-40 | refinedweb | 750 | 76.01 |
SOLID Design Principles
Written with reference to Clean Architecture: A Craftsman’s Guide to Software Structure and Design and of course, The Internet.
Clean code is the foundation of good software. We can imagine code as bricks and software architecture as the architecture of the building we are trying to construct. The architecture of the building isn’t important if the bricks aren’t well made. On the other hand, even if you are given well made bricks, you can still end up with a messy structure. This is then where the SOLID Principles come in.
The SOLID Principles teaches us to organise our functions and data structures into classes (coupled groupings of functions and data) as well as how to connect these classes.
In short, SOLID is ….
Single Responsibility Principle. Each software module has one, and only one, reason to change.
Open Closed Principle. Software systems must be designed such that they allow for the behaviour of those systems to be changed by adding new code rather than changing existing code.
Liskov Substitution Principle. In order to build software systems from interchangeable parts, these parts must adhere to a contract that allows those parts to be substituted one for another.
Interface Segregation Principle. Splits unnecessarily large interfaces into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them and avoid depending on things they don’t use. Avoid God Classes.
Dependency Inversion Principle. The code that implements high level policy should not depend on the code that implements low level details. Details should depend on Policy. Depend on abstractions, not on concretions.
Single Responsibility Principle …
A module should have one, and only one, reason to change.
A common reason for software to change is due to a change in requirements either from users or stakeholders. Hence, in another way of phrasing, a module should be responsible to one, and only one actor.
To understand it better, lets consider the following situation where the SRP has been violated.
Imagine we have an Employee class from a payroll application with 3 methods: calculatePay(), reportHours(), and save().
Following our definition, we can see that the above class violates the SRP. This is because the three methods placed within it are responsible for 3 different actors, which are the CFO, COO and CTO respectively.
- calculatePay(): Specified by the accounting department which reports to the CFO.
- reportHours(): Specified and used by the human resources department, which reports to the COO.
- save(): Specified by the database administrators who report to the CTO.
You might think, why might this be an issue?
There may be a scenario whereby the different methods, A and B, share a common underlying algorithm. The developer might then create another private method C to house this common algorithm and C will be used by A and B. Suppose that one of the client, perhaps the CFO, decides to modify the algorithm used in method A. To accommodate the change in the algorithm, the developer will then have to modify C. While everything works well for the CFO after the intended change, the CTO which uses method B might be unaware of the changes made to C. Hence, a problem arises.
Furthermore, if we have a class being used by different actors, then at any point where the two different actors have to make changes to the class, there will be a need for extra coordination between the two actors to ensure that any of the changes made by one of them do not affect the other.
Solution:
There are more than 1 solution to this problem.
One of the solution is to separate the data from the functions. We will construct a class for each of the three actors to contain the source code for their respective functions. These three classes will then share access to the data structure class, EmployeeData, which does not contain any methods.
The downside is that there will now be 3 classes for developers to instantiate. But, fret not! We can make use of the Facade pattern to create a single Facade class for all the actors to interact. According to the method called, this Facade class will then instantiate and delegate work to the respective actual classes containing the required functions.
Open-Closed Principle …
A software artifact should be open for extension but closed for modification.
Consider this….
Lets say we have a system to display financial records summary. Negative numbers are rendered in red and the page is scrollable.
An addition in requirement is requested whereby the same information is to be printable in black and white. The pages should have pagination with the appropriate page headers, footers and labels. Negative numbers should be surrounded by parentheses.
Due to this requirement addition, we will need to make changes to the code. Ideally we want to have 0 change.
To do so, we will need to separate the things that change for different reasons (SRP), then organise the dependencies between those things properly (Dependency Inversion Principle).
After we apply the SRP, we may come up with the following data flow. We have some procedure responsible for analysing the financial data and producing reportable data, which is then formatted by the two different reporter processes.
The key point to note here is that generating the report involves two separate responsibilities: calculation of the reported data, and the presentation of the data into web and printer friendly format.
Hence, we need to organise the code dependencies to ensure that changes to one of those responsibilities do not cause changes in the other. The new organisation should also make sure that the behaviour can be extended without modification of the existing code.
We do so by separating the processes into classes, and separating those classes into components.
Here we have the components: Controller, Interactor, Database, Presenter and Views.
An arrow pointing from class A to class B means that the source code of A mentions B but B does not know A.
The arrows points towards components that we want to protect from change. If A should be protected from changes in B, then B should depend on A. B should point to A. We want to protect the Controller from changes in the Presenters. We want to protect the Presenters from changes in the Views. We want to protect the Interactor from changes in everything.
Why is the Interactor protected from everything? It is because it contains the business rules and hence has the highest level policies of the application. On the other hand, Views are the lowest level concept and are the least protected.
This is how the OCP works at the architectural level. Architects separate functionality based on how, why, and when it changes, and then organise that separated functionality into a hierarchy of components. High level components are protected from changes in lower level components.
Another good article:
Liskov Substitution Principle …
Functions that are written to expect base classes must be able to use objects of derived classes without knowing it.
At the core, we can use LSP to help us in deciding between using inheritance or composition as our solution.
To achieve this, the following is what we need to ensure that we
- Implement no more stringent restrictions on input parameters than the parent class.
- Have a use case for every method present in the parent base class.
- At the very least, apply the same rules to all output parameters as the parent class.
Consider …
the following example code:
public class Bird{
public void fly(){}
}
public class Duck extends Bird{}
The duck can fly because it is a bird. However, what if we have another type of bird, the Ostrich, which is not supposed to have the flying capability:
public class Ostrich extends Bird{}
This means we are breaking the LSP principle.
In this case, we are better off using object composition instead of object inheritance. To elaborate briefly how we could go about using composition, we could construct a separate class to hold the implementation detail for the flying behaviour. To instantiate a new Duck instance, we will then initialise it with the flying behaviour object where the flying behaviour object is held as an instance variable within the Duck class. In other words, we could include a behavior setter methods in the Duck class so that we can even modify and set the Duck class to contain an alternative flying behaviour at run time.
Interface Segregation Principle …
Depending on something that carries other methods that you do not use or need might cause more troubles.
Lets say we have 3 users who uses the OPS class. User1 uses op1 method, User2 uses op2 method and User3 uses op3 method. In this case, the source code of User1 will inadvertently depend on op2 and op3, even though it doesn’t call them. For eg, a change to the code of op2 will force User1 to be recompiled and redeployed even though nothing that it cared about has actually changed.
This problem could be resolved by segregating the operations into interfaces.
U1Ops one = new OPS();
In general, it is harmful to depend on modules that contain more than you need.
Another explanation from Wikipedia: is what is today called the Interface Segregation Principle. was all implemented by the Job class.
Avoid God Classes!
Differences between ISP and SRP
In SOLID, what is the distinction between SRP and ISP? (Single Responsibility Principle and…
SRP tells us that you should only have a single responsibility in a module. ISP tells us that you should not be forced…
stackoverflow.com
A “client”, as intended by Gang of Four definitions, is a class that implements an interface.
As quoted from the Stack Overflow answer above …
To be fair, they are both different views on the same idea — SRP is more focused on the designer-side point-of-view, while ISP is more focused on the client-side point-of-view.
ISP can be seen as similar to SRP for interfaces; but it is more than that. ISP generalizes into: “Don’t depend on more than you need.” SRP generalizes to “Gather together things that change for the same reasons and at the same times.”
Imagine a stack class with both push and pop. Imagine a client that only pushes. If that client depends upon the stack interface, it depends upon pop, which it does not need. SRP would not separate push from pop; ISP would.
Dependency Inversion Principle …
The most flexible systems are those in which source code dependencies refer only to abstractions, not to concretions. Although exceptions can be made to classes that we know to be stable. For example, the Java String class.
If we change an abstract interface, we will need to make a change to its concrete implementations. Conversely, changes to concrete implementations of a class do not necessarily require a change to its corresponding interface. For this reason, interfaces are often kept more stable than implementations and engineers often avoid changing them.
Rules
- Refer to abstract interface.
- Do not inherit from volatile concrete classes. Use inheritance with care.
- Do not override concrete functions.
Inevitably, we have to initialise concrete classes. We cannot avoid this! We usually use factories to create objects since the creation of an object with the new keyword is a source code dependency on the concrete definition of the object.
The abstract components -> high level business rules. The concrete components (bottom half) has all the implementation details.
The concrete component contains a single dependency, so it violates the DIP. This is ok. DIP cannot be entirely removed, but can be gathered into a small number of concrete components and kept separate from the rest of the system. | https://liverungrow.medium.com/solid-design-principles-11578871e54d?source=post_page-----11578871e54d-------------------------------- | CC-MAIN-2021-39 | refinedweb | 1,960 | 64.41 |
The. In the example below we shall make a basic example that reads the temperature and outputs via serial and can be verified using the serial monitor in the Arduino IDE.
Lets look at the parts list
Parts List
Layout
As always be careful not to get the connections incorrect, you can refer to the pinout for the device below to help . The DS18B20 can be powered by between 3.0V and 5.5V so you can simply connect its GND pin to 0V and the VDD pin to +5V from the Arduino Duo.
Here is the connection diagram showing how to connect your arduino to the resistor and sensor.
Coding
You need to download 2 libraries and copy them into your Arduino libraries folder.
Dallas 18b20 Temperature Library
“1-Wire” Library
Now copy and paste this into a new sketch
#include <OneWire.h> #include <DallasTemperature.h> //the pin you connect the ds18b20 to #define DS18B20 2 OneWire ourWire(DS18B20); DallasTemperature sensors(&ourWire); void setup() { Serial.begin(9600); delay(1000); //start reading sensors.begin(); } void loop() { //read temperature and output via serial sensors.requestTemperatures(); Serial.print(sensors.getTempCByIndex(0)); Serial.println(” degrees C”); }
When you upload the sketch, go to Tools -> Serial Monitor and you should see something like the following. Put your finger on the DS18B20 and you should see the temperature vary.
Links
DS18B20 links
Buy DS18B20 from Amazon UK
Buy DS18B20 from Amazon US | http://arduinolearning.com/learning/basics/ds18b20-temperature-sensor.php | CC-MAIN-2020-29 | refinedweb | 237 | 56.55 |
Created on 2009-07-17 19:06 by terry.reedy, last changed 2010-07-09 15:11 by eric.araujo. This issue is now closed..
Copying my suggestion (minus examples) over from the python-ideas thread:
We could define it as trying the three modes in order (first 'eval',
then 'single', then 'exec') moving on to the next option if it raises
syntax error:
from dis import dis
def dis_str(source):
modes = ('eval', 'single', 'exec')
for mode in modes:
try:
c = compile(source, '', mode)
break
except SyntaxError:
if mode is modes[-1]:
raise
return dis(c)
As I explained on python-ideas, 'single' should not be tried.
As per Georg's suggestion, a better approach would look like:
from dis import dis
def dis_str(source):
try:
c = compile(source, '', 'eval')
except SyntaxError:
c = compile(source, '', 'exec')
return dis(c)
Trying both 'eval' and 'exec' looks fine to me.
Marking 'easy' because I expect it should be ;-)
I've made a patch, which adds a disassemble_str function to the dis module. The dis.dis function calls this function if x is a string. Added the following sentence to the documentation: "Strings are first compiled to code objects with the :func:`compile` built-in function." Added two simle unittests.
+1
Any chance, that my patch will be accepted? Is there a problem with it?
Thanks.
disassemble_str should be private with an underscore.
Done. Attached new patch as issue6507_2_priv.diff.
Missed the window for 2.7, but should be right for 3.2.
There's a minor error in the documentation (strings need to be mentioned in the list of acceptable types), but I can fix that on commit.
> disassemble_str should be private with an underscore.
disassemble_string should've been private as well, while we are editing this module.
> disassemble_string should've been private as well, while we are editing this module.
Attached the updated patch.
Just today, someone posted the result of dis.dis('somebytes') and did not notice the error because dis blithely disassembles bytes as bytecodes, even in 3.x. (The person actually dissed a 2.x string).
>>> from dis import dis
>>> dis(b'cat')
0 DUP_TOPX 29793
It is a natural thing to do, so I hope this is put in 3.2.
Since the undocumented 'disassemble_string' now disassembles bytes, I think it should be renamed '_disassemble_bytes' instead of '_disassemble_string'. This would accord with the general effort to remove 2.x fossils from 3.x.
Aside from that, it looks ready, from a reading review, to apply and test: doc addition, added tests, new function and else case, and rename.
Committed (with some minor modifications) in r82471.
Inspired by Yanov Aknin's ssc() tool, I've opened a new RFE (issue 9147) for a similarly enhanced show_code() implementation. | https://bugs.python.org/issue6507 | CC-MAIN-2019-43 | refinedweb | 459 | 65.73 |
Opened 2 months ago
Last modified 5 weeks ago
#16643 new defect
integrate() problem
Description (last modified by nbruin)
I interrupted Sage after 5min of churning without result:
sage: f=diff((tan(x)+x)*e^tan(x),x) (tan(x)^2 + 1)*(x + tan(x))*e^tan(x) + (tan(x)^2 + 2)*e^tan(x) sage: integrate(f,x)
On a faster computer:
sage: %time integrate(f,x) CPU times: user 3min 58s, sys: 50 ms, total: 3min 58s Wall time: 3min 58s integrate((tan(x)^2 + 1)*(x + tan(x))*e^tan(x) + (tan(x)^2 + 2)*e^tan(x), x)
On the other hand, for the equivalent expression
sage: g=e^tan(x)*sec(x)^2*(tan(x)+x)+e^tan(x)*(sec(x)^2+1) sage: %time integrate(g,x) RuntimeError: ECL says: In function CAR, the value of the first argument is 0 which is not of the expected type LIST
which happens in maxima/ECL with abs_integrate loaded, but not in maxima/SBCL. Upstream:
Change History (7)
comment:1 Changed 2 months ago by nbruin
comment:2 Changed 2 months ago by nbruin
The following helps perhaps to locate the problematic code. The following fragment does complete (but after considerable time):
from sage.interfaces.maxima_lib import * args=((tan(x)^2 + 1)*(x + tan(x))*e^tan(x) + (tan(x)^2 + 2)*e^tan(x), x) expr=EclObject(([max_integrate],[sr_to_max(SR(a)) for a in args])) result=maxima_eval(expr) max_to_sr(result)
this is the code the integrator would execute, and it does return the integral unevaluated. So somehow we're avoiding the error above.
Indeed, the difference seems to be how you feed the expression. Sage actually DOES return this integral (unevaluated), it just takes longer. The difference is in how you give the integral. The expression for the derivative that maxima computes gives the result above. However, the form computed by sage still works. If you do in maxima
... (%i6) f: (tan(x)^2 + 1)*(x + tan(x))*exp(tan(x)) + (tan(x)^2 + 2)*exp(tan(x)); (%o6) %e^tan(x)*(tan(x)^2+2)+%e^tan(x)*(tan(x)+x)*(tan(x)^2+1) (%i7) integrate(f,x); (%o7) 'integrate(%e^tan(x)*(tan(x)^2+2)+%e^tan(x)*(tan(x)+x)*(tan(x)^2+1),x)
everything is fine.
So the only report for Maxima is the above question why ECL runs into an error for the particular integral given there. This integral is not the one encountered with the original sage script and the sage code does finish correctly (albeit after a rather long time).
comment:3 Changed 2 months ago by nbruin
I changed the title and description, because I found evidence there is no infinite loop involved. Please change back if you're unhappy with the change.
comment:4 Changed 2 months ago by nbruin
comment:5 Changed 2 months ago by nbruin
comment:6 Changed 2 months ago by kcrisman
- Report Upstream changed from N/A to Reported upstream. No feedback yet.
comment:7 Changed 5 weeks ago by vbraun_spam
- Milestone changed from sage-6.3 to sage-6.4
This may be a reportable issue upstream:
Without the load(abs_integrate) the code seems to execute fine (by returning the integral unevaluated). This does not fully explain why sage seems to get stuck on it, though. Perhaps a try/except that is a little too agressive in suppressing problems?
Also, the problem does not arise in Maxima 5.30.0 on SBCL 1.1.8-2, so it may be a problem with maxima-ecl interaction (so it depends a little on how well the maxima-devs want to support ECL)
Also executing domain: complex;load(to_poly_solve);load(simplify_sum); (as we do in sage) doesn't affect the outcome. | http://trac.sagemath.org/ticket/16643 | CC-MAIN-2014-41 | refinedweb | 632 | 52.9 |
User talk:Cormaggio/Archive 2
Contents
- 1 History of Quebec and Canada Study Guide
- 2 Towards improving the New User Experience
- 3 Thanks
- 4 @
- 5 Bricks and Mortar
- 6 Using Javascripts
- 7 UIUC PHIL 270
- 8 Re: Degree programs
- 9 Goals for the filmmaking lessons
- 10 New Cover for Podcast
- 11 Newcomer feedback
- 12 Global Text Project
- 13 Examples of good content
- 14 re: Newcomers page
- 15 Audio Engineer
- 16 Educational Expertise is Needed
- 17 History of Wikiversity formation
- 18 Honesty/Integrity
- 19 The name
- 20 Handout Tests
- 21 Go to sleep
- 22 Becoming an admin.
- 23 Idea of a treasure hunt
- 24 On reflective practice
- 25 Yet another application: Flashcards
- 26 Pyridinoline
- 27 Talk:Learning to learn a wiki way
- 28 Music/Software/Programming drums
- 29 New user needs mentor
- 30 Bureaucrats
- 31 search comments in my blog
- 32 Thanks
- 33 OLPT
- 34 Nice to meet you
- 35 candidate for probationary custodianship
- 36 Cheers, nice to meet you...
- 37 Merging two pages
- 38 Dynamic Page List
- 39 A sentence in wikiversity:approved Wikiversity project proposal#Research
- 40 PPT files
- 41 More details on my request (Subject of emails)
History of Quebec and Canada Study Guide[edit]
Hi Cormac. Thanks for your input. The page (article) you quote is a link from the main page. From there you link to the various Modules and Topics. The structure is: start at the Main Page, select a module, review each topic, return to the main page, select a new module. As a nubie I linked to newly named articles or pages. Is there any other way? thanks --Mikec 00:08, 10 October 2006 (UTC)
Towards improving the New User Experience[edit]
I think I can help most by working on the new user experience. Over the past couple of days I've been stumbling on useful bits and pieces here and there. They need to be drawn together and expanded, and then repositioned. I'm pretty good at this kind of stuff and believe (with help from yourself and others) I could make a meaningful contribution.
However I'm such a newbie I'm not yet clear on the mechanics.
For instance, I would propose there be a clearly defined channel for new users to help them get up to speed. And that the entrance to that channel be unambiguously presented on the Wikiversity's main page. In effect, present those who have yet to log in with a fork — returning visitor for announcements, new developments and the like; or go to a guided new visitor pathway.
I suspect such a revision to the presentation of the Wikiversity's main page might be welcome. But before I put energy into it I'd like that confirmed.
In developing such an alternative new user channel it would be useful to draft it in relative obscurity, where you and others could review it, revise it, expand it, reshape it, before dropping it onto the general public via the Main Page. No sense in adding to existing confusion.
So, what should be in this new user channel?
1. A clear, brief definition of what the Wikiversity is, and what what it is not — with a link to an extended discussion on the objectives.
2. A similar brief description of the organization of the Wikiversity and how it will go about achieving its objectives. Again with a link into extended detail.
3. A summary of the current status of the project with a link to representative samples.
4. A discussion of options on how to become involved — as a student, as a teacher, as an organizer. Again, with recommended links.
In summary, a tight overview of the essentials as orientation, with pathways to dig deeper and deeper in an orderly, non-overwhelming fashion. An end to mud, the appearance of being inactive and vague.
As I've now discovered, much of this material already exists, somewhat. But it's incomplete and it's scattered. And definitely not up front. I very much appreciate the user page you set up for me. The links there themselves form the core of what I have in mind.
If the above meets with your approval, tell me how to set up such a "sandbox" arena. Or give me guidance on how you would rather I proceed.
Kind regards,
Morley 20:22, 10 October 2006 (UTC)
Thanks[edit]
Thanks for your kind comment. I'm just trying to help where I can. To be honest, I've spent way more time here than I can afford. I just really enjoy the prospect of being involved here. The Jade Knight 02:44, 11 October 2006 (UTC)
- I'm a student finishing up my degrees in English and History. I actually have a very intense semester right now, and as much self-control as I can muster will keep me doing homework rather than helping out here. Unfortunately, as my contribution record will show, self-control's been fighting a losing battle lately. =þ The Jade Knight 16:14, 11 October 2006 (UTC)
@[edit]
Hey there! Just trying to get back to you about this. I was smiling a little bit at the subject of your message too. How fitting! Anyway, obfuscating an e-mail address makes it more difficult for it to be harvested by spammers. It doesn't prevent it entirely. It would be just as easy for a programmer to add a line or two of code to check those alternatives, although, what would happen is that it would take more time to do the processing...I just thought it would look nicer to be consistent, that was all. :-) --HappyCamper 20:39, 12 October 2006 (UTC)
Bricks and Mortar[edit]
Hi! I am referring to your comment on School:Strategic Studies a while back. Yes, I and my writings are both linked to bricks-and-mortar institutions. You can find the link to my old school at the bottom of the School: page, and some of my personal info on my user page. Cheers!--Dnjkirk 15:36, 16 October 2006 (UTC)
Using Javascripts[edit]
I would like to use javascripts for some of my module tests. It seems from my research that I need permission. Could you arrange this?--Mikec 01:57, 17 October 2006 (UTC)
UIUC PHIL 270[edit]
The UIUC PHIL 270 discussion, here presents an important precedent I think. I set forth what I think is a bit of diplomacy on Talk:UIUC PHIL 270 in case the poster returned. At any rate, this potential problem should be anticipated by the staff. Maybe we can come up with a polite but firm template and a sort of "jail" for orphaned pages that are suspect as cheatsheets or other malfeasance?
IMO, the tone should be one of simple caution rather than stern warning and certainly not accusational in any way. I can't imagine why or how anyone would want to abuse Wikiversity, but you never know. The prospect of a negative news report is a real concern in my mind, and should be dealt with immediately. I've notified all the posters who commented about the UIUC PHIL 270 piece, saving you and JWSurf for last. I think this should float toward the top of policy discussions. I'll present it also at Wikiversity:Request custodian action 'cuz I think it needs action.
Practicum:Multilingualism (example) – I know you're quite busy, but I've also proposed another maybe namespace (or something) that can platform for PAR, based on action, empowerment, participation, and critical reflection. I think this meshes well with the pedagogy of "real-world" academia. Just thinking out loud. This idea is also heading for Wikiversity:Request custodian action.
We're looking really good here Cormac! Great Work! CQ 03:07, 19 October 2006 (UTC)
Re: Degree programs[edit]
Most of the research I've been doing has been into local degree programs and how they would relate to online materials. I've been trying to find a means to obtain accreditation from local colleges or universities through independent online studies. Something akin to Excelsior portfolio based assessment. I've yet to find anything online on how a portfolio should be formatted and what information a portfolio should include. I've also yet to find out what institutions outside of Excelsior et al would allow such an assessment.
Sorry, forgot to sign my post RichMac 02:17, 18 October 2006 (UTC)
Goals for the filmmaking lessons[edit]
Currently, I am roughing out the basic outline of the first ten lessons. This will take about two months. Then I will be able to stop and take a look at the direction that the film school is going. For now, it is just rough chicken scratchings which are changing direction from day to day. Therefore, serious planning should wait for a few months until I finish experimenting with the possibilities. Thanks for your encouragement. Robert Elliott 16:01, 20 October 2006 (UTC)
New Cover for Podcast[edit]
I changed the "cover" image for the podcast introduction to School: and Topic: namespaces. --JWSchmidt 00:48, 21 October 2006 (UTC)
Newcomer feedback[edit]
Just saw your posting on the Colloquium. Actually I'm so new around here I didn't know what to think. But I certainly didn't want to expend energy on a project like this just to find myself in the midst of some turf war.
Not so much hurt as being unsure what ground I was/am standing on. Your clarification has got me back on track. Recently I came into free time to devote to a project of interest (like helping out here). I just want to make a positive difference in whatever I engage in. (Turf wars ain't it.)
To be practical about this, I need a guide from a more experienced hand. For instance, in how to track who's edited a page and engage them in dialogue. Or answers to wiki syntax questions. This sort of thing. I notice the Wikipedia has something called Projects. I suspect the Newcomers section might benefit from something similar.
Just so the "live" newcomers page doesn't become a problem for actual new users, I'm placing my edits towards the bottom of the page.
Didn't realize until just now individual pages (such as the Newcomers page) can have a talk page. That will be useful. morley 21:06, 23 October 2006 (UTC)
- Thanks for the feedback and vote of confidence. I have some experience in writing computer code, so I'm pretty familiar with learning syntax by experimentation and comparison, but also by asking dumb questions in discussion forums.
- There were a few sections in your lengthy post that felt they have merit on editing "how to" pages themselves. I'll do that soon.
Global Text Project[edit]
hi
I saw your message about opportunities to collaborate.
Let's talk
Rick Watson <mailto:[email protected]>
Examples of good content[edit]
To quote you back to yourself, on the Colloquium, early October.
- We need, in general, a collection of links to good content in one page - akin to the featured articles on Wikipedia. We should not only guide people to good educational material in a specific area, but also give examples of specific types of material, eg. quizzes, interactive "games", activities such as "fill-the gap", essays, research projects etc.
I vigorously agree.
Question: How does the Wikipedia manage this? Are there any particular mechanics used over there to keep the content current and fresh?
morley 22:52, 5 November 2006 (UTC)
re: Newcomers page[edit]
I've added a fair bit to the Newcomers page, including a quote on cheating from a discussion on the Colloquium. I suspect it's all all right, but I'd appreciate it if you'd review the page. Thanks.
morley 02:40, 6 November 2006 (UTC)
Audio Engineer[edit]
This all depends on what kind of non-instrument you mean. If you mean vocals, the yes i have background. If you mean midi then I have some background, but not too much. I could however, point you in the right direction.
In that case, yes I can help you quite a bit. I'd be more than glad to upload a file and tutorial if you give me an idea of what you'd like your soundscape to be. If you want a new-age type ambient song, then you'll need a keyboard or a midi sequencer. (I use live 6's midi sequencer, but GarageBand and many other programs have better midi sequencers). Or if you want to just record non-instrument sounds, you can do this with any microphone a computer and a few other items to maximize quality. Let me know which one of these you mean, and I'll be more than glad to write up a tutorial. I've never heard of Reason, but I'll check it out.
guitarlord71 7 November 2006 8:44 EST
Educational Expertise is Needed[edit]
Cormaggio I hope things are going well with your dissertation. I have started a open source game design and production learning trail and eventually we will need some expertise on how to include some learning and refresher material to make it worth while for game enthusiasts to play. I have a couple of concepts regarding how to get them playing with math balancing equations. If you could drop by[1] anytime in the next few months and consult with us on educational issues in games or "edutainment" and provide a few high quality links to free online technial papers or applicable journal it might give our learning trail a serious boost! Thanks! Mirwin 08:38, 7 November 2006 (UTC)
- Thanks for the html formatting work! It was above and beyond the call of duty requested. I have answered some of your questions at the talk page. Hopefully some others will chip in soon. Within a few weeks I will visit a few modding and modeling sites I know and invite some artists and developers to drop by. Mirwin 14:13, 7 November 2006 (UTC)
History of Wikiversity formation[edit]
Is there a page on how Wikiversity came to be? Don't want to start one if such already exists.
morley 00:43, 8 November 2006 (UTC)
Honesty/Integrity[edit]
I suggested honesty and integrity as an over-reaching principle because in wikiversity we need to know that we are in companies that we can trust. It may be related to civility but it is different. We need this line because, in contrast to wikipedia, it is sometimes difficult to tell whether somebody is honest or not. Thus the honour code (do not intentionally deceive) is much more important here.
For example, a liar in Wikipedia will not cause much damage; the faults he introduces would be deleted either because somebody knows that it is wrong, or because nobody can understand it. But on Wikiversity, it is not always as easy.
I would put honesty before everything else. And I am against merging honesty with civilty. --Hillgentleman 04:17, 10 November 2006 (UTC)
- On honesty, I agree that it should be an over-riding principle (or "code"), but I'm interested in why you see Wikiversity as being so different from Wikipedia in this regard. Why do you see it as more difficult to deal with dishonesty here?
- Since more freedom is allowed on wikiversity. Some fake articles may appear on wikiversity, which is beyond anybody on wikiversity to point out the mistake. On wikipedia, it would just be deleted, because it cannot be supported. On wikiversity, we might have to keep it until somebody finds out the mistake. This is okay if the mistake was unintentional, and often the mistake can be corrected and it would become a contribution to the society. But if it were a hoax, then it would have wasted the time of many readers in the mean time. And I have not heard of wikipedians being banned because of intentionally deceiving.
- I am not sure if Civility and disclosure cover such grounds. --Hillgentleman 23:21, 10 November 2006 (UTC)
The name[edit]
Cormaggio, how did wikiversity arrive at its name?--Hillgentleman 19:03, 11 November 2006 (UTC)
- I think the name was thought up first, and the concept developed around it. Someone name Ray proposed the name (not me).--Rayc 19:55, 11 November 2006 (UTC)
- That'd be Ray Saintonge (User:Eclecticology, mainly at Wiktionary) - though it was also proposed at around the same time by someone else on the Textbook mailing list.. Cormaggio 20:48, 11 November 2006 (UTC)
Handout Tests[edit]
My lastest invention! Handout_tests! What do you think? Would they be useful?--Rayc 19:55, 11 November 2006 (UTC)
- Yes, colabortive test taking... I had to say something since there is nothing keeping students from looking at how other people answered. Maybe we need an encryption system--Rayc 23:03, 11 November 2006 (UTC)
Go to sleep[edit]
Hiya! I think it's better you to go to bed :-) Talvikki 00:10, 14 November 2006 (UTC)
Becoming an admin.[edit]
Hi. I'm an administrator on Wikipedia. And I was wondering if that would make me an automatic admin, on Wikiversity. Thanks. -- drini 22:12, 14 November 2006 (UTC)
Thanks alot for the message. -- drini 21:31, 15 November 2006 (UTC)
I wouldn't like to nominate myself but rather BE nominated by SOMEONE else.tHANKS -- drini 21:43, 15 November 2006 (UTC)
Idea of a treasure hunt[edit]
This is an idea of an idea. It may not work. When wikiversity has gained sufficient content, we can use a group game of treasure hunt to study its complexity, and it could serve as a simple example for original research if we set it up right and document it properly. The game would be a set of questions to be answered and tasks to be done. The hints and information would be inside wikiversity. Participants should probably also report their routes. Points are deducted if they use google or the recent changes page. The winner gets a barnstar or something. The purpose of this study is to see if wikiversity is easy to use, especially for new-comers. C.f. --Hillgentleman|User talk:hillgentleman 11:25, 23 November 2006 (UTC)
- Dear Cormaggio, I have a rough list of questions at User:Hillgentleman/study2. Please feel free to add more. I shall cut it into a reasonable size later. Or I would add more when more schools start functioning. --Hillgentleman|User talk 12:56, 8 December 2006 (UTC)
On reflective practice[edit]
Hi Cormac sorry it's taken me so long to get back to you I've only recently returned to the Wikiversity. I'm keen to work with you on all the projects that you have written to me about.
Learning to learn a wiki way[edit]
I think we need to recruit some interested parties and then clarify what social practice at Wikiversity we want to make interventions to. Then plan out our interventions and carry them out.
School of Education[edit]
There's lots of work needs doing here. I think a clear strategy would help. We could invite interested parties to contribute there fantasy School of Education or even run it as a competition.
Reflective Blogg[edit]
This particular blogg would be about my practice at Wikiversity as both consumer and producer of content. Mystictim 01:22, 24 November 2006 (UTC)
Yet another application: Flashcards[edit]
I finally bugged the devs into telling me how to make a random number, the result can be seen here: Flashcards for Java keywords. I'm thinking of expanding on the concept to have it randomly create a test for a subject, though I would need a pre-formatted list of questions.--Rayc 20:27, 24 November 2006 (UTC)
- You just click the "get new card" link and the card will update randomly from the list.--Rayc 18:21, 25 November 2006 (UTC)
Pyridinoline[edit]
Hi Andrew, I tried answering your query on Wikiversity:Help desk, but it's not much good - might point you in the right direction though.. Cormaggio talk 15:46, 25 November 2006 (UTC)
- Thanks very much. I'll copy the discussion to Wiktionary. Andrew massyn 05:25, 26 November 2006 (UTC)
Talk:Learning to learn a wiki way[edit]
Hi Cormac:33, 28 November 2006 (UTC)
Music/Software/Programming drums[edit]
Hi as you requested , i created a flash video tutorial on programming drums with an embeded finished loop , i used the "upload file section of the site but after sending the fille got a message"swf is not a recomended image format" how would i go about attaching the small flash file to the actual wiki page ? im a noob :) midiscore
hi i created a short flash video tutorial that might clear things up aswell as a short mp3 of the programeed drum loop...im not sure how to tie the two to my tutorial ..after uploading the 2 files i got a messas ge the the format of the files is not a preffered image format ..pls help me sort it all out midiscore
New user needs mentor[edit]
I'm new to editing Wiki articles and was surprised to discover Wikiversity. I'm studying for a Master's degree in music composition in Korea (though I'm from America. I'm also a teacher. You can hear samples of my compositions over at myspace.com/gongchime. I don't really know how I can become involved so that's why I'm talking to you. What needs to be done?
Thanks
Greg Turner
- Thanks Greg! I'm fascinated in your studies, and would love to find out more. As to what needs to be done, that really depends a lot on you, and what you want to do. I suppose you could see School:Music and see if there are any pages there that spark your interest and that you'd like to add to - or perhaps there are topics that you are interested in that aren't yet represented and you'd like to add them and begin work on them. I can certainly go through specifics with you, but it might be easier if you logged in to Wikiversity and/or gave me an email address I could use to contact you - I need to be registered to message you on Myspace.. Cheers! Cormaggio talk 00:11, 5 December 2006 (UTC)
Bureaucrats[edit]
So, I am not sure where else to take this discussion about bureaucrats and such. What are your thoughts? --HappyCamper 03:12, 9 December 2006 (UTC)
search comments in my blog[edit]
I answered your question about the search problem by writing a reply to User_talk:Mu301#Blog.--mikeu 18:19, 12 December 2006 (UTC)
Thanks[edit]
- Thanks for cleaning up the Russian Revolution course! Gabriel Spiro 04:16, 13 December 2006 (UTC)
OLPT[edit]
- Thanks for looking at our OLPT paper. We are currently cutting the .doc file down from 10 to 6 pages so that we submit it. Please revisit. Something special has happened here. --Ian Kennedy 05:37, 14 December 2006 (UTC)
Nice to meet you[edit]
Hi,
Yes - I am Teemu Leinonen from Helsinki () and very interested in to learn more about Wikiversity. --Teemu 14:34, 15 December 2006 (UTC)
candidate for probationary custodianship[edit]
Please consider this candidate: Wikiversity:Candidates for Custodianship/J.Steinbock. Thanks. --JWSchmidt 14:46, 16 December 2006 (UTC)
Cheers, nice to meet you...[edit]
- Hi, thanks very much. It's such a great place. I would really like to help with Wikiversity the Movie, however I don't see any scripts or video's or anything yet. When will those be ready?At the moment I'm just adding content to some of the music theory pages, but I'd love to collaborate on a course in film scoring. What kinds of media are you interested in? Aidan 13:28, 16 December 2006 (UTC) - (I live in Canterbury, Kent) (User:Taeke)
Merging two pages[edit]
Hi Cormac hope things are going well with you. I wonder if you could help me out. I was attempting to merge the pages Introduction to Psychology and School:Psychology/Psy 1001 by copying the contents of psy 1001 into Introduction to psychology as suggested at W:Merging and moving pages however this resulted in the loss / occlusion of the edit history. Someone said in another post that this is a breach of the GFDL. Is this the correct way to merge articles or is their some other method. Mystictim 00:03, 19 December 2006 (UTC)
- Thanks for your answer I'm leaving it with the page editors for now. However I'll add your comments to the help page for merging pages linking to the template. Mystictim 13:52, 20 December 2006 (UTC)
Dynamic Page List[edit]
Hi Cormac would it be possible to have this extension added to Wikiversity? I think it would be very useful in all kinds of context. See dynamic page lists for more information. Mystictim 23:56, 20 December 2006 (UTC)
A sentence in wikiversity:approved Wikiversity project proposal#Research[edit]
- Cormaggio: I am translating the proposal into 中文.
Quote: There will not necessarily be "approval" of research added to Wikiversity - though some sort of review process needs to be established which will deal with potential problems.
- The first sentence: Does it mean that there may not be research at all? Or that research need not always be approved?
- The second sentence: To what does review process refer? Reviewing the particular studies as in wikiversity:review board, or reviewing the whole wikiversity project on meta?
--Hillgentleman|Talk 20:05, 25 December 2006 (UTC)
- P.S. If you have time, you may try the test. It may be a little rough and down-to-date. -Hillgentleman|Talk 20:06, 25 December 2006 (UTC)
PPT files[edit]
Oh, this is simple to do for anyone with shell access - I'll look into this now.. <--- This is a commment you made on my talk page. Could you get back to me once you look into it? -- J.Steinbock 20:40, 26 December 2006 (UTC)
- Okay. I won't be doing too much either until the whole holiday season is over. Thanks for the reponse. :) -- J.Steinbock 22:12, 28 December 2006 (UTC)
More details on my request (Subject of emails)[edit]
- Previously, I wrote
When I use the Special Page for a student to email me (by adding "[[Special:Emailuser/Robert_Elliott | Click here to send me an email]]" to my lesson), can I get something other than "Wikiversity e-mail" in the subject of the email. Can I get a subject such as "Wikiversity e-mail about the second question on the fourth lesson"? (You can send me the answer by clicking here to send me an email.) Robert Elliott 00:47, 27 December 2006 (UTC)
- You replied
- Hi Robert, the email subject is editable by the person who sends you a message, but it is not possible to customise the default subject of a specific message. MediaWiki:Defemailsubject is set to "Wikiversity e-mail" - this can be changed (by a custodian), but it would affect every message across the whole wiki. I asked on IRC about customising a message for you only, and the response I got was: "not possible at this time (and possibly not ever)". Sorry :-( Cormaggio talk 15:47, 29 December 2006 (UTC)
- A simple solution
- Current, the syntax is [[Special:Emailuser/Robert_Elliott | Click here to send me an email]].
- What I want is [[Special:Emailuser/Robert_Elliott | SpecialSubject:Answer for Question 2 | Click here to send me an email]].
I just want a simple method to override the default message. Robert Elliott 15:32, 3 January 2007 (UTC)
- I have created {{email}} for you. Please let me know if that will work for you. sebmol ? 20:33, 3 January 2007 (UTC)
- It works great!!!! Thanks! Robert Elliott 16:23, 4 January 2007 (UTC)
- Attention Instructors!!!
- Click here to see the new help page which explains how to use this new email feature/template to set up ways for your students to eMail you. | https://en.wikiversity.org/wiki/User_talk:Cormaggio/Archive_2 | CC-MAIN-2019-43 | refinedweb | 4,718 | 63.19 |
On 04/22/2011 09:48 AM, Suresh Srinivas wrote:
> A few weeks ago, I had sent an email about the progress of HDFS
> federation development in HDFS-1052 branch. I am happy to announce
> that all the tasks related to this feature development is complete
> and it is ready to be integrated into trunk.:
first datanode process configuraton
fs.default.name = hdfs://nn1/
dfs.data.dir = /drive1/nn1/,drive2/nn1/...
second datanode process configuraton
fs.default.name = hdfs://nn2/
dfs.data.dir = /drive1/nn2/,drive2/nn2/...
...
Then symlinks could be used between nn1, nn2, etc to provide a
reasonably unified namespace. From the benefits listed in the design
document it is not clear to me what the clear, substantial benefits are
over such a configuration.
2. How much testing has been performed on this? The patch modifies much
of the logic of Hadoop's central component, upon which the performance
and reliability of most other components of the ecosystem depend. It
seems to me that such an invasive change should be well tested before it
is merged to trunk. Can you please tell me how this has been tested
beyond unit tests?
Thanks!
Doug | http://mail-archives.apache.org/mod_mbox/hadoop-hdfs-dev/201104.mbox/%[email protected]%3E | CC-MAIN-2014-52 | refinedweb | 195 | 56.76 |
Subsets and Splits